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 |
|---|---|---|---|---|---|---|---|---|---|---|
e721f5fc7481e7970ba5e281e37b426123b415c3 | ruledxml/tests/test_order.py | ruledxml/tests/test_order.py | #!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlForeach(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
ruledxml.run(src, utils.data('030_rules.py'), result)
... | #!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlOrder(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
ruledxml.run(src, utils.data('030_rules.py'), result)
wi... | Fix name: should be TestRuledXmlOrder, not TestRuledXmlForeach. | Fix name: should be TestRuledXmlOrder, not TestRuledXmlForeach.
| Python | bsd-3-clause | meisterluk/ruledxml | ---
+++
@@ -8,7 +8,7 @@
from . import utils
-class TestRuledXmlForeach(unittest.TestCase):
+class TestRuledXmlOrder(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src: |
5a8f107f987198740a0f0b9f1ee1f79d90662109 | txircd/modules/rfc/cmode_n.py | txircd/modules/rfc/cmode_n.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class NoExtMsgMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class NoExtMsgMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "... | Fix mode +n specification so that it actually fires ever | Fix mode +n specification so that it actually fires ever
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd | ---
+++
@@ -18,8 +18,8 @@
return [ ("n", ModeType.NoParam, self) ]
def actions(self):
- return [ ("modeactioncheck-channel-n-commandpermission-PRIVMSG", 1, self.channelHasMode),
- ("modeactioncheck-channel-n-commandpermission-NOTICE", 1, self.channelHasMode) ]
+ return... |
3ff9f60e857c9ffbd7c72c53403ae7bf3afecab8 | test/features/steps/system.py | test/features/steps/system.py | from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
... | from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
... | Fix OS X test skip. | tests.features: Fix OS X test skip.
| Python | bsd-3-clause | hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure | ---
+++
@@ -33,7 +33,8 @@
@then('{exe} is a static executable')
def step_impl(ctx, exe):
if sys.platform.lower().startswith('darwin'):
- context.scenario.skip("Static runtime linking is not supported on OS X")
+ ctx.scenario.skip("Static runtime linking is not supported on OS X")
+ return
... |
1dfe45d9ce6c81e5ae2396f97cc979192251c906 | selectable/apps.py | selectable/apps.py | try:
from django.apps import AppConfig
except ImportError:
AppConfig = object
class SelectableConfig(AppConfig):
"""App configuration for django-selectable."""
name = 'selectable'
def ready(self):
self.module.registry.autodiscover()
| try:
from django.apps import AppConfig
except ImportError:
AppConfig = object
class SelectableConfig(AppConfig):
"""App configuration for django-selectable."""
name = 'selectable'
def ready(self):
from . import registry
registry.autodiscover()
| Update auto-registration to work while running the tests. | Update auto-registration to work while running the tests.
| Python | bsd-2-clause | affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,affan2/django-selectable,mlavin/django-selectable,mlavin/django-selectable | ---
+++
@@ -10,4 +10,5 @@
name = 'selectable'
def ready(self):
- self.module.registry.autodiscover()
+ from . import registry
+ registry.autodiscover() |
96ace17d9cd800a5649ad32a8cb496a55d73ca9f | wapps/templatetags/wagtail.py | wapps/templatetags/wagtail.py | import jinja2
from django.conf import settings
from django_jinja import library
from jinja2.ext import Extension
from wagtail.wagtailcore.models import Page
from wagtail.contrib.wagtailroutablepage.templatetags.wagtailroutablepage_tags import (
routablepageurl as dj_routablepageurl
)
from wapps.utils import get_i... | import jinja2
from django.conf import settings
from django_jinja import library
from jinja2.ext import Extension
from wagtail.wagtailcore.models import Page
from wagtail.contrib.wagtailroutablepage.templatetags.wagtailroutablepage_tags import (
routablepageurl as dj_routablepageurl
)
from wapps.utils import get_i... | Fix is_site_root when no page | Fix is_site_root when no page
| Python | mit | apihackers/wapps,apihackers/wapps,apihackers/wapps,apihackers/wapps | ---
+++
@@ -19,7 +19,7 @@
@library.global_function
@jinja2.contextfunction
def is_site_root(context, page):
- if 'request' not in context or not context['request'].site:
+ if 'request' not in context or not context['request'].site or not page:
return False
site = context['request'].site
re... |
020ffbe8436da2f7ee654fa6a12d50f9915db17f | examples/collection/views.py | examples/collection/views.py | from cruditor.contrib.collection import CollectionViewMixin
from cruditor.views import CruditorAddView, CruditorChangeView, CruditorDeleteView, CruditorListView
from django.urls import reverse, reverse_lazy
from examples.mixins import ExamplesMixin
from store.models import Person
from .filters import PersonFilter
fro... | from cruditor.contrib.collection import CollectionViewMixin
from cruditor.views import CruditorAddView, CruditorChangeView, CruditorDeleteView, CruditorListView
from django.urls import reverse, reverse_lazy
from examples.mixins import ExamplesMixin
from store.models import Person
from .filters import PersonFilter
fro... | Make use of auto generated table classes. | Make use of auto generated table classes.
| Python | mit | moccu/django-cruditor,moccu/django-cruditor,moccu/django-cruditor | ---
+++
@@ -19,7 +19,6 @@
class PersonListView(PersonViewMixin, CruditorListView):
title = 'Persons'
- table_class = PersonTable
def get_titlebuttons(self):
return [{'url': reverse('collection:add'), 'label': 'Add person'}]
@@ -27,6 +26,7 @@
class PersonFilterView(PersonListView):
f... |
4ce7f8ce338c84b44e7ad16475ff68bc0fad970e | dddp/accounts/tests.py | dddp/accounts/tests.py | """Django DDP Accounts test suite."""
from __future__ import unicode_literals
import sys
from dddp import tests
class AccountsTestCase(tests.DDPServerTestCase):
# gevent-websocket doesn't work with Python 3 yet
@tests.expected_failure_if(sys.version_info.major == 3)
def test_login_no_accounts(self):
... | """Django DDP Accounts test suite."""
from __future__ import unicode_literals
import sys
from dddp import tests
# gevent-websocket doesn't work with Python 3 yet
@tests.expected_failure_if(sys.version_info.major == 3)
class AccountsTestCase(tests.DDPServerTestCase):
def test_login_no_accounts(self):
soc... | Move expected test failure to TestCase class. | Move expected test failure to TestCase class.
| Python | mit | commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp | ---
+++
@@ -5,10 +5,10 @@
from dddp import tests
+# gevent-websocket doesn't work with Python 3 yet
+@tests.expected_failure_if(sys.version_info.major == 3)
class AccountsTestCase(tests.DDPServerTestCase):
- # gevent-websocket doesn't work with Python 3 yet
- @tests.expected_failure_if(sys.version_info.... |
02f7a546cda7b8b3ce31616a74f3aa3518632885 | djangocms_spa_vue_js/templatetags/router_tags.py | djangocms_spa_vue_js/templatetags/router_tags.py | import json
from django import template
from django.utils.safestring import mark_safe
from ..menu_helpers import get_vue_js_router
register = template.Library()
@register.simple_tag(takes_context=True)
def vue_js_router(context):
if context.has_key('vue_js_router'):
router = context['vue_js_router']
... | import json
from django import template
from django.utils.safestring import mark_safe
from ..menu_helpers import get_vue_js_router
register = template.Library()
@register.simple_tag(takes_context=True)
def vue_js_router(context):
if 'vue_js_router' in context:
router = context['vue_js_router']
else... | Use `in` rather than `has_key` | Use `in` rather than `has_key`
| Python | mit | dreipol/djangocms-spa-vue-js | ---
+++
@@ -10,7 +10,7 @@
@register.simple_tag(takes_context=True)
def vue_js_router(context):
- if context.has_key('vue_js_router'):
+ if 'vue_js_router' in context:
router = context['vue_js_router']
else:
router = get_vue_js_router(context=context) |
15bbe3aaaa017513ac652bf246b906139a71be00 | doc/tutorials/examples/general/client/headers.py | doc/tutorials/examples/general/client/headers.py | import base64
from pyamf.remoting.client import RemotingService
gw = RemotingService('http://demo.pyamf.org/gateway/recordset')
gw.addHTTPHeader('Set-Cookie', 'sessionid=QT3cUmACNeKQo5oPeM0')
gw.removeHTTPHeader('Set-Cookie')
username = 'admin'
password = 'admin'
auth = base64.encodestring('%s:%s' % (username, pass... | from pyamf.remoting.client import RemotingService
gw = RemotingService('http://demo.pyamf.org/gateway/recordset')
gw.addHTTPHeader('Set-Cookie', 'sessionid=QT3cUmACNeKQo5oPeM0')
gw.removeHTTPHeader('Set-Cookie')
username = 'admin'
password = 'admin'
auth = ('%s:%s' % (username, password)).encode('base64')[:-1]
gw.a... | Apply client authorization fix from wiki | Apply client authorization fix from wiki
git-svn-id: f3978d5834b2aa37aa734927aace4f0b92cf88c5@2985 2dde4cc4-cf3c-0410-b1a3-a9b8ff274da5
| Python | mit | cardmagic/PyAMF,cardmagic/PyAMF,cardmagic/PyAMF | ---
+++
@@ -1,5 +1,3 @@
-import base64
-
from pyamf.remoting.client import RemotingService
gw = RemotingService('http://demo.pyamf.org/gateway/recordset')
@@ -9,6 +7,9 @@
username = 'admin'
password = 'admin'
-auth = base64.encodestring('%s:%s' % (username, password))[:-1]
+auth = ('%s:%s' % (username, passwo... |
a3c3a6ed4d01f1857fc4728b10505e330af9e6ae | code/helper/easierlife.py | code/helper/easierlife.py | #! /usr/bin/env python3
""" Helper functions to make our life easier.
Originally obtained from the 'pharm' repository, but modified.
"""
import fileinput
import json
import os.path
from dstruct import Sentence
## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.path.realpath(__file_... | #! /usr/bin/env python3
""" Helper functions to make our life easier.
Originally obtained from the 'pharm' repository, but modified.
"""
import fileinput
import json
import os.path
import sys
from dstruct.Sentence import Sentence
## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.p... | Fix import, use fileinput.iput as context, and fix its argument | Fix import, use fileinput.iput as context, and fix its argument
| Python | apache-2.0 | amwenger/dd-genomics,rionda/dd-genomics,HazyResearch/dd-genomics,amwenger/dd-genomics,HazyResearch/dd-genomics,HazyResearch/dd-genomics,HazyResearch/dd-genomics,rionda/dd-genomics,amwenger/dd-genomics,HazyResearch/dd-genomics | ---
+++
@@ -7,8 +7,9 @@
import fileinput
import json
import os.path
+import sys
-from dstruct import Sentence
+from dstruct.Sentence import Sentence
## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.path.realpath(__file__))
@@ -23,12 +24,13 @@
yield (start, end... |
91aa7ed06d168700692a33fd3c51add585d60ac0 | backend/uclapi/roombookings/migrations/0007_auto_20170327_1323.py | backend/uclapi/roombookings/migrations/0007_auto_20170327_1323.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-27 13:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('roombookings', '0006_bookinga_bookingb_lock'),
]
operations = [
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-27 13:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('roombookings', '0006_bookinga_bookingb_lock'),
]
operations = [
... | Fix up migration to have only one PK | Fix up migration to have only one PK
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi | ---
+++
@@ -12,6 +12,16 @@
]
operations = [
+ migrations.AlterField(
+ model_name='bookinga',
+ name='slotid',
+ field=models.BigIntegerField(null=True, primary_key=False),
+ ),
+ migrations.AlterField(
+ model_name='bookingb',
+ ... |
61e30e91ffc87a7a8f575d32fba43e61a65b477a | bot/storage/data_source/data_sources/sqlite/sqlite.py | bot/storage/data_source/data_sources/sqlite/sqlite.py | from sqlite_framework.log.logger import SqliteLogger
from sqlite_framework.session.session import SqliteSession
from bot.storage.data_source.data_source import StorageDataSource
class SqliteStorageDataSource(StorageDataSource):
def __init__(self, database_filename: str, debug: bool, logger: SqliteLogger):
... | from sqlite_framework.log.logger import SqliteLogger
from sqlite_framework.session.session import SqliteSession
from bot.storage.data_source.data_source import StorageDataSource
class SqliteStorageDataSource(StorageDataSource):
def __init__(self, session: SqliteSession, logger: SqliteLogger):
super().__i... | Update SqliteStorageDataSource to receive the SqliteSession already built, so that clients can have more control over its construction | Update SqliteStorageDataSource to receive the SqliteSession already built, so that clients can have more control over its construction
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -5,9 +5,9 @@
class SqliteStorageDataSource(StorageDataSource):
- def __init__(self, database_filename: str, debug: bool, logger: SqliteLogger):
+ def __init__(self, session: SqliteSession, logger: SqliteLogger):
super().__init__()
- self.session = SqliteSession(database_filename,... |
9207009ae26324650f904b010a065d98c2f41300 | server/server/debug.py | server/server/debug.py | from django.http import HttpResponse
import json
class NonHtmlDebugToolbarMiddleware(object):
"""
The Django Debug Toolbar usually only works for views that return HTML.
This middleware wraps any non-HTML response in HTML if the request has a
'debug' query parameter (e.g. http://localhost/foo?debug) S... | from django.http import HttpResponse
import json
class NonHtmlDebugToolbarMiddleware(object):
"""
The Django Debug Toolbar usually only works for views that return HTML.
This middleware wraps any non-HTML response in HTML if the request has a
'debug' query parameter (e.g. http://localhost/foo?debug) S... | Drop wrap content starting with text/html | Drop wrap content starting with text/html
New versions of Django give HTML responses with the content type
'text/html; charset: utf-8'. We don't want to wrap that, so only check
for a start of text/html.
| Python | apache-2.0 | auvsi-suas/interop,auvsi-suas/interop,auvsi-suas/interop,justineaster/interop,justineaster/interop,justineaster/interop,auvsi-suas/interop,justineaster/interop,justineaster/interop | ---
+++
@@ -19,7 +19,7 @@
new_content = '<html><body>Binary Data, ' \
'Length: {}</body></html>'.format(len(response.content))
response = HttpResponse(new_content)
- elif response['Content-Type'] != 'text/html':
+ elif not response['Content-... |
023e814e6661c11bfe58a4e3e4ce4167ae63cd7f | rdio_dl/cli.py | rdio_dl/cli.py | import click
import youtube_dl
from .config import storage_load
from .extractor import RdioIE
@click.command()
@click.option(u'-u', u'--user', help=u'A Rdio user')
@click.option(u'-p', u'--password', help=u'The password')
@click.argument(u'urls', required=True, nargs=-1)
def main(user, password, urls):
storage = ... | # -*- coding: utf-8 -*-
import click
import youtube_dl
from .config import storage_load
from .extractor import RdioIE
def add_info_extractor_above_generic(ydl, ie):
generic = ydl._ies.pop()
ydl.add_info_extractor(ie)
ydl.add_info_extractor(generic)
@click.command()
@click.option(u'-u', u'--user', help=... | Fix generic extractor being always selected | Fix generic extractor being always selected
Turns out our extractor was being inserted *after* the GenericIE.
Now we are inserting our RdioIE right above GenericIE.
| Python | mit | ravishi/rdio-dl | ---
+++
@@ -1,8 +1,16 @@
+# -*- coding: utf-8 -*-
import click
import youtube_dl
from .config import storage_load
from .extractor import RdioIE
+
+
+def add_info_extractor_above_generic(ydl, ie):
+ generic = ydl._ies.pop()
+ ydl.add_info_extractor(ie)
+ ydl.add_info_extractor(generic)
+
@click.comma... |
fb3f1023faedda37e5ca16b87d2b9ddc38a2196c | deployer/tasks/util.py | deployer/tasks/util.py | from celery.result import ResultBase, AsyncResult, GroupResult
import deployer
from deployer.tasks.exceptions import TaskExecutionException
__author__ = 'sukrit'
def check_or_raise_task_exception(result):
if isinstance(result, AsyncResult) and result.failed():
if isinstance(result.result, TaskExecutionEx... | import socket
from celery.result import ResultBase, AsyncResult, GroupResult
import deployer
from deployer.tasks.exceptions import TaskExecutionException
from deployer.util import retry
__author__ = 'sukrit'
def check_or_raise_task_exception(result):
if isinstance(result, AsyncResult) and result.failed():
... | Add retry for socket error | Add retry for socket error
| Python | mit | totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer | ---
+++
@@ -1,6 +1,8 @@
+import socket
from celery.result import ResultBase, AsyncResult, GroupResult
import deployer
from deployer.tasks.exceptions import TaskExecutionException
+from deployer.util import retry
__author__ = 'sukrit'
@@ -20,6 +22,7 @@
_check_error(result.parent)
+@retry(10, delay=5, ... |
d0ea27a56013af944ef9e7fef9ebe1c8f44e3aab | community_blog/__openerp__.py | community_blog/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Buron
# Copyright 2013 Yannick Buron
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# publi... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Buron
# Copyright 2013 Yannick Buron
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# publi... | Change name of module community_blog | Change name of module community_blog
Changement de nom | Python | agpl-3.0 | YannickB/vertical-community,Valeureux/wezer-exchange,Valeureux/wezer-exchange,codoo/vertical-community,open-synergy/vertical-community,Valeureux/wezer-exchange,Valeureux/wezer-exchange | ---
+++
@@ -19,7 +19,7 @@
#
##############################################################################
-{'name': 'OpenERP CommunityTools - Website Blog',
+{'name': 'Odoo for Communities - Website Blog',
'version': '1.0',
'category': 'Community',
'depends': ['community',
@@ -29,7 +29,7 @@
'license': 'A... |
b7bad7823384ec5261271e3f54ed272775a7562f | sparqllib/formatter.py | sparqllib/formatter.py | import abc
import re
class Formatter:
@abc.abstractmethod
def format(self, query):
''' Should return a human-readable version of the query string
'''
pass
class BasicFormatter(Formatter):
''' Provides a basic default formatting for query strings
This formatter provides only in... | import abc
import re
class Formatter:
@abc.abstractmethod
def format(self, query):
''' Should return a human-readable version of the query string
'''
pass
class BasicFormatter(Formatter):
''' Provides a basic default formatting for query strings
This formatter provides only in... | Trim trailing whitespace with BasicFormatter | Trim trailing whitespace with BasicFormatter
| Python | mit | ALSchwalm/sparqllib | ---
+++
@@ -18,6 +18,9 @@
self.indent_str = " "
def format(self, query):
+ if not isinstance(query, str):
+ query = query.serialize()
+
#TODO handle braces inside literals correctly
formatted_query = ""
indent_level = 0
@@ -42,6 +45,9 @@
else:... |
a7f467589c49020977328e45eed4eff5b607231f | checker/tests/downstream/test_check_files_menu_agreements.py | checker/tests/downstream/test_check_files_menu_agreements.py | import magic
import os.path as op
from checker.base import BakeryTestCase as TestCase, tags
from checker.metadata import Metadata
class CheckFontsMenuAgreements(TestCase):
path = '.'
name = __name__
targets = ['metadata']
tool = 'lint'
def menufile(self, font_metadata):
return '%s.menu'... | import magic
import os.path as op
from checker.base import BakeryTestCase as TestCase, tags
from checker.metadata import Metadata
class CheckFontsMenuAgreements(TestCase):
path = '.'
name = __name__
targets = ['metadata']
tool = 'lint'
def read_metadata_contents(self):
return open(self.... | Fix check menu files agreement test | Fix check menu files agreement test
| Python | apache-2.0 | davelab6/fontbakery,googlefonts/fontbakery,moyogo/fontbakery,moyogo/fontbakery,graphicore/fontbakery,jessamynsmith/fontbakery,graphicore/fontbakery,googlefonts/fontbakery,graphicore/fontbakery,moyogo/fontbakery,googlefonts/fontbakery | ---
+++
@@ -11,6 +11,9 @@
name = __name__
targets = ['metadata']
tool = 'lint'
+
+ def read_metadata_contents(self):
+ return open(self.path).read()
def menufile(self, font_metadata):
return '%s.menu' % font_metadata.post_script_name |
4fc108a39476f92acf0d42b66466012cba868b1d | h2o-py/tests/testdir_algos/rf/pyunit_vi_toy_testRF.py | h2o-py/tests/testdir_algos/rf/pyunit_vi_toy_testRF.py | import sys
sys.path.insert(1, "../../../")
import h2o
def vi_toy_test(ip,port):
# Connect to h2o
h2o.init(ip,port)
toy_data = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/toy_data_RF.csv"))
#toy_data.summary()
toy_data[6] = toy_data[6].asfactor()
toy_data.show()
rf = h2o.random_fo... | import sys
sys.path.insert(1, "../../../")
import h2o
def vi_toy_test(ip,port):
# Connect to h2o
h2o.init(ip,port)
toy_data = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/toy_data_RF.csv"))
#toy_data.summary()
toy_data[6] = toy_data[6].asfactor()
toy_data.show()
rf = h2o.random_fo... | Fix the seed for RF test. | Fix the seed for RF test.
| Python | apache-2.0 | ChristosChristofidis/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,bospetersen/h2o-3,spennihana/h2o-3,mathemage/h2o-3,weaver-viii/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-3,mathemage/h2o-3,PawarPawan/h2o-v3,michalkurka/h2o-3,datachand/h2o-3,PawarPawan/h2o-v3,printedheart/h2o-3,kyoren/https-github.com-h2oai-h2o-3,mrgloom/h2o-3... | ---
+++
@@ -11,7 +11,7 @@
toy_data[6] = toy_data[6].asfactor()
toy_data.show()
- rf = h2o.random_forest(x=toy_data[[0,1,2,3,4,5]], y=toy_data[6], ntrees=500, max_depth=20, nbins=100)
+ rf = h2o.random_forest(x=toy_data[[0,1,2,3,4,5]], y=toy_data[6], ntrees=500, max_depth=20, nbins=100, seed=0)
... |
ead5d7aa7a4a6fe4557c0e792ebc11e25359722f | rx/concurrency/scheduleditem.py | rx/concurrency/scheduleditem.py | from rx.disposables import SingleAssignmentDisposable
def default_sub_comparer(x, y):
return 0 if x == y else 1 if x > y else -1
class ScheduledItem(object):
def __init__(self, scheduler, state, action, duetime, comparer=None):
self.scheduler = scheduler
self.state = state
self.actio... | from rx.core import Disposable
from rx.disposables import SingleAssignmentDisposable
def default_sub_comparer(x, y):
return 0 if x == y else 1 if x > y else -1
class ScheduledItem(object):
def __init__(self, scheduler, state, action, duetime, comparer=None):
self.scheduler = scheduler
self.s... | Check if action returns disposable | Check if action returns disposable
| Python | mit | ReactiveX/RxPY,ReactiveX/RxPY | ---
+++
@@ -1,3 +1,4 @@
+from rx.core import Disposable
from rx.disposables import SingleAssignmentDisposable
@@ -15,7 +16,9 @@
self.disposable = SingleAssignmentDisposable()
def invoke(self):
- self.disposable.disposable = self.invoke_core()
+ ret = self.action(self.scheduler, self... |
840aef8fee59c9f1a9863177e060b05b09fcacd4 | tests/utils.py | tests/utils.py | # -*- coding: utf-8 -*-
def has_no_django():
try:
import django
return False
except ImportError:
return True
| # -*- coding: utf-8 -*-
def has_no_django():
try:
import django # noqa isort:skip
return False
except ImportError:
return True
| Add noqa to conditional import | Add noqa to conditional import
| Python | mit | python-thumbnails/python-thumbnails,relekang/python-thumbnails | ---
+++
@@ -3,7 +3,7 @@
def has_no_django():
try:
- import django
+ import django # noqa isort:skip
return False
except ImportError:
return True |
5ddde4a43ede87770543984e96eb8ccaf1d829b2 | lib/methods/drupalconsole.py | lib/methods/drupalconsole.py | from base import BaseMethod
from fabric.api import *
from lib.utils import SSHTunnel, RemoteSSHTunnel
from fabric.colors import green, red
from lib import configuration
import copy
class DrupalConsoleMethod(BaseMethod):
@staticmethod
def supports(methodName):
return methodName == 'drupalconsole'
def instal... | from base import BaseMethod
from fabric.api import *
from lib.utils import SSHTunnel, RemoteSSHTunnel
from fabric.colors import green, red
from lib import configuration
import copy
class DrupalConsoleMethod(BaseMethod):
@staticmethod
def supports(methodName):
return methodName == 'drupalconsole'
def instal... | Fix exception when running install-task | Fix exception when running install-task
| Python | mit | factorial-io/fabalicious,factorial-io/fabalicious | ---
+++
@@ -11,7 +11,7 @@
def supports(methodName):
return methodName == 'drupalconsole'
- def install(self, config):
+ def install(self, config, **kwargs):
with cd(config['tmpFolder']):
run('curl https://drupalconsole.com/installer -L -o drupal.phar')
run('mv drupal.phar /usr/local/bin... |
a667b3503b0434f01459bae2d29df800d95ba1c4 | gapipy/resources/tour/departure.py | gapipy/resources/tour/departure.py | from __future__ import unicode_literals
from ...models import Address, AddOn, DepartureRoom, PP2aPrice
from ..base import Product
from .tour_dossier import TourDossier
from .departure_component import DepartureComponent
class Departure(Product):
_resource_name = 'departures'
_is_listable = True
_is_par... | from __future__ import unicode_literals
from ...models import Address, AddOn, DepartureRoom, PP2aPrice
from ..base import Product
from .tour_dossier import TourDossier
from .departure_component import DepartureComponent
class Departure(Product):
_resource_name = 'departures'
_is_listable = True
_is_par... | Add name to Departure resource | Add name to Departure resource
| Python | mit | gadventures/gapipy | ---
+++
@@ -14,7 +14,7 @@
_is_parent_resource = True
_as_is_fields = [
- 'id', 'href', 'availability', 'flags', 'nearest_start_airport',
+ 'id', 'href', 'name', 'availability', 'flags', 'nearest_start_airport',
'nearest_finish_airport', 'product_line', 'sku', 'requirements',
]
... |
ae1de4000a6e9f3fc70d14c6214038e83772a5f6 | Part2/main.py | Part2/main.py | import detectLang
import graph
# ====================================================================================================
# La detection est rapide car toute les perplexites sont stockées dans les fichiers binaires pp_EN etc
# Pour regénerer les fichiers :
# Executer detectLang.create_all_pp_and_save_to_di... | import detectLang
import graph
# ====================================================================================================
# La detection est rapide car toute les perplexites sont stockées dans les fichiers binaires pp_EN etc
# Pour regénerer les fichiers :
# Executer detectLang.create_all_pp_and_save_to_di... | Update doc and add one call | Update doc and add one call
| Python | mit | Focom/NLPWork1,Focom/NLPWork1,Focom/NLPWork1 | ---
+++
@@ -4,25 +4,28 @@
# ====================================================================================================
# La detection est rapide car toute les perplexites sont stockées dans les fichiers binaires pp_EN etc
# Pour regénerer les fichiers :
-# Executer detectLang.create_all_pp_and_save_to_di... |
19cb68209252615c66cee0a1c6df1069f81f6f77 | stock_request_picking_type/models/stock_request_order.py | stock_request_picking_type/models/stock_request_order.py | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... | Set Picking Type in Create | [IMP] Set Picking Type in Create
[IMP] Flake8
| Python | agpl-3.0 | Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse | ---
+++
@@ -28,3 +28,13 @@
('warehouse_id', '=', self.warehouse_id.id)], limit=1)
if picking_type_id:
self._origin.write({'picking_type_id': picking_type_id.id})
+
+ @api.model
+ def create(self, vals):
+ if vals.get('warehouse_id', False):
+ ... |
b6139583bf5074c73c0de6626391b6f128ed6e34 | export_jars.py | export_jars.py | #!/usr/bin/env python
import os
import shutil
from glob import glob
from subprocess import call, check_output
OUTPUT_DIR_NAME = 'jars'
def call_unsafe(*args, **kwargs):
kwargs['shell'] = True
call(*args, **kwargs)
call_unsafe('./gradlew clean javadocRelease jarRelease')
try:
os.mkdir(OUTPUT_DIR_NAME)... | #!/usr/bin/env python
import os
import shutil
from glob import glob
from subprocess import call, check_output
OUTPUT_DIR_NAME = 'jars'
def call_unsafe(*args, **kwargs):
kwargs['shell'] = True
call(*args, **kwargs)
call_unsafe('./gradlew clean javadocRelease jarRelease')
try:
os.mkdir(OUTPUT_DIR_NAME)... | Remove existing JARs before building new ones | Remove existing JARs before building new ones
| Python | mit | swstack/Bean-Android-SDK,PunchThrough/bean-sdk-android,colus001/Bean-Android-SDK,PunchThrough/Bean-Android-SDK,hongbinz/Bean-Android-SDK,androidgrl/Bean-Android-SDK,PunchThrough/Bean-Android-SDK,swstack/Bean-Android-SDK,PunchThrough/bean-sdk-android,androidgrl/Bean-Android-SDK,hongbinz/Bean-Android-SDK,colus001/Bean-An... | ---
+++
@@ -21,6 +21,7 @@
pass
os.chdir(OUTPUT_DIR_NAME)
+call_unsafe('rm *.jar')
call_unsafe('cp ../beansdk/build/libs/*.jar .')
commit = check_output(['git', 'rev-parse', 'HEAD'])[:7] |
1b7a3f045bf7a23ef993d136b481f22258c4a778 | wagtail/wagtailimages/rich_text.py | wagtail/wagtailimages/rich_text.py | from wagtail.wagtailimages.models import get_image_model
from wagtail.wagtailimages.formats import get_image_format
class ImageEmbedHandler(object):
"""
ImageEmbedHandler will be invoked whenever we encounter an element in HTML content
with an attribute of data-embedtype="image". The resulting element in ... | from wagtail.wagtailimages.models import get_image_model
from wagtail.wagtailimages.formats import get_image_format
class ImageEmbedHandler(object):
"""
ImageEmbedHandler will be invoked whenever we encounter an element in HTML content
with an attribute of data-embedtype="image". The resulting element in ... | Refactor try-catch block by limiting code in the try block | Refactor try-catch block by limiting code in the try block
Always good to know which line will raise an exception and limit the try block to that statement
| Python | bsd-3-clause | Toshakins/wagtail,timorieber/wagtail,nrsimha/wagtail,kurtrwall/wagtail,timorieber/wagtail,FlipperPA/wagtail,inonit/wagtail,davecranwell/wagtail,nealtodd/wagtail,iansprice/wagtail,thenewguy/wagtail,nutztherookie/wagtail,jnns/wagtail,kaedroho/wagtail,iansprice/wagtail,serzans/wagtail,inonit/wagtail,kurtw/wagtail,mixxorz/... | ---
+++
@@ -31,15 +31,14 @@
Image = get_image_model()
try:
image = Image.objects.get(id=attrs['id'])
- image_format = get_image_format(attrs['format'])
-
- if for_editor:
- try:
- return image_format.image_to_editor_html(image, att... |
7e1ec1b27d69882005ac5492809c8847c21e2198 | baro.py | baro.py | from datetime import datetime
class Baro:
"""This class represents a Baro item and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation']['sec'])
self.end... | from datetime import datetime
import utils
class Baro:
"""This class contains info about the Void Trader and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation'... | Change class Baro to use timedelta_to_string, some fixes | Change class Baro to use timedelta_to_string, some fixes
| Python | mit | pabletos/Hubot-Warframe,pabletos/Hubot-Warframe | ---
+++
@@ -1,8 +1,9 @@
from datetime import datetime
+import utils
class Baro:
- """This class represents a Baro item and is initialized with
+ """This class contains info about the Void Trader and is initialized with
data in JSON format
"""
@@ -15,7 +16,7 @@
self.manifest =... |
12cd87394e09e7481b39ca519f15db4688ab0073 | tmpl/Prompt.py | tmpl/Prompt.py | #--coding:utf-8--
#Platform
class BasePrompt(object):
pass
class ErrPrompt(BasePrompt):
"""
Define some of Err Prompts
Usually print to sys.stderr
"""
def PrintErr(self, content):
import sys
"""
Automous write content to sys.stderr and add '\n' to the end
"""
... | #--coding:utf-8--
#Platform
class BasePrompt(object):
pass
class ErrPrompt(BasePrompt):
"""
Define some of Err Prompts
Usually print to sys.stderr
"""
def PrintErr(self, content):
import sys
"""
Automous write content to sys.stderr and add '\n' to the end
"""
... | Fix Bugs in module when using -O option | Fix Bugs in module when using -O option
| Python | mit | nday-dev/Spider-Framework | ---
+++
@@ -27,7 +27,7 @@
"""
return True if want to replace, and False for the other
"""
- self.PrintErr("Warning: '%s' already exists, replace?(y/n)" %(Files))
+ self.PrintErr("Warning: '%s' already exists, replace?(y/n)" %(File))
tmp = raw_input()
if tmp =... |
d3078cafd4e64e9c093d9d823df2035b8380d643 | meta-refkit-computervision/recipes-computervision/caffe-bvlc-reference/files/dnn-test.py | meta-refkit-computervision/recipes-computervision/caffe-bvlc-reference/files/dnn-test.py | #!/usr/bin/env python3
# Classify an image using a suitable model. The image conversion magic
# is from
# https://github.com/opencv/opencv_contrib/blob/master/modules/dnn/samples/googlenet_python.py
# (3-clause BSD license).
import numpy as np
import cv2
import sys
if len(sys.argv) != 4:
print("Usage: dnn.py <pr... | #!/usr/bin/env python3
# Classify an image using a suitable model. The image conversion magic
# is from
# https://github.com/opencv/opencv_contrib/blob/master/modules/dnn/samples/googlenet_python.py
# (3-clause BSD license).
import numpy as np
import cv2
import sys
if len(sys.argv) != 4:
print("Usage: dnn.py <pr... | Fix DNN test to be compatible with OpenCV 3.3. | convnet: Fix DNN test to be compatible with OpenCV 3.3.
OpenCV DNN module API changed with OpenCV 3.3. Fix the tests to use the
new API.
Signed-off-by: Ismo Puustinen <75dda586a9213f0e0695eb79120c94222bb30e60@intel.com>
| Python | mit | intel/intel-iot-refkit,mythi/intel-iot-refkit,mythi/intel-iot-refkit,intel/intel-iot-refkit,intel/intel-iot-refkit,intel/intel-iot-refkit,mythi/intel-iot-refkit,klihub/intel-iot-refkit,klihub/intel-iot-refkit,klihub/intel-iot-refkit,klihub/intel-iot-refkit,klihub/intel-iot-refkit,klihub/intel-iot-refkit,mythi/intel-iot... | ---
+++
@@ -25,10 +25,10 @@
# initialize network
net = cv2.dnn.readNetFromCaffe(sys.argv[1], sys.argv[2])
-net.setBlob(".data", data)
+net.setInput(data, "data")
# run the network
-net.forward()
+result = net.forward("prob")
# print the class
-print(str(net.getBlob("prob").argmax()))
+print(str(result.argma... |
210be14772b403e8fb5938e4e2cd391d43275ab1 | tests/test_ot_propagators.py | tests/test_ot_propagators.py | import instana.http_propagator as ihp
import opentracing as ot
from instana import tracer, options, util
from nose.tools import assert_equals
import inspect
def test_basics():
inspect.isclass(ihp.HTTPPropagator)
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
assert inspe... | import instana.http_propagator as ihp
import opentracing as ot
from instana import tracer, options, util
from nose.tools import assert_equals
import inspect
def test_basics():
inspect.isclass(ihp.HTTPPropagator)
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
assert calla... | Fix function test to work on both Py 2 + 3 | Fix function test to work on both Py 2 + 3
| Python | mit | instana/python-sensor,instana/python-sensor | ---
+++
@@ -10,11 +10,11 @@
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
- assert inspect.ismethod(inject_func)
+ assert callable(inject_func)
extract_func = getattr(ihp.HTTPPropagator, "extract", None)
assert extract_func
- assert inspect.ismethod(extr... |
ef94948a8ce16d9d80fb69950381e0936a462bb0 | tests/config_tests.py | tests/config_tests.py | from nose.tools import assert_equal
from wunderapi.config import Config
def setup():
return Config(config_file="tests/resources/test_config")
def test_parse_config_with_correct_parms():
pass
def test_parse_config_with_incorrect_parms():
pass
def test_config_created_with_default_parms():
config =... | from nose.tools import assert_equal
from wunderapi.config import Config
def setup():
return Config(config_file="tests/resources/test_config")
def test_parse_config_with_correct_parms():
pass
def test_parse_config_with_incorrect_parms():
pass
def test_config_created_with_default_parms():
config =... | Update test to get api_key from environment | Update test to get api_key from environment
| Python | mit | paris3200/Weather,paris3200/wunderapi | ---
+++
@@ -17,7 +17,5 @@
def test_config_created_with_default_parms():
config = setup()
config.parse_config()
- assert_equal(config.api_key, 'API Key')
- assert_equal(config.location, 'Zipcode')
assert_equal(config.date_format, 'date')
assert_equal(config.units, 'english') |
0529c392c8c3e75a03aa312e4fc7b367008fdf27 | tests/test_20_main.py | tests/test_20_main.py |
import click.testing
import pytest
from cfgrib import __main__
def test_main():
runner = click.testing.CliRunner()
res = runner.invoke(__main__.cfgrib_cli, ['selfcheck'])
assert res.exit_code == 0
assert 'Your system is ready.' in res.output
res = runner.invoke(__main__.cfgrib_cli, ['non-exis... |
import click.testing
from cfgrib import __main__
def test_main():
runner = click.testing.CliRunner()
res = runner.invoke(__main__.cfgrib_cli, ['selfcheck'])
assert res.exit_code == 0
assert 'Your system is ready.' in res.output
res = runner.invoke(__main__.cfgrib_cli, ['non-existent-command']... | Fix docs and CLI tests. | Fix docs and CLI tests.
| Python | apache-2.0 | ecmwf/cfgrib | ---
+++
@@ -1,6 +1,5 @@
import click.testing
-import pytest
from cfgrib import __main__
|
c5a0d0c5bf578a2221322c068a41ce6331b84c9b | tests/test_cattery.py | tests/test_cattery.py | import pytest
from catinabox import cattery
class TestCattery(object):
###########################################################################
# add_cats
###########################################################################
def test__add_cats__succeeds(self):
c = cattery.Cattery()... | import pytest
from catinabox import cattery, mccattery
@pytest.fixture(params=[
cattery.Cattery,
mccattery.McCattery
])
def cattery_fixture(request):
return request.param()
###########################################################################
# add_cats
###########################################... | Add full tests for mccattery and cattery | Add full tests for mccattery and cattery
| Python | mit | keeppythonweird/catinabox,indexOutOfBound5/catinabox | ---
+++
@@ -1,32 +1,42 @@
import pytest
-from catinabox import cattery
+from catinabox import cattery, mccattery
-class TestCattery(object):
+@pytest.fixture(params=[
+ cattery.Cattery,
+ mccattery.McCattery
+])
+def cattery_fixture(request):
+ return request.param()
- ###########################... |
e79f87121a955847af92d93fad3e2687fc4f472f | tests/test_gen_sql.py | tests/test_gen_sql.py | #!/usr/bin/env python
class TestGenSql:
def test_gen_drop_statement(self):
pass
def test_create_statement(self):
pass
| #!/usr/bin/env python
import sys
from io import StringIO
from pg_bawler import gen_sql
def test_simple_main(monkeypatch):
stdout = StringIO()
monkeypatch.setattr(sys, 'stdout', stdout)
class Args:
tablename = 'foo'
gen_sql.main(*[Args.tablename])
sql = stdout.getvalue()
assert gen_... | Add simple test for sql full sql generation with only tablename | Add simple test for sql full sql generation with only tablename
| Python | bsd-3-clause | beezz/pg_bawler,beezz/pg_bawler | ---
+++
@@ -1,10 +1,19 @@
#!/usr/bin/env python
+import sys
+from io import StringIO
+
+from pg_bawler import gen_sql
-class TestGenSql:
+def test_simple_main(monkeypatch):
+ stdout = StringIO()
+ monkeypatch.setattr(sys, 'stdout', stdout)
- def test_gen_drop_statement(self):
- pass
+ class ... |
d60116aecbb6935fae508c94905a335fdb0603bb | tests/test_xgboost.py | tests/test_xgboost.py | import unittest
from sklearn import datasets
from xgboost import XGBClassifier
class TestXGBoost(unittest.TestCase):
def test_classifier(self):
boston = datasets.load_boston()
X, y = boston.data, boston.target
xgb1 = XGBClassifier(n_estimators=3)
xgb1.fit(X[0:70],y[0:70])
| import unittest
import xgboost
from distutils.version import StrictVersion
from sklearn import datasets
from xgboost import XGBClassifier
class TestXGBoost(unittest.TestCase):
def test_version(self):
# b/175051617 prevent xgboost version downgrade.
self.assertGreaterEqual(StrictVersion(xgboost.__... | Add xgboost version regression test. | Add xgboost version regression test.
BUG=175051617
| Python | apache-2.0 | Kaggle/docker-python,Kaggle/docker-python | ---
+++
@@ -1,9 +1,16 @@
import unittest
+import xgboost
+
+from distutils.version import StrictVersion
from sklearn import datasets
from xgboost import XGBClassifier
class TestXGBoost(unittest.TestCase):
+ def test_version(self):
+ # b/175051617 prevent xgboost version downgrade.
+ self.asse... |
a57e40ea7b0cc55ec67664d9f32658085c24900f | tools/project/check_style.py | tools/project/check_style.py | import subprocess
import sys
git_diff_output = subprocess.check_output(
"git diff --name-only --diff-filter=ACM", universal_newlines=True)
git_diff_lines = git_diff_output.split("\n")
for file_name in git_diff_lines:
if not file_name:
continue
print "Checking style for %s" %file_name
ret_value = subprocess.call... | import subprocess
import sys
git_diff_output = subprocess.check_output(
"git diff --name-only --diff-filter=ACM", universal_newlines=True)
git_diff_lines = git_diff_output.split("\n")
for file_name in git_diff_lines:
if not file_name:
continue
print "Checking style for %s" %file_name
ret_value = subprocess.call... | Update style checker options to ignore copyright. | Update style checker options to ignore copyright.
| Python | mit | damlaren/ogle,damlaren/ogle,damlaren/ogle | ---
+++
@@ -10,8 +10,9 @@
continue
print "Checking style for %s" %file_name
ret_value = subprocess.call(
- "python 3rdparty/styleguide/cpplint/cpplint.py --filter=%s %s"
- %("-build/include_order", file_name), stderr=subprocess.STDOUT)
+ "python 3rdparty/styleguide/cpplint/cpplint.py --filter="
+ "-build/i... |
800706f5835293ee20dd9505d1d11c28eb38bbb2 | tests/shipane_sdk/matchers/dataframe_matchers.py | tests/shipane_sdk/matchers/dataframe_matchers.py | # -*- coding: utf-8 -*-
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_... | # -*- coding: utf-8 -*-
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_... | Fix HasColumn matcher for dataframe with duplicated columns | Fix HasColumn matcher for dataframe with duplicated columns
| Python | mit | sinall/ShiPanE-Python-SDK,sinall/ShiPanE-Python-SDK | ---
+++
@@ -25,7 +25,7 @@
self._column_pattern = re.compile(column_pattern)
def _matches(self, df):
- return df.filter(regex=self._column_pattern).columns.size > 0
+ return len(list(filter(self._column_pattern.match, df.columns.values))) > 0
def describe_to(self, description):
... |
7d6800c33a525355714e355ec87e989372c293d7 | main.py | main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import xmpp
#from google.appengine.api import urlfetch
import urllib2,md5,logging,csv
############## webapp Models ###################
class MainP... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import xmpp
#from google.appengine.api import urlfetch
import urllib2,md5,logging,csv,re,math
def ckinv(oo):
""" check the value is date or not ... | Add check the value is date or not. | Add check the value is date or not.
| Python | mit | toomore/goristock | ---
+++
@@ -7,7 +7,25 @@
#from google.appengine.api import urlfetch
-import urllib2,md5,logging,csv
+import urllib2,md5,logging,csv,re,math
+
+def ckinv(oo):
+ """ check the value is date or not """
+ pattern = re.compile(r"[0-9]{2}/[0-9]{2}/[0-9]{2}")
+ b = re.search(pattern, oo[0])
+ try:
+ b.group()
+ ... |
f85425a2c74cf15555bbed233287ddbd7ab8b24e | flexget/ui/plugins/log/log.py | flexget/ui/plugins/log/log.py | from __future__ import unicode_literals, division, absolute_import
from flexget.ui import register_plugin, Blueprint, register_menu
log = Blueprint('log', __name__)
register_plugin(log)
log.register_angular_route(
'',
url=log.url_prefix,
template_url='index.html',
controller='LogViewCtrl'
)
log.reg... | from __future__ import unicode_literals, division, absolute_import
from flexget.ui import register_plugin, Blueprint, register_menu
log = Blueprint('log', __name__)
register_plugin(log)
log.register_angular_route(
'',
url=log.url_prefix,
template_url='index.html',
controller='LogViewCtrl'
)
log.reg... | Rename libs to keep with standard | Rename libs to keep with standard
| Python | mit | LynxyssCZ/Flexget,qvazzler/Flexget,tobinjt/Flexget,malkavi/Flexget,ZefQ/Flexget,qk4l/Flexget,Flexget/Flexget,tsnoam/Flexget,ianstalk/Flexget,grrr2/Flexget,jacobmetrick/Flexget,qvazzler/Flexget,crawln45/Flexget,poulpito/Flexget,JorisDeRieck/Flexget,gazpachoking/Flexget,tobinjt/Flexget,oxc/Flexget,dsemi/Flexget,jawilson/... | ---
+++
@@ -15,8 +15,8 @@
log.register_css('log', 'css/log.css', order=99)
log.register_js('log', 'js/log.js')
-log.register_js('angular-oboe', 'js/libs/angular-oboe.js')
-log.register_js('oboe-browser', 'js/libs/oboe-browser.js')
+log.register_js('angular-oboe', 'libs/oboe/js/angular-oboe.js')
+log.register_js('... |
8eb47d151868c8e5906af054749993cd46a73b2d | capstone/player/kerasplayer.py | capstone/player/kerasplayer.py | from keras.models import load_model
from . import Player
from ..utils import normalize_board, utility
class KerasPlayer(Player):
'''
Takes moves based on a Keras neural network model.
'''
name = 'Keras'
def __init__(self, filepath):
self.model = load_model(filepath)
def __str__(self... | from keras.models import load_model
from . import Player
from ..utils import normalize_board, utility
class KerasPlayer(Player):
'''
Takes moves based on a Keras neural network model.
'''
name = 'Keras'
def __init__(self, filepath):
self.model = load_model(filepath)
def __str__(self... | Rename state to game in KerasPlayer | Rename state to game in KerasPlayer
| Python | mit | davidrobles/mlnd-capstone-code | ---
+++
@@ -23,16 +23,15 @@
# Player #
##########
- def choose_move(self, state):
- assert state.cur_player() == 0
- best_action = None
+ def choose_move(self, game):
+ assert game.cur_player() == 0
+ best_move = None
best_value = -1000000
- for action in ... |
9b032e06156aa011e5d78d0d9ea297420cb33c2e | form_designer/contrib/cms_plugins/form_designer_form/migrations/0001_initial.py | form_designer/contrib/cms_plugins/form_designer_form/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import cms
from django.db import migrations, models
from pkg_resources import parse_version as V
# Django CMS 3.3.1 is oldest release where the change affects.
# Refs https://github.com/divio/django-cms/commit/871a164
if V(cms.__version__) >= V('3.3.1'):... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import cms
from django.db import migrations, models
from pkg_resources import parse_version as V
# Django CMS 3.3.1 is oldest release where the change affects.
# Refs https://github.com/divio/django-cms/commit/871a164
if V(cms.__version__) >= V('3.3.1'):... | Add on_delete args to CMS plugin migration for Django 2 support | Add on_delete args to CMS plugin migration for Django 2 support
| Python | bsd-3-clause | kcsry/django-form-designer,kcsry/django-form-designer,andersinno/django-form-designer,andersinno/django-form-designer-ai,andersinno/django-form-designer-ai,andersinno/django-form-designer | ---
+++
@@ -30,11 +30,13 @@
primary_key=True,
to='cms.CMSPlugin',
parent_link=True,
+ on_delete=models.CASCADE,
**field_kwargs)),
('form_definition',
models.ForeignKey(
... |
d6787523cb8b58c51fe32d4524389a500e3b7b21 | foliant/cli.py | foliant/cli.py | """Foliant: Markdown to PDF, Docx, and LaTeX generator powered by Pandoc.
Usage:
foliant (build | make) <target> [--path=<project-path>]
foliant (upload | up) <document> [--secret=<client_secret*.json>]
foliant (-h | --help)
foliant --version
Options:
-h --help Show this screen.
-... | """Foliant: Markdown to PDF, Docx, and LaTeX generator powered by Pandoc.
Usage:
foliant (build | make) <target> [--path=<project-path>]
foliant (upload | up) <document> [--secret=<client_secret*.json>]
foliant (-h | --help)
foliant --version
Options:
-h --help Show this screen.
-... | Replace hardcoded package name with ".". | CLI: Replace hardcoded package name with ".".
| Python | mit | foliant-docs/foliant | ---
+++
@@ -17,8 +17,8 @@
import colorama
from colorama import Fore
-from foliant import builder, uploader
-from foliant import __version__ as foliant_version
+from . import builder, uploader
+from . import __version__ as foliant_version
def main(): |
dd02861cd9fb5b06d42f7a6413b371c52c167ba8 | gcmconsumer.py | gcmconsumer.py | import sys
import fedmsg.consumers
import yaml
class GCMConsumer(fedmsg.consumers.FedmsgConsumer):
topic = 'org.fedoraproject.prod.*'
config_key = 'gcmconsumer'
def __init__(self, *args, **kw):
super(GCMConsumer, self).__init__(*args, **kw)
def get_registration_ids_for_topic(self, topic):
... | import fedmsg.consumers
import json
import requests
import sys
import yaml
class GCMConsumer(fedmsg.consumers.FedmsgConsumer):
topic = 'org.fedoraproject.prod.*'
config_key = 'gcmconsumer'
def __init__(self, *args, **kw):
self.config_file = '/home/ricky/devel/fedora/fedmsg-gcm-demo/config.yaml'
... | Handle actually sending out notifications | Handle actually sending out notifications
| Python | apache-2.0 | fedora-infra/fedmsg-gcm-demo | ---
+++
@@ -1,5 +1,7 @@
+import fedmsg.consumers
+import json
+import requests
import sys
-import fedmsg.consumers
import yaml
class GCMConsumer(fedmsg.consumers.FedmsgConsumer):
@@ -7,17 +9,44 @@
config_key = 'gcmconsumer'
def __init__(self, *args, **kw):
+ self.config_file = '/home/ricky/dev... |
81e7d7d45e71f96d85468737708a31aef939091b | grip/default_config.py | grip/default_config.py | """\
Default Configuration
Do NOT change the values here for risk of accidentally committing them.
Override them using command-line arguments or with a local_config.py instead.
"""
HOST = 'localhost'
PORT = 5000
DEBUG = True
DEBUG_GRIP = False
STYLE_URLS = []
STYLE_URL_SOURCE = 'https://github.com/joeyespo/grip'
STY... | """\
Default Configuration
Do NOT change the values here for risk of accidentally committing them.
Override them using command-line arguments or with a local_config.py instead.
"""
HOST = 'localhost'
PORT = 5000
DEBUG = True
DEBUG_GRIP = False
STYLE_URLS = []
STYLE_URL_SOURCE = 'https://github.com/joeyespo/grip'
STY... | Update GitHub CSS file regex. | Update GitHub CSS file regex.
| Python | mit | mgoddard-pivotal/grip,mgoddard-pivotal/grip,ssundarraj/grip,joeyespo/grip,ssundarraj/grip,joeyespo/grip,jbarreras/grip,jbarreras/grip | ---
+++
@@ -12,4 +12,4 @@
DEBUG_GRIP = False
STYLE_URLS = []
STYLE_URL_SOURCE = 'https://github.com/joeyespo/grip'
-STYLE_URL_RE = '<link.+href=[\'"]?([^\'" >]+)[\'"]?.+media=[\'"]?screen[\'"]?.+rel=[\'"]?stylesheet[\'"]?.+/>'
+STYLE_URL_RE = '<link.+href=[\'"]?([^\'" >]+)[\'"]?.+media=[\'"]?(?:screen|all)[\'"]?.+... |
019c91a8cd32fe1a4034837ed75dcc849d9033e5 | format_json.py | format_json.py | #! /usr/bin/env python3
import sys
import json
for filepath in sys.argv[1:]:
with open(filepath) as f:
try:
oyster = json.load(f)
except ValueError:
sys.stderr.write("In file: {}\n".format(filepath))
raise
with open(filepath, 'w') as f:
json.dump(oys... | #! /usr/bin/env python3
import sys
import json
import argparse
def format_json(fp):
try:
data = json.load(fp)
except ValueError:
sys.stderr.write("In file: {}\n".format(fp.name))
raise
# Jump back to the beginning of the file before overwriting it.
fp.seek(0)
json.dump(data... | Make this a proper argparse script. | Make this a proper argparse script.
| Python | mit | nbeaver/cmd-oysters,nbeaver/cmd-oysters | ---
+++
@@ -2,14 +2,30 @@
import sys
import json
+import argparse
-for filepath in sys.argv[1:]:
- with open(filepath) as f:
- try:
- oyster = json.load(f)
- except ValueError:
- sys.stderr.write("In file: {}\n".format(filepath))
- raise
- with open(filepath,... |
2a242bb6984fae5e32f117fa5ae68118621f3c95 | pycroft/model/alembic/versions/fb8d553a7268_add_account_pattern.py | pycroft/model/alembic/versions/fb8d553a7268_add_account_pattern.py | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
... | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
def upgrade():
... | Remove unnecessary pycroft import in migration | Remove unnecessary pycroft import in migration
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft | ---
+++
@@ -7,8 +7,6 @@
"""
from alembic import op
import sqlalchemy as sa
-import pycroft
-
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268' |
569e180b99be2ec67f360a7081bbd54020d78a25 | grum/models.py | grum/models.py | import bcrypt
from grum import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
password = db.Column(db.String(128))
display_name = db.Column(db.String(128))
def __init__(self, username=None, password=None):
if username... | import bcrypt
from grum import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
password = db.Column(db.String(128))
display_name = db.Column(db.String(128))
def __init__(self, username=None, display_name=None, password=None):
... | Add display name to the constructor for User | Add display name to the constructor for User
| Python | mit | Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web | ---
+++
@@ -8,9 +8,11 @@
password = db.Column(db.String(128))
display_name = db.Column(db.String(128))
- def __init__(self, username=None, password=None):
+ def __init__(self, username=None, display_name=None, password=None):
if username:
self.username = username
+ if di... |
94861438189537b88deaf8d04cc9942192038d8c | user_messages/views.py | user_messages/views.py | from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from user_messages.models import Thread, Message
@login_required
def inbox(request, template_name='user_messages/inbox.html'):
threads ... | from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from user_messages.models import Thread, Message
@login_required
def inbox(request, template_name='user_messages/inbox.html'):
threads ... | Update the read status of a thread when it's viewed | Update the read status of a thread when it's viewed
| Python | mit | eldarion/user_messages,eldarion/user_messages,pinax/pinax-messages,arthur-wsw/pinax-messages,pinax/pinax-messages,arthur-wsw/pinax-messages | ---
+++
@@ -16,6 +16,9 @@
template_name='user_messages/thread_detail.html'):
qs = Thread.objects.filter(Q(to_user=request.user) | Q(from_user=request.user))
thread = get_object_or_404(qs, pk=thread_id)
+ if request.user == thread.to_user:
+ thread.to_user_unread = False
+ else:
+ th... |
7897423ea3c8e418b405ce2d09318ad9b1526a22 | tests/test_urls.py | tests/test_urls.py | from django.conf.urls import patterns, url
from djproxy.urls import generate_routes
from test_views import LocalProxy, index
urlpatterns = patterns(
'',
url(r'^some/content/.*$', index, name='index'),
url(r'^local_proxy/(?P<url>.*)$', LocalProxy.as_view(), name='proxy')
) + generate_routes({
'service... | from django.conf.urls import patterns, url
from djproxy.urls import generate_routes
from test_views import LocalProxy, index
urlpatterns = patterns(
'',
url(r'^some/content/.*$', index, name='index'),
url(r'^local_proxy/(?P<url>.*)$', LocalProxy.as_view(), name='proxy')
) + generate_routes({
'service... | Add www to test google config | Add www to test google config
This makes it work right for google.com sub pages when testing via a browser.
| Python | mit | thomasw/djproxy | ---
+++
@@ -14,7 +14,7 @@
'prefix': 'yahoo/'
},
'service_two': {
- 'base_url': 'https://google.com/',
+ 'base_url': 'https://www.google.com/',
'prefix': 'google/'
}
}) |
64f9ef6fcc71ef09e113161711369fe4d9781a18 | shorpypaper.py | shorpypaper.py | #!/usr/bin/python
from pyquery import PyQuery as pq
import requests
import subprocess
APPLESCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""
def main():
# Load main site.
root = 'http://www.shorpy.com'
r = requests.get(root)
j = pq(r.... | #!/usr/bin/python
from pyquery import PyQuery as pq
import requests
import subprocess
APPLESCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""
def main():
# Load main site.
root = 'http://www.shorpy.com'
r = requests.get(root)
j = pq(r.... | Use a grey solid instead of the damn frog. | Use a grey solid instead of the damn frog.
| Python | mit | nicksergeant/shorpypaper | ---
+++
@@ -25,7 +25,7 @@
with open('/tmp/dailyshorpy.jpg', 'wb') as handle:
# To reset the cached dailyshorpy.jpg.
- subprocess.Popen(APPLESCRIPT % '/Library/Desktop Pictures/Frog.jpg', shell=True)
+ subprocess.Popen(APPLESCRIPT % '/Library/Desktop Pictures/Solid Colors/Solid Gray Light... |
c09f586bfa36f4ff66ae3b8a82fd7b4eeb8ea5d7 | windpowerlib/tools.py | windpowerlib/tools.py | """
The ``tools`` module contains a collection of functions used in the
windpowerlib.
"""
__copyright__ = "Copyright oemof developer group"
__license__ = "GPLv3"
| """
The ``tools`` module contains a collection of functions used in the
windpowerlib.
"""
__copyright__ = "Copyright oemof developer group"
__license__ = "GPLv3"
import collections
def select_closer_value(value_1, value_2, comp_value, corresp_1, corresp_2):
r"""
Selects the value with the smaller differenc... | Add function for selection of value closer to comparative value | Add function for selection of value closer to comparative value
| Python | mit | wind-python/windpowerlib | ---
+++
@@ -6,3 +6,66 @@
__copyright__ = "Copyright oemof developer group"
__license__ = "GPLv3"
+
+import collections
+
+
+def select_closer_value(value_1, value_2, comp_value, corresp_1, corresp_2):
+ r"""
+ Selects the value with the smaller difference to a comparative value.
+
+ Additionally returns ... |
9f6d6509b1f3f4a5f3fd20919bcc465475fc1ce3 | app/composer.py | app/composer.py | import os
from app.configuration import get_value
from app.helper import php
def initialization():
checker_dir = get_value('checker-dir')
if not os.path.isfile(checker_dir+'bin/composer'):
download(checker_dir)
if not os.path.isfile(checker_dir+'bin/phpcs'):
php('bin/composer install')
... | import os
from app.configuration import get_value
from app.helper import php
def initialization():
checker_dir = get_value('checker-dir')
if not os.path.isfile(checker_dir+'bin/composer'):
download(checker_dir)
if not os.path.isfile(checker_dir+'bin/phpcs'):
composer('install')
def down... | Add execution path for internal update | Add execution path for internal update
| Python | mit | mi-schi/php-code-checker | ---
+++
@@ -9,7 +9,7 @@
if not os.path.isfile(checker_dir+'bin/composer'):
download(checker_dir)
if not os.path.isfile(checker_dir+'bin/phpcs'):
- php('bin/composer install')
+ composer('install')
def download(checker_dir):
@@ -21,11 +21,20 @@
def update():
- php('bin/com... |
618245ab759cbf47fb53946b4c6149efdca7e1e0 | troposphere/sqs.py | troposphere/sqs.py | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject
from .validators import integer
try:
from awacs.aws import Policy
policytypes = (dict, Policy)
except ImportError:
policytypes = dict,
class Queue(AWSObject):
typ... | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer
try:
from awacs.aws import Policy
policytypes = (dict, Policy)
except ImportError:
policytypes = dict,
class RedrivePolic... | Add SQS dead letter queue from CloudFormation release 2014-01-29 | Add SQS dead letter queue from CloudFormation release 2014-01-29
| Python | bsd-2-clause | cloudtools/troposphere,mhahn/troposphere,johnctitus/troposphere,ikben/troposphere,ikben/troposphere,garnaat/troposphere,pas256/troposphere,alonsodomin/troposphere,Yipit/troposphere,ptoraskar/troposphere,mannytoledo/troposphere,dmm92/troposphere,craigbruce/troposphere,jantman/troposphere,micahhausler/troposphere,jdc0589... | ---
+++
@@ -3,13 +3,20 @@
#
# See LICENSE file for full license.
-from . import AWSObject
+from . import AWSObject, AWSProperty
from .validators import integer
try:
from awacs.aws import Policy
policytypes = (dict, Policy)
except ImportError:
policytypes = dict,
+
+
+class RedrivePolicy(AWSPrope... |
1026581107668e15db91912302ae3fd577140008 | builder.py | builder.py | import ratebeer
import string
def strip_brewery_name(brewery_name, beer_name):
brewery_word_list = brewery_name.split()
for word in brewery_word_list:
beer_name = beer_name.replace(word, "")
return beer_name.strip()
categories = []
categories.append("0-9")
for letter in string.ascii_uppercase:
... | import ratebeer
import string
import csv
from io import BytesIO
def strip_brewery_name(brewery_name, beer_name):
brewery_word_list = brewery_name.split()
for word in brewery_word_list:
beer_name = beer_name.replace(word, "")
return beer_name.strip()
def brewery_name_field(brewery):
val = getat... | Add a csv export for caching the list of beers for display in the app | Add a csv export for caching the list of beers for display in the app
| Python | mit | jwrubel/initial_dictionary | ---
+++
@@ -1,12 +1,21 @@
import ratebeer
import string
-
+import csv
+from io import BytesIO
def strip_brewery_name(brewery_name, beer_name):
brewery_word_list = brewery_name.split()
for word in brewery_word_list:
beer_name = beer_name.replace(word, "")
return beer_name.strip()
+
+def br... |
7e36568d5b8aeaf2c77e4643a793fdc13cb9ba51 | spacy/about.py | spacy/about.py | # inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spaCy'
__version__ = '1.6.0'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ ... | # inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy'
__version__ = '1.6.0'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ ... | Fix title to accommodate sputnik | Fix title to accommodate sputnik | Python | mit | Gregory-Howard/spaCy,spacy-io/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,raphael0202/spaCy,aikramer2/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy... | ---
+++
@@ -3,7 +3,7 @@
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
-__title__ = 'spaCy'
+__title__ = 'spacy'
__version__ = '1.6.0'
__summary__ = 'Industrial-strength Natural Language Processing (NL... |
054b0bf9cacef4e55fb8167fb5f2611e2ce39b43 | hw3/hw3_2a.py | hw3/hw3_2a.py | import sympy
x1, x2 = sympy.symbols('x1 x2')
f = 100*(x2 - x1**2)**2 + (1-x1)**2
df_dx1 = sympy.diff(f,x1)
df_dx2 = sympy.diff(f,x2)
H = sympy.hessian(f, (x1, x2))
xs = sympy.solve([df_dx1, df_dx2], [x1, x2])
H_xs = H.subs([(x1,xs[0][0]), (x2,xs[0][1])])
flag = True
for i in H_xs.eigenvals().keys():
if i.evalf... | import sympy
x1, x2 = sympy.symbols('x1 x2')
f = 100*(x2 - x1**2)**2 + (1-x1)**2
df_dx1 = sympy.diff(f,x1)
df_dx2 = sympy.diff(f,x2)
H = sympy.hessian(f, (x1, x2))
xs = sympy.solve([df_dx1, df_dx2], [x1, x2])
H_xs = H.subs([(x1,xs[0][0]), (x2,xs[0][1])])
lambda_xs = H_xs.eigenvals()
count = 0
for i in lambda_xs.ke... | Fix decision about minima, maxima and saddle point | Fix decision about minima, maxima and saddle point
| Python | bsd-2-clause | escorciav/amcs211,escorciav/amcs211 | ---
+++
@@ -10,14 +10,16 @@
xs = sympy.solve([df_dx1, df_dx2], [x1, x2])
H_xs = H.subs([(x1,xs[0][0]), (x2,xs[0][1])])
+lambda_xs = H_xs.eigenvals()
-flag = True
-for i in H_xs.eigenvals().keys():
+count = 0
+for i in lambda_xs.keys():
if i.evalf() <= 0:
- flag = False
- break
+ count ... |
210581cfef3d54b055ec9f9b1dc6d19b757a4d6e | cli/cli.py | cli/cli.py | import argparse
parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis')
parser.add_argument('-v', '--version', action='version', version='0.1.0')
parser.parse_args()
| Add cmd for getting version | Add cmd for getting version
| Python | mit | McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research | ---
+++
@@ -0,0 +1,5 @@
+import argparse
+
+parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis')
+parser.add_argument('-v', '--version', action='version', version='0.1.0')
+parser.parse_args() | |
ddbcd88bb086d1978c9196833d126ded18db97f8 | airflow/migrations/versions/211e584da130_add_ti_state_index.py | airflow/migrations/versions/211e584da130_add_ti_state_index.py | """add TI state index
Revision ID: 211e584da130
Revises: 2e82aab8ef20
Create Date: 2016-06-30 10:54:24.323588
"""
# revision identifiers, used by Alembic.
revision = '211e584da130'
down_revision = '2e82aab8ef20'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
... | # -*- coding: utf-8 -*-
#
# 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
... | Add license to migration file | Add license to migration file
| Python | apache-2.0 | dhuang/incubator-airflow,Twistbioscience/incubator-airflow,kerzhner/airflow,vineet-rh/incubator-airflow,zodiac/incubator-airflow,cademarkegard/airflow,MetrodataTeam/incubator-airflow,sekikn/incubator-airflow,sergiohgz/incubator-airflow,wooga/airflow,RealImpactAnalytics/airflow,CloverHealth/airflow,apache/incubator-airf... | ---
+++
@@ -1,3 +1,17 @@
+# -*- coding: utf-8 -*-
+#
+# 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 la... |
0469f8f707ba542b0e1af2915d8a46a0107d9d62 | calexicon/tests/test_dates.py | calexicon/tests/test_dates.py | import unittest
from datetime import date
from calexicon.dates import DateWithCalendar
class TestDateWithCalendar(unittest.TestCase):
def setUp(self):
date_dt = date(2010, 8, 1)
self.date_wc = DateWithCalendar(None, date_dt)
def test_comparisons(self):
self.assertTrue(self.date_wc <... | import unittest
from datetime import date, timedelta
from calexicon.dates import DateWithCalendar
class TestDateWithCalendar(unittest.TestCase):
def setUp(self):
date_dt = date(2010, 8, 1)
self.date_wc = DateWithCalendar(None, date_dt)
def test_comparisons(self):
self.assertTrue(sel... | Add a test for __sub__ between a DateWith and a vanilla date. | Add a test for __sub__ between a DateWith and a vanilla date.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual | ---
+++
@@ -1,6 +1,6 @@
import unittest
-from datetime import date
+from datetime import date, timedelta
from calexicon.dates import DateWithCalendar
@@ -23,3 +23,5 @@
self.assertTrue(self.date_wc <= date(2010, 8, 1))
self.assertTrue(self.date_wc >= date(2010, 8, 1))
+ def test_... |
f3e6bc366ea77468772905c0094c9b4305c49fed | jsonpickle/handlers.py | jsonpickle/handlers.py |
class TypeRegistered(type):
"""
As classes of this metaclass are created, they keep a registry in the
base class of all handler referenced by the keys in cls._handles.
"""
def __init__(cls, name, bases, namespace):
super(TypeRegistered, cls).__init__(name, bases, namespace)
if not h... |
class TypeRegistered(type):
"""
As classes of this metaclass are created, they keep a registry in the
base class of all handler referenced by the keys in cls._handles.
"""
def __init__(cls, name, bases, namespace):
super(TypeRegistered, cls).__init__(name, bases, namespace)
if not h... | Add a backward-compatibility shim to lessen the burden upgrading from 0.4 to 0.5 | Add a backward-compatibility shim to lessen the burden upgrading from 0.4 to 0.5
| Python | bsd-3-clause | mandx/jsonpickle,dongguangming/jsonpickle,mandx/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle,dongguangming/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle | ---
+++
@@ -47,3 +47,11 @@
"""
raise NotImplementedError("Abstract method.")
+
+# for backward compatibility, provide 'registry'
+# jsonpickle 0.4 clients will call it with something like:
+# registry.register(handled_type, handler_class)
+class registry:
+ @staticmethod
+ def register(handl... |
08eb1f9e510b85e77d401ca4e13b7ad5354f4ecf | ingestors/email/outlookpst.py | ingestors/email/outlookpst.py | import logging
from followthemoney import model
from ingestors.ingestor import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
log = logging.getLogger(__name__)
... | import logging
from followthemoney import model
from ingestors.ingestor import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
log = logging.getLogger(__name__)
... | Make outlook emit single files | Make outlook emit single files
| Python | mit | alephdata/ingestors | ---
+++
@@ -22,12 +22,13 @@
temp_dir = self.make_empty_directory()
try:
self.exec_command('readpst',
- '-e', # make subfolders, files per message
- '-D', # include deleted
- '-r', # recursive struc... |
a2c8ade4d73b6756fef2829c0e656acbe60f2b03 | fabfile.py | fabfile.py | from fabric.api import local
from fabric.api import warn_only
CMD_MANAGE = "python manage.py "
def auto_schema():
with warn_only():
schema('rockit.foundation.core')
schema('rockit.plugins.mailout')
schema('rockit.plugins.razberry')
def build():
migrate('rockit.foundation.core')
mi... | from fabric.api import local
CMD_MANAGE = "python manage.py "
def auto_schema():
schema('rockit.foundation.core')
schema('rockit.plugins.mailout')
schema('rockit.plugins.razberry')
def build():
migrate('rockit.foundation.core')
migrate('rockit.plugins.mailout')
migrate('rockit.plugins.razberr... | Remove warn only from fabric file | Remove warn only from fabric file
| Python | mit | acreations/rockit-server,acreations/rockit-server,acreations/rockit-server,acreations/rockit-server | ---
+++
@@ -1,13 +1,11 @@
from fabric.api import local
-from fabric.api import warn_only
CMD_MANAGE = "python manage.py "
def auto_schema():
- with warn_only():
- schema('rockit.foundation.core')
- schema('rockit.plugins.mailout')
- schema('rockit.plugins.razberry')
+ schema('rockit.... |
79911105899c95bf3fdb27c1aa61e8ff08ebef14 | bokeh/models/component.py | bokeh/models/component.py | from __future__ import absolute_import
from ..model import Model
from ..core.properties import abstract
from ..core.properties import Bool
from ..embed import notebook_div
@abstract
class Component(Model):
""" A base class for all embeddable models, i.e. plots, layouts and widgets.
"""
disabled = Bool(F... | from __future__ import absolute_import
from ..model import Model
from ..core.properties import abstract
from ..core.properties import Bool
from ..embed import notebook_div
@abstract
class Component(Model):
""" A base class for all for all DOM-level components, i.e. plots, layouts
and widgets.
"""
di... | Change Component docstring to mention DOM-level models | Change Component docstring to mention DOM-level models
| Python | bsd-3-clause | aavanian/bokeh,bokeh/bokeh,ericmjl/bokeh,schoolie/bokeh,ericmjl/bokeh,dennisobrien/bokeh,azjps/bokeh,mindriot101/bokeh,jakirkham/bokeh,aiguofer/bokeh,dennisobrien/bokeh,ptitjano/bokeh,msarahan/bokeh,azjps/bokeh,aiguofer/bokeh,ericmjl/bokeh,mindriot101/bokeh,aavanian/bokeh,phobson/bokeh,bokeh/bokeh,philippjfr/bokeh,Kasp... | ---
+++
@@ -7,7 +7,8 @@
@abstract
class Component(Model):
- """ A base class for all embeddable models, i.e. plots, layouts and widgets.
+ """ A base class for all for all DOM-level components, i.e. plots, layouts
+ and widgets.
"""
|
5847e9db8f316fdee6493fefc9cbc64a1e6a28de | km_api/know_me/serializers/subscription_serializers.py | km_api/know_me/serializers/subscription_serializers.py | import hashlib
import logging
from django.utils.translation import ugettext
from rest_framework import serializers
from know_me import models, subscriptions
logger = logging.getLogger(__name__)
class AppleSubscriptionSerializer(serializers.ModelSerializer):
"""
Serializer for an Apple subscription.
""... | import hashlib
import logging
from django.utils.translation import ugettext
from rest_framework import serializers
from know_me import models, subscriptions
logger = logging.getLogger(__name__)
class AppleSubscriptionSerializer(serializers.ModelSerializer):
"""
Serializer for an Apple subscription.
""... | Mark apple receipt expiration time as read only. | Mark apple receipt expiration time as read only.
| Python | apache-2.0 | knowmetools/km-api,knowmetools/km-api,knowmetools/km-api,knowmetools/km-api | ---
+++
@@ -24,6 +24,7 @@
"receipt_data",
)
model = models.SubscriptionAppleData
+ read_only_fields = ("expiration_time",)
def validate(self, data):
""" |
fa279ca1f8e4c8e6b4094840d3ab40c0ac637eff | ocradmin/ocrpresets/models.py | ocradmin/ocrpresets/models.py | from django.db import models
from django.contrib.auth.models import User
from picklefield import fields
from tagging.fields import TagField
import tagging
class OcrPreset(models.Model):
user = models.ForeignKey(User)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = m... | from django.db import models
from django.contrib.auth.models import User
from picklefield import fields
from tagging.fields import TagField
import tagging
class OcrPreset(models.Model):
user = models.ForeignKey(User)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = m... | Improve unicode method. Whitespace cleanup | Improve unicode method. Whitespace cleanup
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | ---
+++
@@ -21,4 +21,4 @@
"""
String representation.
"""
- return self.name
+ return "<%s: %s>" % (self.__class__.__name__, self.name) |
ebdc3a1d00ddd8c15aaa64c436e43f3815317923 | pythainlp/segment/pyicu.py | pythainlp/segment/pyicu.py | from __future__ import absolute_import,print_function
from itertools import groupby
import PyICU
import six
# ตัดคำภาษาไทย
def segment(txt):
"""รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU"""
bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th"))
bd.setText(six.u(txt))
bre... | from __future__ import absolute_import,print_function
from itertools import groupby
import PyICU
# ตัดคำภาษาไทย
def segment(txt):
"""รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU"""
bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th"))
bd.setText(six.u(txt))
breaks = list(... | Revert "fix bug import six" | Revert "fix bug import six"
This reverts commit a80c1d7c80d68f72d435dbb7ac5c48a6114716fb.
| Python | apache-2.0 | PyThaiNLP/pythainlp | ---
+++
@@ -1,7 +1,6 @@
from __future__ import absolute_import,print_function
from itertools import groupby
import PyICU
-import six
# ตัดคำภาษาไทย
def segment(txt):
"""รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" |
f29665f853d1a33bcf08d1a9298460d0be11d610 | molly/apps/places/__init__.py | molly/apps/places/__init__.py | from flask import Blueprint
from flask.ext.babel import lazy_gettext as _
from molly.apps.common.app import BaseApp
from molly.apps.places.endpoints import PointOfInterestEndpoint
from molly.apps.places.services import PointsOfInterest
class App(BaseApp):
module = 'http://mollyproject.org/apps/places'
human... | from flask import Blueprint
from flask.ext.babel import lazy_gettext as _
from molly.apps.common.app import BaseApp
from molly.apps.places.endpoints import PointOfInterestEndpoint
from molly.apps.places.services import PointsOfInterest
class App(BaseApp):
module = 'http://mollyproject.org/apps/places'
human... | Update URL rules to match Molly 1.x | Update URL rules to match Molly 1.x
| Python | apache-2.0 | ManchesterIO/mollyproject-next,ManchesterIO/mollyproject-next,ManchesterIO/mollyproject-next | ---
+++
@@ -22,5 +22,5 @@
self._poi_endpoint = PointOfInterestEndpoint(instance_name, poi_service)
self.blueprint = Blueprint(self.instance_name, __name__)
- self.blueprint.add_url_rule('/<slug>', 'poi', self._poi_endpoint.get)
+ self.blueprint.add_url_rule('/<slug>/', 'poi', self._p... |
c7455da1b0092e926ed9dafe5ac5ae1335401dba | admin.py | admin.py | from django.contrib import admin
from django.contrib.sites.models import Site
from .models import Church
admin.site.site_header = "Churches of Bridlington Administration"
admin.site.register(Church)
admin.site.unregister(Site)
| from django.contrib import admin
from django.contrib.sites.models import Site
from .models import Church
admin.site.site_header = "Churches of Bridlington Administration"
admin.site.register(Church)
| Undo deregistration of Site object | Undo deregistration of Site object
This will now be controlled by restricting permissions in the
admin.
| Python | mit | bm424/churchmanager,bm424/churchmanager | ---
+++
@@ -6,4 +6,3 @@
admin.site.site_header = "Churches of Bridlington Administration"
admin.site.register(Church)
-admin.site.unregister(Site) |
dee0b3764259ee7f4916e8e5e303c48afb3e5edd | api/base/urls.py | api/base/urls.py | from django.conf import settings
from django.conf.urls import include, url
# from django.contrib import admin
from django.conf.urls.static import static
from . import views
urlpatterns = [
### API ###
url(r'^$', views.root),
url(r'^nodes/', include('api.nodes.urls', namespace='nodes')),
url(r'^users... | from django.conf import settings
from django.conf.urls import include, url, patterns
# from django.contrib import admin
from django.conf.urls.static import static
from . import views
urlpatterns = [
### API ###
url(r'^v2/', include(patterns('',
url(r'^$', views.root),
url(r'^nodes/', include... | Change API url prefix to 'v2' | Change API url prefix to 'v2'
| Python | apache-2.0 | laurenrevere/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,cosenal/osf.io,reinaH/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,aaxelb/osf.io,MerlinZhang/osf.io,TomHeatwole/osf.io,felliott/osf.io,sloria/osf.io,dplorimer/osf,wearpants/osf.io,chrisseto/osf.io,zamattiac/osf.io,wearpants/osf.i... | ---
+++
@@ -1,5 +1,5 @@
from django.conf import settings
-from django.conf.urls import include, url
+from django.conf.urls import include, url, patterns
# from django.contrib import admin
from django.conf.urls.static import static
@@ -9,8 +9,9 @@
urlpatterns = [
### API ###
- url(r'^$', views.root),
-... |
f70574c38140c9a5493981f5baf72bab82be8c60 | opps/articles/tests/models.py | opps/articles/tests/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from opps.articles.models import Post
class PostModelTest(TestCase):
fixtures = ['tests/initial_data.json']
def setUP(self):
self.post = Post.objects.get(id=1)
def test_basic_post_exist(self):
post = Post.ob... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from opps.articles.models import Post
class PostModelTest(TestCase):
fixtures = ['tests/initial_data.json']
def setUp(self):
self.post = Post.objects.get(id=1)
def test_basic_post_exist(self):
post = Post.ob... | Add test articles, post get absolute url | Add test articles, post get absolute url
| Python | mit | YACOWS/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,jeanmask/opps,opps/opps,williamroot/opps | ---
+++
@@ -9,7 +9,7 @@
fixtures = ['tests/initial_data.json']
- def setUP(self):
+ def setUp(self):
self.post = Post.objects.get(id=1)
def test_basic_post_exist(self):
@@ -26,3 +26,11 @@
self.assertTrue(self.post.child_class)
self.assertEqual(self.post.child_class, ... |
3eee55236a709e2929ffab7f15b8e50d541ed9a7 | utils/graph.py | utils/graph.py | """
This module serves as an interface to
matplotlib.
"""
from utils import config
OFFSET = 2 # offset = max_x/stepsize * OFFSET
def init(output):
import matplotlib
config.mpl(matplotlib, bool(output))
from matplotlib import pyplot
globals()['plt'] = pyplot
def line_plot(xs, ys, color='red'):
plt.p... | """
This module serves as an interface to
matplotlib.
"""
from utils import config
OFFSET = 2 # offset = max_x/stepsize * OFFSET
def init(output):
import matplotlib
config.mpl(matplotlib, bool(output))
from matplotlib import pyplot
globals()['plt'] = pyplot
def line_plot(xs, ys, color='red'):
plt.p... | Add a different color for scatter plots to differentiate from line. | Add a different color for scatter plots to differentiate from line.
| Python | mit | wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation | ---
+++
@@ -24,7 +24,7 @@
def legend(*args):
plt.legend(args, loc='best')
-def scatter_plot(x, y, color='red'):
+def scatter_plot(x, y, color='blue'):
plt.scatter(x, y, color=color)
def scale_plot(max_x, stepsize): |
dcc810f3181ebe358481c30c2248d25511aab26c | npz_to_my5c.py | npz_to_my5c.py | import numpy as np
import argparse
import sys
import pandas as pd
parser = argparse.ArgumentParser(description='Calculate coverage over different window sizes for a list of bam files.')
parser.add_argument('-n', '--npz_frequencies_file', required=True, help='An npz file containing co-segregation frequencies to convert... | import numpy as np
import argparse
import sys
import pandas as pd
parser = argparse.ArgumentParser(description='Calculate coverage over different window sizes for a list of bam files.')
parser.add_argument('-n', '--npz_frequencies_file', required=True, help='An npz file containing co-segregation frequencies to convert... | Handle NaNs properly when flattening matrices. | Handle NaNs properly when flattening matrices.
| Python | apache-2.0 | pombo-lab/gamtools,pombo-lab/gamtools | ---
+++
@@ -14,4 +14,4 @@
windows, data = open_npz(args.npz_frequencies_file)
names = [ '{}:{}-{}'.format(*i) for i in windows ]
-pd.DataFrame(data, index=names, columns=names).to_csv(sys.stdout, sep='\t')
+pd.DataFrame(data, index=names, columns=names).to_csv(sys.stdout, sep='\t', na_rep="NaN") |
8ad95ada5e57ad941b1333cea8f8b81ce739a245 | knights/defaultfilters.py | knights/defaultfilters.py |
from .library import Library
from .filters import Filter
register = Library()
@register.filter(name='title')
class TitleFilter(Filter):
def __rshift__(self, other):
return str(other).title()
|
from .library import Library
register = Library()
@register.filter
def title(val):
return str(val).title()
| Convert to new style filter | Convert to new style filter
| Python | mit | funkybob/knights-templater,funkybob/knights-templater | ---
+++
@@ -1,12 +1,10 @@
from .library import Library
-from .filters import Filter
register = Library()
-@register.filter(name='title')
-class TitleFilter(Filter):
- def __rshift__(self, other):
- return str(other).title()
+@register.filter
+def title(val):
+ return str(val).title() |
0512534c4067b6c36d68241d1ccc7de349a3bbe8 | betfairlightweight/__init__.py | betfairlightweight/__init__.py | from .apiclient import APIClient
from .exceptions import BetfairError
from .streaming import StreamListener
from .filters import MarketFilter, StreamingMarketFilter, StreamingMarketDataFilter
__title__ = 'betfairlightweight'
__version__ = '0.9.9'
__author__ = 'Liam Pauling'
| import logging
from .apiclient import APIClient
from .exceptions import BetfairError
from .filters import MarketFilter, StreamingMarketFilter, StreamingMarketDataFilter
from .streaming import StreamListener
__title__ = 'betfairlightweight'
__version__ = '0.9.9'
__author__ = 'Liam Pauling'
# Set default logging hand... | Add NullHandler to top level package logger | Add NullHandler to top level package logger
| Python | mit | liampauling/betfair,liampauling/betfairlightweight | ---
+++
@@ -1,9 +1,21 @@
+import logging
+
from .apiclient import APIClient
from .exceptions import BetfairError
+from .filters import MarketFilter, StreamingMarketFilter, StreamingMarketDataFilter
from .streaming import StreamListener
-from .filters import MarketFilter, StreamingMarketFilter, StreamingMarketDataF... |
9be232ab83a4c482eaf56ea99f7b1be81412c517 | Bookie/fabfile/development.py | Bookie/fabfile/development.py | """Fabric commands useful for working on developing Bookie are loaded here"""
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
def ge... | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.p... | Add a fab command to run jstests | Add a fab command to run jstests
| Python | agpl-3.0 | adamlincoln/Bookie,skmezanul/Bookie,charany1/Bookie,charany1/Bookie,adamlincoln/Bookie,bookieio/Bookie,wangjun/Bookie,teodesson/Bookie,GreenLunar/Bookie,wangjun/Bookie,teodesson/Bookie,GreenLunar/Bookie,pombredanne/Bookie,pombredanne/Bookie,charany1/Bookie,GreenLunar/Bookie,skmezanul/Bookie,teodesson/Bookie,wangjun/Boo... | ---
+++
@@ -1,4 +1,6 @@
"""Fabric commands useful for working on developing Bookie are loaded here"""
+import os
+
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
@@ -17,3 +19,12 @@
def push_bootstrap():
"""Sync the bootstrap.py up to the server for... |
7197f1578335b38eb2037e8d82f15a27d786d5c1 | var/spack/repos/builtin/packages/py-setuptools/package.py | var/spack/repos/builtin/packages/py-setuptools/package.py | from spack import *
class PySetuptools(Package):
"""Easily download, build, install, upgrade, and uninstall Python packages."""
homepage = "https://pypi.python.org/pypi/setuptools"
url = "https://pypi.python.org/packages/source/s/setuptools/setuptools-11.3.tar.gz"
version('11.3.1', '01f69212e019a... | from spack import *
class PySetuptools(Package):
"""Easily download, build, install, upgrade, and uninstall Python packages."""
homepage = "https://pypi.python.org/pypi/setuptools"
url = "https://pypi.python.org/packages/source/s/setuptools/setuptools-11.3.tar.gz"
version('11.3.1', '01f69212e019a... | Add version 2.6.7 of py-setuptools | Add version 2.6.7 of py-setuptools
| Python | lgpl-2.1 | skosukhin/spack,mfherbst/spack,tmerrick1/spack,lgarren/spack,skosukhin/spack,krafczyk/spack,iulian787/spack,skosukhin/spack,tmerrick1/spack,skosukhin/spack,matthiasdiener/spack,matthiasdiener/spack,TheTimmy/spack,LLNL/spack,LLNL/spack,krafczyk/spack,mfherbst/spack,mfherbst/spack,matthiasdiener/spack,mfherbst/spack,Emre... | ---
+++
@@ -10,6 +10,7 @@
version('18.1', 'f72e87f34fbf07f299f6cb46256a0b06')
version('19.2', '78353b1f80375ca5e088f4b4627ffe03')
version('20.5', 'fadc1e1123ddbe31006e5e43e927362b')
+ version('20.6.7', '45d6110f3ec14924e44c33411db64fe6')
extends('python')
|
90e7bc2c8313de2a5054d5290441c527f5f2c253 | gameButton.py | gameButton.py | # Game Button class for menu
# Marshall Ehlinger
import pygame
class gameButton:
GRAY = [131, 131, 131]
PINK = [255, 55, 135]
def __init__(self, label, buttonWidth, buttonHeight, importedGameFunction):
self.label = label
self.height = buttonHeight
self.width = buttonWidth
self.importedGameFunction = impo... | # Game Button class for menu
# Marshall Ehlinger
import pygame
class gameButton:
GRAY = [131, 131, 131]
PINK = [255, 55, 135]
WHITE = [255, 255, 255]
BLACK = [0, 0, 0]
def __init__(self, label, buttonWidth, buttonHeight, importedGameFunction):
self.label = label
self.height = buttonHeight
self.width = bu... | Add labels to menu buttons | Add labels to menu buttons
| Python | mit | MEhlinger/rpi_pushbutton_games | ---
+++
@@ -7,19 +7,24 @@
GRAY = [131, 131, 131]
PINK = [255, 55, 135]
+ WHITE = [255, 255, 255]
+ BLACK = [0, 0, 0]
def __init__(self, label, buttonWidth, buttonHeight, importedGameFunction):
self.label = label
self.height = buttonHeight
self.width = buttonWidth
self.importedGameFunction = impo... |
761367713658e2a436e1d600af026b375a7a332b | pymks/bases/real_ffts.py | pymks/bases/real_ffts.py | from .abstract import _AbstractMicrostructureBasis
import numpy as np
class _RealFFTBasis(_AbstractMicrostructureBasis):
def __init__(self, *args, **kwargs):
super(_RealFFTBasis, self).__init__(*args, **kwargs)
def _fftn(self, X, threads=1, avoid_copy=True):
if self._pyfftw:
retur... | from .abstract import _AbstractMicrostructureBasis
import numpy as np
class _RealFFTBasis(_AbstractMicrostructureBasis):
def __init__(self, *args, **kwargs):
super(_RealFFTBasis, self).__init__(*args, **kwargs)
def _fftn(self, X, threads=1, avoid_copy=True):
if self._pyfftw:
retur... | Fix bug for numpy's irfftn | Fix bug for numpy's irfftn
address #232
Fix bug for numpy's irfftn. The size of the returned array must be
passed because the returned size is potentially not unique. Without
this change only the return kernel would possibly have the wrong shape.
| Python | mit | davidbrough1/pymks,davidbrough1/pymks | ---
+++
@@ -25,7 +25,7 @@
planner_effort='FFTW_ESTIMATE',
avoid_copy=avoid_copy)().real
else:
- return self._fftmodule.irfftn(X, axes=self._axes).real
+ return self._fftmodule.irfftn(X, axes=self._axes... |
3c6c242fd42bd9acf9866f458fa70536d56f3ccd | tests/test_tabulate.py | tests/test_tabulate.py | from pgcli.packages.tabulate import tabulate
from textwrap import dedent
def test_dont_strip_leading_whitespace():
data = [[' abc']]
headers = ['xyz']
tbl, _ = tabulate(data, headers, tablefmt='psql')
assert tbl == dedent('''
+---------+
| xyz |
|---------|
| ... | from mycli.packages.tabulate import tabulate
from textwrap import dedent
def test_dont_strip_leading_whitespace():
data = [[' abc']]
headers = ['xyz']
tbl, _ = tabulate(data, headers, tablefmt='psql')
assert tbl == dedent('''
+---------+
| xyz |
|---------|
| ... | Change the pgcli import to mycli. | Change the pgcli import to mycli.
| Python | bsd-3-clause | mdsrosa/mycli,mdsrosa/mycli | ---
+++
@@ -1,4 +1,4 @@
-from pgcli.packages.tabulate import tabulate
+from mycli.packages.tabulate import tabulate
from textwrap import dedent
|
633b23fd862f152c3f7d9e88fbeb660635386c3f | qmtp_package/__init__.py | qmtp_package/__init__.py | import os
if not os.environ.get("RMG_workingDirectory"):
import os.path
message = "Please set your RMG_workingDirectory environment variable.\n" +\
"(eg. export RMG_workingDirectory=%s )" % \
os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
raise Exception(message)
| Check for RMG_workingDirectory environment variable in qmtp_package | Check for RMG_workingDirectory environment variable in qmtp_package
I dislike the way this is needed, but for now this commit will at least help people
discover their mistake if they forget. | Python | mit | nickvandewiele/RMG-Py,pierrelb/RMG-Py,KEHANG/RMG-Py,chatelak/RMG-Py,enochd/RMG-Py,comocheng/RMG-Py,nickvandewiele/RMG-Py,nyee/RMG-Py,nyee/RMG-Py,comocheng/RMG-Py,enochd/RMG-Py,pierrelb/RMG-Py,chatelak/RMG-Py,faribas/RMG-Py,KEHANG/RMG-Py,faribas/RMG-Py | ---
+++
@@ -0,0 +1,7 @@
+import os
+if not os.environ.get("RMG_workingDirectory"):
+ import os.path
+ message = "Please set your RMG_workingDirectory environment variable.\n" +\
+ "(eg. export RMG_workingDirectory=%s )" % \
+ os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
+ raise... | |
f791354a098c32617f02f05dbbb53861b7a94139 | rapt/cmds/ingredients.py | rapt/cmds/ingredients.py | import click
from rapt.connection import get_vr
from rapt.models import query
from rapt.util import dump_yaml, load_yaml, edit_yaml
@click.command()
@click.option('--name', '-n')
def ingredients(name, verbose):
"""List builds.
"""
vr = get_vr()
q = {}
if name:
q['name'] = name
# add... | import click
from rapt.connection import get_vr
from rapt.models import query
from rapt.util import dump_yaml, load_yaml, edit_yaml
@click.command()
@click.option('--name', '-n')
def ingredients(name, verbose):
"""List builds.
"""
vr = get_vr()
q = {}
if name:
q['name'] = name
# add... | Update the ingredient or noop if there are no changes | Update the ingredient or noop if there are no changes
| Python | bsd-3-clause | yougov/rapt,yougov/rapt | ---
+++
@@ -35,4 +35,11 @@
}
config = edit_yaml(dump_yaml(doc))
- print(config)
+
+ if not config:
+ click.echo('No changes')
+ return
+
+ ingredient.config_yaml = dump_yaml(config['config'])
+ ingredient.env_yaml = dump_yaml(config['env'])
+ ingredient.save() |
903458640ec8db1c39c822b229e466bc717efe40 | registration/__init__.py | registration/__init__.py | from django.utils.version import get_version as django_get_version
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
return django_get_version(VERSION) # pragma: no cover
| VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
| Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems. | Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
| Python | bsd-3-clause | christang/django-registration-1.5,AndrewLvov/django-registration,AndrewLvov/django-registration,fedenko/django-registration,fedenko/django-registration,christang/django-registration-1.5 | ---
+++
@@ -1,8 +1,6 @@
-from django.utils.version import get_version as django_get_version
-
-
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
+ from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover |
c763d42e48d501461ab6c8c875d691f52045ada8 | intelmq/bots/outputs/mongodb/output.py | intelmq/bots/outputs/mongodb/output.py | # -*- coding: utf-8 -*-
"""
pymongo library automatically tries to reconnect if connection has been lost
"""
from intelmq.lib.bot import Bot
try:
import pymongo
except ImportError:
pymongo = None
class MongoDBOutputBot(Bot):
def init(self):
if pymongo is None:
self.logger.error('Cou... | # -*- coding: utf-8 -*-
"""
pymongo library automatically tries to reconnect if connection has been lost
"""
from intelmq.lib.bot import Bot
try:
import pymongo
except ImportError:
pymongo = None
class MongoDBOutputBot(Bot):
def init(self):
if pymongo is None:
self.logger.error('Cou... | Add authentication otpion to mongodb | Add authentication otpion to mongodb
| Python | agpl-3.0 | certtools/intelmq,certtools/intelmq,certtools/intelmq,aaronkaplan/intelmq,aaronkaplan/intelmq,aaronkaplan/intelmq | ---
+++
@@ -29,6 +29,12 @@
raise ValueError('Connection to mongodb server failed.')
else:
db = self.client[self.parameters.database]
+ if self.parameters.db_user and self.parameters.db_pass:
+ try:
+ db.authenticate(name=self.parameters.d... |
afe90ba2a9720ffd80780e7696353510501362c7 | studygroups/management/commands/generate_reminders.py | studygroups/management/commands/generate_reminders.py | from django.core.management.base import BaseCommand, CommandError
from studygroups.tasks import gen_reminders
class Command(BaseCommand):
help = 'Generate reminders for all study groups happening in 3 days from now'
def handle(self, *args, **options):
gen_reminders()
| from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from studygroups.models import Meeting
from studygroups.models.learningcircle import generate_meeting_reminder
class Command(BaseCommand):
help = 'Transitional command to generate reminders for all meetings in the ... | Update task to generate reminders for all future meetings | Update task to generate reminders for all future meetings
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | ---
+++
@@ -1,9 +1,15 @@
from django.core.management.base import BaseCommand, CommandError
+from django.utils import timezone
-from studygroups.tasks import gen_reminders
+from studygroups.models import Meeting
+from studygroups.models.learningcircle import generate_meeting_reminder
class Command(BaseCommand):
... |
52a9e0b5f3f0df4d2a9a092ecf6935def7a3e5cf | lib/ansiblelint/formatters/__init__.py | lib/ansiblelint/formatters/__init__.py | class Formatter(object):
def format(self, match):
formatstr = u"[{0}] {1}\n{2}:{3}\n{4}\n"
return formatstr.format(match.rule.id,
match.message,
match.filename,
match.linenumber,
... | class Formatter(object):
def format(self, match):
formatstr = u"[{0}] {1}\n{2}:{3}\n{4}\n"
return formatstr.format(match.rule.id,
match.message,
match.filename,
match.linenumber,
... | Improve ParseableFormatter to be more like pylint | Improve ParseableFormatter to be more like pylint
Add an E in front of the rule ID so that pylint detects
it as an error.
Fixes #154
| Python | mit | willthames/ansible-lint,dataxu/ansible-lint,MatrixCrawler/ansible-lint | ---
+++
@@ -23,6 +23,6 @@
formatstr = u"{0}:{1}: [{2}] {3}"
return formatstr.format(match.filename,
match.linenumber,
- match.rule.id,
+ "E" + match.rule.id,
match.message,... |
d1d55450db13766f51f264c9bfef1bcea74ef7b1 | convert.py | convert.py | #!/usr/bin/env python
import os, sys
import pexpect
import geom
from sfepy.fem.mesh import Mesh
try:
from site_cfg import tetgen_path
except ImportError:
tetgen_path = '/usr/bin/tetgen'
def mesh():
if len( sys.argv ) == 3:
geomFileName = sys.argv[1]
vtkFileName = sys.argv[2]
if len( sy... | #!/usr/bin/env python
import os, sys
import geom
from sfepy.fem.mesh import Mesh
try:
from site_cfg import tetgen_path
except ImportError:
tetgen_path = '/usr/bin/tetgen'
def mesh():
if len( sys.argv ) == 3:
geomFileName = sys.argv[1]
vtkFileName = sys.argv[2]
if len( sys.argv ) == 2:
... | Use os.system() instead of pexpect.run(). | Use os.system() instead of pexpect.run().
Also do not generate too dense mesh by default, so that it's faster.
| Python | bsd-3-clause | BubuLK/sfepy,sfepy/sfepy,BubuLK/sfepy,RexFuzzle/sfepy,vlukes/sfepy,sfepy/sfepy,rc/sfepy,lokik/sfepy,RexFuzzle/sfepy,BubuLK/sfepy,olivierverdier/sfepy,sfepy/sfepy,olivierverdier/sfepy,vlukes/sfepy,lokik/sfepy,vlukes/sfepy,RexFuzzle/sfepy,RexFuzzle/sfepy,olivierverdier/sfepy,lokik/sfepy,lokik/sfepy,rc/sfepy,rc/sfepy | ---
+++
@@ -1,6 +1,5 @@
#!/usr/bin/env python
import os, sys
-import pexpect
import geom
from sfepy.fem.mesh import Mesh
@@ -20,11 +19,11 @@
geomFileName = "database/box.geo"
vtkFileName = "tmp/t.1.vtk"
- pexpect.run( "gmsh -0 %s -o tmp/x.geo" % geomFileName )
+ os.system( "gmsh -0 %s ... |
d178fb001b8b6869038ed6ec288acf5fb427205c | rssmailer/tasks/mail.py | rssmailer/tasks/mail.py | from celery.decorators import task
from django.core.mail import send_mail
from ..models import Email
@task(ignore_result=True, name="rssmailer.tasks.mail.send")
def send(entry, **kwargs):
logger = send.get_logger(**kwargs)
logger.info("Sending entry: %s" % entry.title)
emails_all = Email.objects.all(... | from celery.decorators import task
from django.core.mail import send_mail
from ..models import Email
@task(ignore_result=True, name="rssmailer.tasks.send")
def send(entry, **kwargs):
logger = send.get_logger(**kwargs)
logger.info("Sending entry: %s" % entry.title)
emails_all = Email.objects.all()
... | Fix naming issues with tasks | Fix naming issues with tasks
| Python | bsd-3-clause | praus/django-rssmailer | ---
+++
@@ -3,7 +3,7 @@
from ..models import Email
-@task(ignore_result=True, name="rssmailer.tasks.mail.send")
+@task(ignore_result=True, name="rssmailer.tasks.send")
def send(entry, **kwargs):
logger = send.get_logger(**kwargs)
logger.info("Sending entry: %s" % entry.title)
@@ -16,8 +16,8 @@
... |
615627cf6ea4725bed7886e822bc01c12d9fdead | nodewatcher/web/sanitize-dump.py | nodewatcher/web/sanitize-dump.py | #!/usr/bin/python
# Setup import paths, since we are using Django models
import sys, os
sys.path.append('/var/www/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'wlanlj.settings_production'
# Imports
from django.core import serializers
if len(sys.argv) != 4:
print "Usage: %s format input-file output-file" % sys.a... | #!/usr/bin/python
# Setup import paths, since we are using Django models
import sys, os
sys.path.append('/var/www/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'wlanlj.settings_production'
# Imports
from django.core import serializers
if len(sys.argv) != 4:
print "Usage: %s format input-file output-file" % sys.a... | Remove solar statistics data from dumps. | Remove solar statistics data from dumps.
| Python | agpl-3.0 | galaxor/Nodewatcher,galaxor/Nodewatcher,galaxor/Nodewatcher,galaxor/Nodewatcher | ---
+++
@@ -32,7 +32,9 @@
object.password = 'XXX'
elif name == 'Profile':
object.root_pass = 'XXX'
-
+ elif name == 'StatsSolar':
+ continue
+
yield holder.object
# Write transformed objects out |
8ca20bec63b8f8aaff55a7012c69a2644e292095 | mltsp/science_features/lomb_scargle_fast.py | mltsp/science_features/lomb_scargle_fast.py | import numpy as np
import gatspy
def lomb_scargle_fast_period(t, m, e):
"""Fits a simple sinuosidal model
y(t) = A sin(2*pi*w*t) + B cos(2*pi*w*t) + c
and returns the estimated period 1/w. Much faster than fitting the
full multi-frequency model used by `science_features.lomb_scargle`.
"""
... | import numpy as np
import gatspy
def lomb_scargle_fast_period(t, m, e):
"""Fits a simple sinuosidal model
y(t) = A sin(2*pi*w*t + phi) + c
and returns the estimated period 1/w. Much faster than fitting the
full multi-frequency model used by `science_features.lomb_scargle`.
"""
opt_args =... | Change docstring for `period_fast` feature | Change docstring for `period_fast` feature
| Python | bsd-3-clause | bnaul/mltsp,mltsp/mltsp,mltsp/mltsp,bnaul/mltsp,acrellin/mltsp,bnaul/mltsp,acrellin/mltsp,mltsp/mltsp,mltsp/mltsp,bnaul/mltsp,acrellin/mltsp,mltsp/mltsp,mltsp/mltsp,acrellin/mltsp,bnaul/mltsp,acrellin/mltsp,bnaul/mltsp,acrellin/mltsp | ---
+++
@@ -5,7 +5,7 @@
def lomb_scargle_fast_period(t, m, e):
"""Fits a simple sinuosidal model
- y(t) = A sin(2*pi*w*t) + B cos(2*pi*w*t) + c
+ y(t) = A sin(2*pi*w*t + phi) + c
and returns the estimated period 1/w. Much faster than fitting the
full multi-frequency model used by `sc... |
4d5c8ec9c2006b78a42461af43944de8ab7bc9ea | us_ignite/common/sanitizer.py | us_ignite/common/sanitizer.py | import bleach
ALLOWED_TAGS = [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'code',
'em',
'i',
'li',
'ol',
'strong',
'ul',
'p',
'br',
]
ALLOWED_ATTRIBUTES = {
'a': ['href', 'title'],
'abbr': ['title'],
'acronym': ['title'],
}
ALLOWED_STYLES = []
def... | import bleach
ALLOWED_TAGS = [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'code',
'em',
'i',
'li',
'ol',
'strong',
'ul',
'p',
'br',
'h3',
'h4',
'h5',
'h6',
]
ALLOWED_ATTRIBUTES = {
'a': ['href', 'title'],
'abbr': ['title'],
'acronym':... | Allow low level titles when sanitising. | Allow low level titles when sanitising.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -15,6 +15,10 @@
'ul',
'p',
'br',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
]
ALLOWED_ATTRIBUTES = { |
858bc6f152a87298f9bd3568712aed49b6e02e42 | suave/suave.py | suave/suave.py | #!/usr/bin/env python
import curses
import os
import time
from box import Box
from utils import load_yaml
def main(screen):
"""
Draws and redraws the screen.
"""
# Hide the cursor.
curses.curs_set(0)
# Load config from file.
config = load_yaml(os.path.expanduser('~/.suave/config.yml'))
... | #!/usr/bin/env python
import curses
import os
from box import Box
from utils import load_yaml
def main(screen):
"""
Draws and redraws the screen.
"""
# Hide the cursor.
curses.curs_set(0)
# Load config from file.
config = load_yaml(os.path.expanduser('~/.suave/config.yml'))
# Creat... | Use napms method from curses rather than sleep method from time | Use napms method from curses rather than sleep method from time
| Python | mit | countermeasure/suave | ---
+++
@@ -2,7 +2,6 @@
import curses
import os
-import time
from box import Box
from utils import load_yaml
@@ -44,7 +43,7 @@
[box.redraw_if_changed() for box in boxes]
# Wait before redrawing again.
- time.sleep(1)
+ curses.napms(1000)
curses.wrapper(main) |
59627d96975b2735fabd0d44e34e018ca97dec2b | tweepy/error.py | tweepy/error.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from __future__ import print_function
import six
class TweepError(Exception):
"""Tweepy exception"""
def __init__(self, reason, response=None, api_code=None):
self.reason = six.text_type(reason)
self.response = respon... | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from __future__ import print_function
import six
class TweepError(Exception):
"""Tweepy exception"""
def __init__(self, reason, response=None, api_code=None):
self.reason = six.text_type(reason)
self.response = respon... | Fix super usage in TweepError initialization | Fix super usage in TweepError initialization
| Python | mit | svven/tweepy,tweepy/tweepy | ---
+++
@@ -13,7 +13,7 @@
self.reason = six.text_type(reason)
self.response = response
self.api_code = api_code
- super(TweepError, self).__init__(self, reason)
+ super(TweepError, self).__init__(reason)
def __str__(self):
return self.reason |
be9ce58461e56873b0d8f60c85c0af96e48ce3fb | fabfile.py | fabfile.py | import logging
import yaml
from fabric.api import lcd, env, task
from fabric.contrib.project import rsync_project
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
try:
conf = yaml.load(open('deploy.yaml', 'rb').read())
except:
log.exception('error: unable to read deply.yaml config file:')... | import logging
import os
import yaml
from fabric.api import lcd, env, task, local
from fabric.contrib.project import rsync_project
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
repo_root = local('git rev-parse --show-toplevel', capture=True)
try:
conf = yaml.load(open(os.path.join(repo_roo... | Make deployment script work from anywhere. | Make deployment script work from anywhere.
| Python | mit | lexicalunit/pancake-master,lexicalunit/pancake-master,lexicalunit/pancake-master | ---
+++
@@ -1,16 +1,18 @@
import logging
+import os
import yaml
-from fabric.api import lcd, env, task
+from fabric.api import lcd, env, task, local
from fabric.contrib.project import rsync_project
logging.basicConfig(level=logging.DEBUG)
+
log = logging.getLogger()
-
+repo_root = local('git rev-parse --sh... |
d648598d669144d589ffbbb03bf56edad4050aff | connector/__manifest__.py | connector/__manifest__.py | # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{'name': 'Connector',
'version': '10.0.1.0.0',
'author': 'Camptocamp,Openerp Connector Core Editors,'
'Odoo Community Association (OCA)',
'website': 'http://odoo-connector.com',... | # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{'name': 'Connector',
'version': '10.0.1.0.0',
'author': 'Camptocamp,Openerp Connector Core Editors,'
'Odoo Community Association (OCA)',
'website': 'http://odoo-connector.com',... | Remove application flag, not an application | Remove application flag, not an application
| Python | agpl-3.0 | js-landoo/connector,js-landoo/connector | ---
+++
@@ -20,5 +20,4 @@
'res_partner_view.xml',
],
'installable': True,
- 'application': True,
} |
15cb279724a646368066591e81467e1b26d61938 | examples/charts/file/steps.py | examples/charts/file/steps.py | from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
jython=[22, 43, 10, 25, 26, ... | """ This example uses the U.S. postage rate per ounce for stamps and
postcards.
Source: https://en.wikipedia.org/wiki/History_of_United_States_postage_rates
"""
from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(stamp=[
.33, .3... | Change step example to plot US postage rates | Change step example to plot US postage rates
| Python | bsd-3-clause | ptitjano/bokeh,timsnyder/bokeh,draperjames/bokeh,percyfal/bokeh,justacec/bokeh,clairetang6/bokeh,philippjfr/bokeh,ericmjl/bokeh,rs2/bokeh,azjps/bokeh,DuCorey/bokeh,clairetang6/bokeh,draperjames/bokeh,clairetang6/bokeh,DuCorey/bokeh,aavanian/bokeh,KasperPRasmussen/bokeh,justacec/bokeh,bokeh/bokeh,aiguofer/bokeh,rs2/boke... | ---
+++
@@ -1,18 +1,25 @@
+""" This example uses the U.S. postage rate per ounce for stamps and
+postcards.
+
+Source: https://en.wikipedia.org/wiki/History_of_United_States_postage_rates
+"""
+
from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
-data ... |
dd03a3d323594c7836525a1be733b689731d98c4 | core/settings/__init__.py | core/settings/__init__.py | """Settings package initialization."""
import dotenv
dotenv.load()
# Ensure development settings are not used in testing and production:
if dotenv.get('ENVIRONMENT') == 'HEROKU':
from .production import *
elif dotenv.get('ENVIRONMENT') == 'TRAVIS':
from .testing import *
else:
from .local import *
| """Settings package initialization."""
import dotenv
dotenv.load()
# Ensure development settings are not used in testing and production:
if dotenv.get('ENVIRONMENT') == 'PRODUCTION':
from .production import *
elif dotenv.get('ENVIRONMENT') == 'TRAVIS':
from .testing import *
else:
from .local import *
| Change ENVIRONMENT variable from HEROKU to PRODUCTION | Change ENVIRONMENT variable from HEROKU to PRODUCTION
| Python | mit | teamtaverna/core | ---
+++
@@ -4,7 +4,7 @@
dotenv.load()
# Ensure development settings are not used in testing and production:
-if dotenv.get('ENVIRONMENT') == 'HEROKU':
+if dotenv.get('ENVIRONMENT') == 'PRODUCTION':
from .production import *
elif dotenv.get('ENVIRONMENT') == 'TRAVIS':
from .testing import * |
a55f0fa9f80042c3fa673f263b259e70dd52f7d6 | streak-podium/read.py | streak-podium/read.py | import requests
def input_file(filename):
"""
Read a file and return list of usernames.
Assumes one username per line and ignores blank lines.
"""
with open(filename, 'r') as f:
return list(line.strip() for line in f if line.strip())
def org_members(org_name):
"""
Query Github A... | import requests
def input_file(filename):
"""
Read a file and return list of usernames.
Assumes one username per line and ignores blank lines.
"""
with open(filename, 'r') as f:
return list(line.strip() for line in f if line.strip())
def org_members(org_name):
"""
Query Github A... | Handle exception where connection fails | Handle exception where connection fails
| Python | mit | jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium,jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium | ---
+++
@@ -25,6 +25,11 @@
for a specific username.
"""
url = 'https://github.com/users/{}/contributions'.format(username)
- r = requests.get(url)
+ try:
+ r = requests.get(url)
+ except requests.exceptions.ConnectionError:
+ logging.warn('Connection error trying to get url: [{}]... |
764256427ea7c0dbf73accf63ed05e8372f58a75 | test/pyfrontend/util.py | test/pyfrontend/util.py | import contextlib
import tempfile
import shutil
@contextlib.contextmanager
def temporary_directory():
"""Simple context manager to make a temporary directory"""
tmpdir = tempfile.mkdtemp()
yield tmpdir
shutil.rmtree(tmpdir, ignore_errors=True)
| import contextlib
import tempfile
import shutil
import saliweb.test # for python 2.6 support
@contextlib.contextmanager
def temporary_directory():
"""Simple context manager to make a temporary directory"""
tmpdir = tempfile.mkdtemp()
yield tmpdir
shutil.rmtree(tmpdir, ignore_errors=True)
| Add unittest methods to Python 2.6 | Add unittest methods to Python 2.6
| Python | lgpl-2.1 | salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb | ---
+++
@@ -1,6 +1,7 @@
import contextlib
import tempfile
import shutil
+import saliweb.test # for python 2.6 support
@contextlib.contextmanager |
46b60c5886ede34db8998d7cfd5ae36f9211a0e8 | ovp_users/tests/test_views/__init__.py | ovp_users/tests/test_views/__init__.py | from ovp_users.tests.test_views.user import UserResourceViewSetTestCase
from ovp_users.tests.test_views.auth import JWTAuthTestCase
from ovp_users.tests.test_views.password_recovery import RecoveryTokenViewSetTestCase
from ovp_users.tests.test_views.password_recovery import RecoverPasswordViewSetTestCase
| from ovp_users.tests.test_views.user import UserResourceViewSetTestCase
from ovp_users.tests.test_views.auth import JWTAuthTestCase
from ovp_users.tests.test_views.profile import ProfileTestCase
from ovp_users.tests.test_views.password_recovery import RecoveryTokenViewSetTestCase
from ovp_users.tests.test_views.passwor... | Add profile views tests to suite | Add profile views tests to suite
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users | ---
+++
@@ -1,4 +1,5 @@
from ovp_users.tests.test_views.user import UserResourceViewSetTestCase
from ovp_users.tests.test_views.auth import JWTAuthTestCase
+from ovp_users.tests.test_views.profile import ProfileTestCase
from ovp_users.tests.test_views.password_recovery import RecoveryTokenViewSetTestCase
from ovp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.