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 |
|---|---|---|---|---|---|---|---|---|---|---|
9be9ddd64d192240d45dea5b0c3dfbe3a2d3e261 | gae2django/utils.py | gae2django/utils.py | #
# Copyright 2008 Andi Albrecht <albrecht.andi@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #
# Copyright 2008 Andi Albrecht <albrecht.andi@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Return str(self) instead of self. | Return str(self) instead of self.
| Python | apache-2.0 | bubenkoff/bubenkoff-gae2django,andialbrecht/django-gae2django,andialbrecht/django-gae2django,bubenkoff/bubenkoff-gae2django | ---
+++
@@ -17,7 +17,7 @@
class CallableString(str):
def __call__(self):
- return self
+ return str(self)
def id(self):
try: |
3328a58e7c81fb86af2424b851de05e7b409ec00 | asyncio/__init__.py | asyncio/__init__.py | """The asyncio package, tracking PEP 3156."""
import sys
# This relies on each of the submodules having an __all__ variable.
from .futures import *
from .events import *
from .locks import *
from .transports import *
from .protocols import *
from .streams import *
from .tasks import *
if sys.platform == 'win32': # ... | """The asyncio package, tracking PEP 3156."""
import sys
# The selectors module is in the stdlib in Python 3.4 but not in 3.3.
# Do this first, so the other submodules can use "from . import selectors".
try:
import selectors # Will also be exported.
except ImportError:
from . import selectors
# This relies ... | Add fakery so "from asyncio import selectors" always works. | Add fakery so "from asyncio import selectors" always works.
| Python | apache-2.0 | jashandeep-sohi/asyncio,gsb-eng/asyncio,ajdavis/asyncio,vxgmichel/asyncio,gvanrossum/asyncio,manipopopo/asyncio,gsb-eng/asyncio,fallen/asyncio,1st1/asyncio,Martiusweb/asyncio,vxgmichel/asyncio,ajdavis/asyncio,haypo/trollius,ajdavis/asyncio,fallen/asyncio,manipopopo/asyncio,1st1/asyncio,fallen/asyncio,Martiusweb/asyncio... | ---
+++
@@ -1,6 +1,13 @@
"""The asyncio package, tracking PEP 3156."""
import sys
+
+# The selectors module is in the stdlib in Python 3.4 but not in 3.3.
+# Do this first, so the other submodules can use "from . import selectors".
+try:
+ import selectors # Will also be exported.
+except ImportError:
+ fr... |
09e4dd8736d6e829b779dd14b882e0e1d7f5abb9 | tester/register/prepare_test.py | tester/register/prepare_test.py |
import sys
import os
import argparse
def write_csv(filename, nb_users):
with open(filename, "w") as csv_file:
csv_file.write("SEQUENTIAL\n")
for x in xrange(nb_users):
line = "{uname};localhost;[authentication username={uname} password={uname}];\n".format(uname=str(1000+x))
csv_file.write(line)
def write... |
import sys
import os
import argparse
def write_csv(filename, nb_users):
with open(filename, "w") as csv_file:
csv_file.write("SEQUENTIAL\n")
for x in xrange(nb_users):
line = "{uname};localhost;[authentication username={uname} password={uname}];\n".format(uname=str(1000+x))
csv_file.write(line)
def write... | DROP DATABASE IF EXISTS in tests. | DROP DATABASE IF EXISTS in tests. | Python | agpl-3.0 | BelledonneCommunications/flexisip,BelledonneCommunications/flexisip,BelledonneCommunications/flexisip,BelledonneCommunications/flexisip | ---
+++
@@ -13,7 +13,7 @@
def write_sql(filename, nb_users):
with open(filename, "w") as sql_file:
- header = """DROP DATABASE tests;
+ header = """DROP DATABASE IF EXISTS tests;
CREATE DATABASE tests;
USE tests;
CREATE TABLE accounts (user VARCHAR(20),password VARCHAR(20));""" |
8be856ed565d9e961a4d24da74a13240e25f4ded | cio/plugins/base.py | cio/plugins/base.py | class BasePlugin(object):
ext = None
def load(self, content):
"""
Return plugin data for content string
"""
return content
def save(self, data):
"""
Persist external plugin resources and return content string for plugin data
"""
return data
... | from cio.conf import settings
class BasePlugin(object):
ext = None
@property
def settings(self):
return settings.get(self.ext.upper(), {})
def load(self, content):
"""
Return plugin data for content string
"""
return content
def save(self, data):
... | Add support for plugin settings | Add support for plugin settings | Python | bsd-3-clause | 5monkeys/content-io | ---
+++
@@ -1,6 +1,13 @@
+from cio.conf import settings
+
+
class BasePlugin(object):
ext = None
+
+ @property
+ def settings(self):
+ return settings.get(self.ext.upper(), {})
def load(self, content):
""" |
e4696a04cbc003737d7ba28d58b14775e9fc2682 | tests/transport/test_asyncio.py | tests/transport/test_asyncio.py | from unittest import TestCase
class AsyncioTransportTestCase(TestCase):
pass
| from asyncio import get_event_loop
from unittest import TestCase, mock
from rfxcom.transport import AsyncioTransport
from rfxcom.protocol import RESET_PACKET, STATUS_PACKET
class AsyncioTransportTestCase(TestCase):
def test_loop_once(self):
loop = get_event_loop()
def handler(*args, **kwargs)... | Add an initial ghetto asyncio test. | Add an initial ghetto asyncio test. | Python | bsd-3-clause | skimpax/python-rfxcom,kalfa/python-rfxcom,AndyA13/python-rfxcom,d0ugal-archive/python-rfxcom,kalfa/python-rfxcom,d0ugal-archive/python-rfxcom,AndyA13/python-rfxcom,skimpax/python-rfxcom | ---
+++
@@ -1,5 +1,24 @@
-from unittest import TestCase
+from asyncio import get_event_loop
+from unittest import TestCase, mock
+
+from rfxcom.transport import AsyncioTransport
+
+from rfxcom.protocol import RESET_PACKET, STATUS_PACKET
class AsyncioTransportTestCase(TestCase):
- pass
+
+ def test_loop_onc... |
f97e1d88f0508521fb2841ef9e8c98ec77424daa | SettingsTemplate.py | SettingsTemplate.py | HOST = "irc.twitch.tv"
PORT = 6667
PASS = "oauth:##############################" # Your bot's oauth (https://twitchapps.com/tmi/)
IDENTITY = "my_bot" # Your bot's username. Lowercase!!
WHITELIST = ["some_authourized_account", "another one"] ... | HOST = "irc.twitch.tv"
PORT = 6667
PASS = "oauth:##############################" # Your bot's oauth (https://twitchapps.com/tmi/)
IDENTITY = "my_bot" # Your bot's username. Lowercase!!
WHITELIST = ["some_authourized_account", "another one"] ... | Set CHECK_LINKS to False for default | Set CHECK_LINKS to False for default
| Python | apache-2.0 | K00sKlust/K00sTwitchBot | ---
+++
@@ -9,4 +9,4 @@
JOIN_MESSAGE = "Hi, I'm a bot that just joined this channel." # Message from the bot when it joins a channel.
WOT_KEY = "" # Api key of WOT to check sites (mywot.com)
-CHECK_LINKS = True ... |
793ad28cf8bae098d12d08d971f19fd9cc29f3dd | colorlog/logging.py | colorlog/logging.py | """Wrappers around the logging module"""
from __future__ import absolute_import
import functools
import logging
from colorlog.colorlog import ColoredFormatter
BASIC_FORMAT = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s"
def basicConfig(**kwargs):
"""This calls basicConfig() and then overrides the... | """Wrappers around the logging module"""
from __future__ import absolute_import
import functools
import logging
from colorlog.colorlog import ColoredFormatter
BASIC_FORMAT = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s"
def basicConfig(**kwargs):
"""This calls basicConfig() and then overrides the... | Add datefmt to arguments that will be passed within decorated basicConfig | Add datefmt to arguments that will be passed within decorated basicConfig
| Python | mit | borntyping/python-colorlog | ---
+++
@@ -17,7 +17,8 @@
try:
stream = logging.root.handlers[0]
stream.setFormatter(
- ColoredFormatter(kwargs.get('format', BASIC_FORMAT)))
+ ColoredFormatter(kwargs.get('format', BASIC_FORMAT),
+ datefmt=kwargs.get('datefmt')))
finally:
... |
b2d06e068fbc7bad9ed0c8f22e751b6bb46d353d | dependencies/contrib/_django.py | dependencies/contrib/_django.py | from __future__ import absolute_import
from collections import OrderedDict
from dependencies import this
from django.views.generic import View
def view(injector):
"""Create Django class-based view from injector class."""
handler = create_handler(View)
apply_http_methods(handler, injector)
handler.h... | from __future__ import absolute_import
from collections import OrderedDict
from dependencies import this
from django.views.generic import View
def view(injector):
"""Create Django class-based view from injector class."""
handler = create_handler(View)
apply_http_methods(handler, injector)
finalize_... | Fix django view closure issue. | Fix django view closure issue.
| Python | bsd-2-clause | proofit404/dependencies,proofit404/dependencies,proofit404/dependencies,proofit404/dependencies | ---
+++
@@ -11,8 +11,7 @@
handler = create_handler(View)
apply_http_methods(handler, injector)
- handler.http_method_names = list(handler.http_method_names.keys())
-
+ finalize_http_methods(handler)
return injector.let(as_view=handler.as_view)
@@ -27,17 +26,23 @@
def apply_http_methods(han... |
5d5cb362410896927b6216deeb9421adfc3331c4 | hatarake/net.py | hatarake/net.py | '''
Wrappers around Python requests
This allows us to handle all the custom headers in a single place
'''
from __future__ import absolute_import
import requests
from functools import wraps
from hatarake import USER_AGENT
def add_args(func):
@wraps(func)
def wrapper(*args, **kwargs):
if 'headers' no... | '''
Wrappers around Python requests
This allows us to handle all the custom headers in a single place
'''
from __future__ import absolute_import
import requests
from functools import wraps
from hatarake import USER_AGENT
def add_args(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
... | Support token as an argument to our requests wrapper | Support token as an argument to our requests wrapper
| Python | mit | kfdm/hatarake | ---
+++
@@ -14,9 +14,15 @@
def add_args(func):
@wraps(func)
def wrapper(*args, **kwargs):
- if 'headers' not in kwargs:
- kwargs['headers'] = {}
- kwargs['headers']['user-agent'] = USER_AGENT
+ try:
+ kwargs['headers']['user-agent'] = USER_AGENT
+ except Ke... |
6d6d1af248ce555cca56521bba5e7c356817c74e | account/forms.py | account/forms.py | from django.contrib.auth.models import User
from django import forms
from account.models import UserProfile
attributes = {"class": "required"}
class RegistrationForm(forms.Form):
username = forms.RegexField(regex=r'^[\w.@+-]+$',
max_length=30,
wid... | from django.contrib.auth.models import User
from django import forms
from account.models import UserProfile
attributes = {"class": "required"}
class RegistrationForm(forms.Form):
username = forms.RegexField(regex=r'^[\w.@+-]+$',
max_length=30,
wid... | Remove unused section of SettingsForm | Remove unused section of SettingsForm
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp | ---
+++
@@ -32,12 +32,6 @@
label="XSEDE Username")
new_ssh_keypair = forms.BooleanField(required=False)
- def clean(self):
- if "password1" in self.cleaned_data and "password2" in self.cleaned_data:
- if self.cleaned_data["password1"] != self.cleaned_data["... |
8c174388aefa3907aeb8733bb3d4c77c770eefe7 | DataModelAdapter.py | DataModelAdapter.py |
class DataModelAdapter(object) :
def __init__(self, data) :
self._data = data
self._children = set()
pass
def numChildren(self) :
return len(self._children)
def hasData(self) :
return self._data is not None
def getData(self, key) :
return self._data[k... |
class DataModelAdapter(object) :
def __init__(self, data) :
self._data = data
self._children = set()
self._parent = None
pass
def numChildren(self) :
return len(self._children)
def hasData(self) :
return self._data is not None
def getData(self, key) :... | Add _parent field with setter/getter | Add _parent field with setter/getter
| Python | apache-2.0 | mattdeckard/wherewithal | ---
+++
@@ -4,6 +4,7 @@
def __init__(self, data) :
self._data = data
self._children = set()
+ self._parent = None
pass
def numChildren(self) :
@@ -17,3 +18,9 @@
def addChild(self, child) :
self._children.add(child)
+
+ def setParent(self, parent) :
+ ... |
e27f04e9c8d5d74afdd9cd7d6990cad5ff6f6cb5 | api/v330/docking_event/serializers.py | api/v330/docking_event/serializers.py | from api.v330.common.serializers import *
class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
spacecraft = SpacecraftSerializer(read_only=True, many=False)
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft... | from api.v330.common.serializers import *
class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
spacecraft = SpacecraftSerializer(read_only=True, many=False)
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft... | Add space_station field to detailed docking event | Add space_station field to detailed docking event
| Python | apache-2.0 | ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server | ---
+++
@@ -7,6 +7,12 @@
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft')
+
+
+class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = SpaceStation
+ fields = ('id', 'url'... |
e0becdd677c06c29834ecea73c28635553e18337 | app/main/presenters/search_results.py | app/main/presenters/search_results.py | from flask import Markup
class SearchResults(object):
"""Provides access to the search results information"""
def __init__(self, response, lots_by_slug):
self.search_results = response['services']
self._lots = lots_by_slug
self._annotate()
self.total = response['meta']['total'... | from flask import Markup
class SearchResults(object):
"""Provides access to the search results information"""
def __init__(self, response, lots_by_slug):
self.search_results = response['services']
self._lots = lots_by_slug
self._annotate()
self.total = response['meta']['total'... | Add static highlighting on serviceDescription field | Add static highlighting on serviceDescription field
| Python | mit | alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend | ---
+++
@@ -23,10 +23,11 @@
def _add_highlighting(self, service):
if 'highlight' in service:
- if 'serviceSummary' in service['highlight']:
- service['serviceSummary'] = Markup(
- ''.join(service['highlight']['serviceSummary'])
- )
+ ... |
df6339ad776aa989362089f54f3a1f675a86bfb0 | adhocracy/lib/tiles/badge_tiles.py | adhocracy/lib/tiles/badge_tiles.py | def badge(badge):
from adhocracy.lib.templating import render_def
return render_def('/badge/tiles.html', 'badge', badge=badge,
cached=True)
def badges(badges):
from adhocracy.lib.templating import render_def
return render_def('/badge/tiles.html', 'badges', badges=badges,
... | def badge(badge):
from adhocracy.lib.templating import render_def
return render_def('/badge/tiles.html', 'badge', badge=badge,
cached=True)
def badges(badges):
from adhocracy.lib.templating import render_def
return render_def('/badge/tiles.html', 'badges', badges=badges,
... | Include style for all badges | badges: Include style for all badges
Not only global badges.
| Python | agpl-3.0 | phihag/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,alkadis/vcv,alkadis/vcv,alkadis/vcv,liqd/adhocracy,SysTheron/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,SysTheron/adhocracy,phihag/adhocracy,SysTheron/adhocr... | ---
+++
@@ -16,6 +16,6 @@
'''
from adhocracy.lib.templating import render_def
from adhocracy.model import Badge
- badges = Badge.all()
+ badges = Badge.all_q().all()
return render_def('/badge/tiles.html', 'badge_styles', badges=badges,
cached=True) |
dbba6f10c867e64031ae07adb3d21becfe4a4e5a | law/contrib/cms/__init__.py | law/contrib/cms/__init__.py | # coding: utf-8
"""
CMS-related contrib package. https://home.cern/about/experiments/cms
"""
__all__ = ["CMSJobDashboard", "BundleCMSSW"]
# provisioning imports
from law.contrib.cms.job import CMSJobDashboard
from law.contrib.cms.tasks import BundleCMSSW
| # coding: utf-8
"""
CMS-related contrib package. https://home.cern/about/experiments/cms
"""
__all__ = ["CMSJobDashboard", "BundleCMSSW", "Site", "lfn_to_pfn"]
# provisioning imports
from law.contrib.cms.job import CMSJobDashboard
from law.contrib.cms.tasks import BundleCMSSW
from law.contrib.cms.util import Site,... | Load utils in cms contrib package. | Load utils in cms contrib package.
| Python | bsd-3-clause | riga/law,riga/law | ---
+++
@@ -5,9 +5,10 @@
"""
-__all__ = ["CMSJobDashboard", "BundleCMSSW"]
+__all__ = ["CMSJobDashboard", "BundleCMSSW", "Site", "lfn_to_pfn"]
# provisioning imports
from law.contrib.cms.job import CMSJobDashboard
from law.contrib.cms.tasks import BundleCMSSW
+from law.contrib.cms.util import Site, lfn_to... |
372a1cab73dad91daab5640f472eda4552be0adb | chatterbot/__init__.py | chatterbot/__init__.py | """
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot
__version__ = '1.0.0a1'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'
__all__ = (
'ChatBot',
)
| """
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot
__version__ = '1.0.0a2'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'
__all__ = (
'ChatBot',
)
| Set release version to 1.0.0a2 | Set release version to 1.0.0a2
| Python | bsd-3-clause | gunthercox/ChatterBot,vkosuri/ChatterBot | ---
+++
@@ -3,7 +3,7 @@
"""
from .chatterbot import ChatBot
-__version__ = '1.0.0a1'
+__version__ = '1.0.0a2'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot' |
3c1357627bf1921fdee114b60f96f42c328120b4 | caramel/__init__.py | caramel/__init__.py | #! /usr/bin/env python
# vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python :
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import (
init_session,
)
def main(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
... | #! /usr/bin/env python
# vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python :
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import (
init_session,
)
def main(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
... | Move pyramid_tm include to caramel.main | Caramel: Move pyramid_tm include to caramel.main
Move the setting to include pyramid_tm to caramel.main from ini files.
This is a vital setting that should never be changed by the user.
| Python | agpl-3.0 | ModioAB/caramel,ModioAB/caramel | ---
+++
@@ -13,6 +13,7 @@
engine = engine_from_config(settings, "sqlalchemy.")
init_session(engine)
config = Configurator(settings=settings)
+ config.include("pyramid_tm")
config.add_route("ca", "/root.crt", request_method="GET")
config.add_route("cabundle", "/bundle.crt", request_method="... |
409ad4af8a4ad933667d91709822a04dbbda77ac | km3pipe/cmd.py | km3pipe/cmd.py | # coding=utf-8
# Filename: cmd.py
"""
KM3Pipe command line utility.
Usage:
km3pipe test
km3pipe tohdf5 [-s] -i FILE -o FILE
km3pipe (-h | --help)
km3pipe --version
Options:
-h --help Show this screen.
-i FILE Input file.
-o FILE Output file.
-s Write each event in a sepa... | # coding=utf-8
# Filename: cmd.py
"""
KM3Pipe command line utility.
Usage:
km3pipe test
km3pipe tohdf5 [-s] -i FILE -o FILE
km3pipe (-h | --help)
km3pipe --version
Options:
-h --help Show this screen.
-i FILE Input file.
-o FILE Output file.
-s Write each event in a sepa... | Set HDF5TableSink as default sink | Set HDF5TableSink as default sink
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe | ---
+++
@@ -21,12 +21,12 @@
from km3pipe import version
-def tohdf5(input_file, output_file, separate_events=False):
+def tohdf5(input_file, output_file, use_tables=True):
"""Convert ROOT file to HDF5 file"""
from km3pipe import Pipeline # noqa
- from km3pipe.pumps import AanetPump, HDF5Sink, HDF5S... |
16f531cb7e9d067725a4c25a4321773aada9616d | api/v2/views/tag.py | api/v2/views/tag.py | from core.models import Tag
from api.permissions import CloudAdminRequired
from api.v2.serializers.summaries import TagSummarySerializer
from api.v2.views.base import AuthReadOnlyViewSet
class TagViewSet(AuthReadOnlyViewSet):
"""
API endpoint that allows tags to be viewed or edited.
"""
queryset = T... | from threepio import logger
from core.models import Tag
from api.permissions import ApiAuthRequired, CloudAdminRequired,\
InMaintenance
from api.v2.serializers.summaries import TagSummarySerializer
from api.v2.views.base import AuthOptionalViewSet
class TagViewSet(AuthOptionalViewSet):
"""
API endpoint t... | Address @jchansen's requests. No dupes. POST for authorized users, PUT DELETE for cloud admins and staff. | Address @jchansen's requests. No dupes. POST for authorized users, PUT DELETE for cloud admins and staff.
modified: api/v2/views/tag.py
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend | ---
+++
@@ -1,11 +1,13 @@
+from threepio import logger
from core.models import Tag
-from api.permissions import CloudAdminRequired
+from api.permissions import ApiAuthRequired, CloudAdminRequired,\
+ InMaintenance
from api.v2.serializers.summaries import TagSummarySerializer
-from api.v2.views.base import Auth... |
00a497b21b9c788cb38da6c92a985e1b5c22801a | apps/survey/urls.py | apps/survey/urls.py | from django.conf.urls.defaults import *
from . import views
urlpatterns = patterns('',
url(r'^profile/$', views.profile_index, name='survey_profile'),
url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'),
#url(r'^profile/intake/$', views.survey_intake, name='survey_profile_i... | from django.conf.urls.defaults import *
from . import views
urlpatterns = patterns('',
url(r'^profile/$', views.profile_index, name='survey_profile'),
url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'),
url(r'^profile/surveys/$', views.survey_management, name='survey_manag... | Add view and update decorators | Add view and update decorators
| Python | agpl-3.0 | chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork | ---
+++
@@ -5,15 +5,15 @@
urlpatterns = patterns('',
url(r'^profile/$', views.profile_index, name='survey_profile'),
url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'),
- #url(r'^profile/intake/$', views.survey_intake, name='survey_profile_intake'),
url(r'^profile/s... |
5a27329e32942523e73d2d01b43ba75ecd281622 | dask/array/__init__.py | dask/array/__init__.py | from __future__ import absolute_import, division, print_function
from ..utils import ignoring
from .core import (Array, stack, concatenate, tensordot, transpose, from_array,
choose, coarsen, constant, fromfunction, compute, unique, store)
from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, ar... | from __future__ import absolute_import, division, print_function
from ..utils import ignoring
from .core import (Array, stack, concatenate, tensordot, transpose, from_array,
choose, where, coarsen, constant, fromfunction, compute, unique, store)
from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcs... | Add "where" to top level dask.array module | Add "where" to top level dask.array module
| Python | bsd-3-clause | vikhyat/dask,minrk/dask,esc/dask,gameduell/dask,ssanderson/dask,vikhyat/dask,jayhetee/dask,mrocklin/dask,wiso/dask,dask/dask,ContinuumIO/dask,mrocklin/dask,jcrist/dask,jayhetee/dask,blaze/dask,marianotepper/dask,ContinuumIO/dask,jakirkham/dask,pombredanne/dask,chrisbarber/dask,wiso/dask,PhE/dask,freeman-lab/dask,jcrist... | ---
+++
@@ -2,7 +2,7 @@
from ..utils import ignoring
from .core import (Array, stack, concatenate, tensordot, transpose, from_array,
- choose, coarsen, constant, fromfunction, compute, unique, store)
+ choose, where, coarsen, constant, fromfunction, compute, unique, store)
from .core import (arccos... |
eef03e6c4eb6d80dd04ccbbea6b530d5679a8142 | sydent/http/servlets/pubkeyservlets.py | sydent/http/servlets/pubkeyservlets.py | # -*- coding: utf-8 -*-
# Copyright 2014 matrix.org
#
# 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 o... | # -*- coding: utf-8 -*-
# Copyright 2014 matrix.org
#
# 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 o... | Update pubkey servlet to s/signers/keyring | Update pubkey servlet to s/signers/keyring
| Python | apache-2.0 | matrix-org/sydent,matrix-org/sydent,matrix-org/sydent | ---
+++
@@ -26,7 +26,7 @@
self.sydent = syd
def render_GET(self, request):
- pubKey = self.sydent.signers.ed25519.signing_key.verify_key
+ pubKey = self.sydent.keyring.ed25519.verify_key
pubKeyHex = pubKey.encode(encoder=nacl.encoding.HexEncoder)
return json.dumps({'p... |
e6f19cc58f32b855fc1f71086dac0ad56b697ed3 | opps/articles/urls.py | opps/articles/urls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from django.conf.urls import patterns, url
from .views import OppsDetail, OppsList, Search
urlpatterns = patterns(
'',
url(r'^$', OppsList.as_view(), name='home'),
url(r'^search/', Search(), name='search'),
url(r'^(?P<channel__long_slug>[\w//-]+)/(?P<sl... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.views.decorators.cache import cache_page
from .views import OppsDetail, OppsList, Search
urlpatterns = patterns(
'',
url(r'^$', cache_page(60 * 2)(OppsList.as_view()), name='home'),
url(r'^search/', Searc... | Add cache on article page (via url) | Add cache on article page (via url)
| Python | mit | opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,williamroot/opps | ---
+++
@@ -1,17 +1,17 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-#
from django.conf.urls import patterns, url
+from django.views.decorators.cache import cache_page
from .views import OppsDetail, OppsList, Search
urlpatterns = patterns(
'',
- url(r'^$', OppsList.as_view(), name='home'),
+ ... |
cfa22fada64882a20f2daec4c8b83488920e8c3a | models/log_entry.py | models/log_entry.py |
from database import db
from conversions import datetime_from_str
class LogEntry(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, index=True)
server = db.Column(db.String(100), index=True)
log_name = db.Column(db.String(760), index=True)
message = db.Col... |
from database import db
from conversions import datetime_from_str
class LogEntry(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, index=True)
server = db.Column(db.String(100), index=True)
log_name = db.Column(db.String(255), index=True)
message = db.Col... | Reduce the size of log_name so it fits within mysql's limit. | Reduce the size of log_name so it fits within mysql's limit.
| Python | agpl-3.0 | izrik/sawmill,izrik/sawmill,izrik/sawmill | ---
+++
@@ -8,7 +8,7 @@
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, index=True)
server = db.Column(db.String(100), index=True)
- log_name = db.Column(db.String(760), index=True)
+ log_name = db.Column(db.String(255), index=True)
message = db.Column(db.Text... |
fb019fa4c277cf988d479333c6cba08a637f948a | flexget/plugins/output/dump_config.py | flexget/plugins/output/dump_config.py | from argparse import SUPPRESS
from loguru import logger
from rich.syntax import Syntax
from flexget import options, plugin
from flexget.event import event
from flexget.terminal import console
logger = logger.bind(name='dump_config')
class OutputDumpConfig:
"""
Dumps task config in STDOUT in yaml at exit or... | from argparse import SUPPRESS
import yaml
from loguru import logger
from rich.syntax import Syntax
from flexget import options, plugin
from flexget.event import event
from flexget.terminal import console
logger = logger.bind(name='dump_config')
class OutputDumpConfig:
"""
Dumps task config in STDOUT in yam... | Adjust --dump-config color theme for better readability Add jinja highlighting to --dump-config | Adjust --dump-config color theme for better readability
Add jinja highlighting to --dump-config
| Python | mit | crawln45/Flexget,Flexget/Flexget,Flexget/Flexget,Flexget/Flexget,Flexget/Flexget,crawln45/Flexget,crawln45/Flexget,crawln45/Flexget | ---
+++
@@ -1,5 +1,6 @@
from argparse import SUPPRESS
+import yaml
from loguru import logger
from rich.syntax import Syntax
@@ -18,10 +19,8 @@
@plugin.priority(plugin.PRIORITY_LAST)
def on_task_start(self, task, config):
if task.options.dump_config:
- import yaml
-
co... |
fbc4247fc7b7d36286c3f25e6ae71dfb7ebb2d39 | example/__init__.py | example/__init__.py | from pupa.scrape import Jurisdiction
from .people import PersonScraper
class Example(Jurisdiction):
jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example'
def get_metadata(self):
return {
'name': 'Example Legislature',
'url': 'http://example.com',
... | from pupa.scrape import Jurisdiction
from .people import PersonScraper
class Example(Jurisdiction):
jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example'
name = 'Example Legislature'
url = 'http://example.com'
terms = [{
'name': '2013-2014',
'sessions': ['2013'],
... | Use new-style metadata in example | Use new-style metadata in example
| Python | bsd-3-clause | rshorey/pupa,rshorey/pupa,mileswwatkins/pupa,opencivicdata/pupa,datamade/pupa,mileswwatkins/pupa,influence-usa/pupa,influence-usa/pupa,datamade/pupa,opencivicdata/pupa | ---
+++
@@ -5,28 +5,23 @@
class Example(Jurisdiction):
jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example'
-
- def get_metadata(self):
- return {
- 'name': 'Example Legislature',
- 'url': 'http://example.com',
- 'terms': [{
- 'name':... |
07da63a9ac95a054332297638df17fcf00ac4291 | core/components/security/factor.py | core/components/security/factor.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from u2flib_server.u2f import (begin_registration,
begin_authentication,
complete_registration,
complete_authentication)
from components.eternity import config
facet... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from u2flib_server.u2f import (begin_registration,
begin_authentication,
complete_registration,
complete_authentication)
from components.eternity import config
facet... | Fix server error when login with u2f | Fix server error when login with u2f
| Python | mit | chiaki64/Windless,chiaki64/Windless | ---
+++
@@ -34,6 +34,7 @@
return user, json.dumps(challenge.data_for_client)
async def verify(user, data):
+ print(user)
challenge = user.pop('_u2f_challenge_')
try:
complete_authentication(challenge, data, [facet]) |
4c484a29480ec9d85a87ac7c2aaf09ced7d15457 | nn/file/__init__.py | nn/file/__init__.py | import functools
import tensorflow as tf
from . import cnn_dailymail_rc
from ..flags import FLAGS
READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files }
def read_files(file_pattern, file_format):
return READERS[file_format](_file_pattern_to_names(file_pattern))
def _file_pattern_to_names(pattern):
re... | import functools
import tensorflow as tf
from . import cnn_dailymail_rc
from .. import collections
from ..flags import FLAGS
from ..util import func_scope
READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files }
@func_scope
def read_files(file_pattern, file_format):
return monitored_batch_queue(
*REA... | Monitor number of batches in a input batch queue | Monitor number of batches in a input batch queue
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten | ---
+++
@@ -2,18 +2,39 @@
import tensorflow as tf
from . import cnn_dailymail_rc
+from .. import collections
from ..flags import FLAGS
+from ..util import func_scope
READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files }
+@func_scope
def read_files(file_pattern, file_format):
- return READERS... |
c0c59a9c5d3aa2d7ed50e8e895f1a3e02a4ae380 | Basic-Number-Guessing-Game-Challenge.py | Basic-Number-Guessing-Game-Challenge.py | import random
attempts = 1
number = str(random.randint(1, 100))
while True:
print number
if raw_input("Guess (1 - 100): ") == number:
print "Correct!"
print "It Only Took You", attempts, "Attempts!" if attempts > 1 else "Attempt!"
break
else:
print "Incorrect, Guess Again!"
... | import random
attempts = 1
number = random.randint(1, 100)
while True:
guess = raw_input("Guess (1 - 100): ")
if guess.isdigit():
guess = int(guess)
if 1 <= guess and guess <= 100:
if guess == number:
print "Correct!"
print "It Only Took You", attempt... | Verify that the guess is a number, that it is between 1 and 100, and tells the user if the guessed number is too high or low. | Verify that the guess is a number, that it is between 1 and 100, and tells the user if the guessed number is too high or low.
| Python | mit | RascalTwo/Basic-Number-Guessing-Game-Challenge | ---
+++
@@ -1,13 +1,22 @@
import random
attempts = 1
-number = str(random.randint(1, 100))
+number = random.randint(1, 100)
while True:
- print number
- if raw_input("Guess (1 - 100): ") == number:
- print "Correct!"
- print "It Only Took You", attempts, "Attempts!" if attempts > 1 else "Atte... |
21e3eac740f54194954d01d517aca0eb841ca1b3 | wagtail/search/apps.py | wagtail/search/apps.py | from django.apps import AppConfig
from django.core.checks import Tags, Warning, register
from django.db import connection
from django.utils.translation import gettext_lazy as _
from wagtail.search.signal_handlers import register_signal_handlers
class WagtailSearchAppConfig(AppConfig):
name = 'wagtail.search'
... | from django.apps import AppConfig
from django.core.checks import Tags, Warning, register
from django.db import connection
from django.utils.translation import gettext_lazy as _
from wagtail.search.signal_handlers import register_signal_handlers
class WagtailSearchAppConfig(AppConfig):
name = 'wagtail.search'
... | Add alternative warning if sqlite is >=3.19 but is missing fts5 support | Add alternative warning if sqlite is >=3.19 but is missing fts5 support
| Python | bsd-3-clause | torchbox/wagtail,torchbox/wagtail,torchbox/wagtail,torchbox/wagtail | ---
+++
@@ -27,6 +27,11 @@
def check_if_sqlite_version_is_supported(app_configs, **kwargs):
if connection.vendor == 'sqlite':
import sqlite3
+
+ from wagtail.search.backends.database.sqlite.utils import fts5_available
+
if sqlite3.sqlite_version_info < (3, 19, 0):
... |
cdfeac780643ddd2502c17f4cd7d949018de8b06 | warehouse/__about__.py | warehouse/__about__.py | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | Add back the development marker | Add back the development marker
| Python | apache-2.0 | mattrobenolt/warehouse,robhudson/warehouse,techtonik/warehouse,robhudson/warehouse,mattrobenolt/warehouse,techtonik/warehouse,mattrobenolt/warehouse | ---
+++
@@ -26,7 +26,7 @@
__summary__ = "Next Generation Python Package Repository"
__uri__ = "https://github.com/dstufft/warehouse"
-__version__ = "13.10.10"
+__version__ = "13.10.10.dev0"
__build__ = "<development>"
__author__ = "Donald Stufft" |
7473a70893a0f31ba717e26a3f508d0adc5026f9 | osbrain/__init__.py | osbrain/__init__.py | import Pyro4
Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle')
Pyro4.config.SERIALIZER = 'pickle'
Pyro4.config.THREADPOOL_SIZE = 16
Pyro4.config.SERVERTYPE = 'multiplex'
# TODO: should we set COMMTIMEOUT as well?
Pyro4.config.DETAILED_TRACEBACK = True
__version__ = '0.2.1'
from .core import BaseAgent, Agent, run_agent
... | import Pyro4
Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle')
Pyro4.config.SERIALIZER = 'pickle'
Pyro4.config.THREADPOOL_SIZE = 16
Pyro4.config.SERVERTYPE = 'multiplex'
Pyro4.config.REQUIRE_EXPOSE = False
# TODO: should we set COMMTIMEOUT as well?
Pyro4.config.DETAILED_TRACEBACK = True
__version__ = '0.2.1'
from .core... | Make osBrain compatible with latest Pyro4 changes | Make osBrain compatible with latest Pyro4 changes
| Python | apache-2.0 | opensistemas-hub/osbrain | ---
+++
@@ -3,6 +3,7 @@
Pyro4.config.SERIALIZER = 'pickle'
Pyro4.config.THREADPOOL_SIZE = 16
Pyro4.config.SERVERTYPE = 'multiplex'
+Pyro4.config.REQUIRE_EXPOSE = False
# TODO: should we set COMMTIMEOUT as well?
Pyro4.config.DETAILED_TRACEBACK = True
|
e12de19ae37a6f3fa0335ecfd0db00b18badf730 | website/files/utils.py | website/files/utils.py |
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
ass... |
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
ass... | Check for a fileversion region before copying them to the source region | Check for a fileversion region before copying them to the source region
This is mainly for test fileversions that are created without regions by default
| Python | apache-2.0 | aaxelb/osf.io,felliott/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,mattclark/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,cslzchen/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,adlius/osf.io,felliott/osf.io,Johnetordoff/osf.io,caseyrollins/os... | ---
+++
@@ -18,7 +18,7 @@
if src.is_file and src.versions.exists():
fileversions = src.versions.select_related('region').order_by('-created')
most_recent_fileversion = fileversions.first()
- if most_recent_fileversion.region != target_node.osfstorage_region:
+ if most_recent_filev... |
7e046e4999959e0cfa3527780ca04e581698b328 | cbagent/collectors/libstats/psstats.py | cbagent/collectors/libstats/psstats.py | from fabric.api import run
from cbagent.collectors.libstats.remotestats import (
RemoteStats, multi_node_task)
class PSStats(RemoteStats):
METRICS = (
("rss", 1024), # kB -> B
("vsize", 1024),
)
def __init__(self, hosts, user, password):
super(PSStats, self).__init__(host... | from fabric.api import run
from cbagent.collectors.libstats.remotestats import (
RemoteStats, multi_node_task)
class PSStats(RemoteStats):
METRICS = (
("rss", 1024), # kB -> B
("vsize", 1024),
)
def __init__(self, hosts, user, password):
super(PSStats, self).__init__(host... | Make `top` work on Ubuntu 12.04 | MB-13234: Make `top` work on Ubuntu 12.04
The `top` in Ubuntu12.04 seems to do different command line parsing
than the one on CentOS. Separating the parameters should work on
both.
Change-Id: I8f9ec022bcb8e0158316fdaac226acbfb0d9d004
Reviewed-on: http://review.couchbase.org/50126
Reviewed-by: Dave Rigby <a09264da4832... | Python | apache-2.0 | mikewied/cbagent,couchbase/cbagent | ---
+++
@@ -15,7 +15,7 @@
super(PSStats, self).__init__(hosts, user, password)
self.ps_cmd = "ps -eo pid,rss,vsize,comm | " \
"grep {} | grep -v grep | sort -n -k 2 | tail -n 1"
- self.top_cmd = "top -bn2d1 -p {} | grep {}"
+ self.top_cmd = "top -bn2 -d1 -p {} | ... |
b4482c257c5333f902569b40bf4e61c8003dbacc | www/config/__init__.py | www/config/__init__.py | from __future__ import unicode_literals
try:
from local import *
except ImportError:
try:
from dev import *
except ImportError:
pass
try:
DEBUG
TEMPLATE_DEBUG
DATABASES['default']
CELERY_BROKER
except NameError:
raise NameError('Required config values not found. Abort !') | from __future__ import unicode_literals, absolute_import
try:
from .local import *
except ImportError:
try:
from dev import *
except ImportError:
pass
try:
DEBUG
TEMPLATE_DEBUG
DATABASES['default']
CELERY_BROKER
except NameError:
raise NameError('Required config values not found. Abort !') | Use absolute import to correctly import local.py config file | Use absolute import to correctly import local.py config file
| Python | agpl-3.0 | UrLab/beta402,UrLab/beta402,UrLab/DocHub,UrLab/DocHub,UrLab/beta402,UrLab/DocHub,UrLab/DocHub | ---
+++
@@ -1,7 +1,7 @@
-from __future__ import unicode_literals
+from __future__ import unicode_literals, absolute_import
try:
- from local import *
+ from .local import *
except ImportError:
try:
from dev import * |
bf7626df74d78f2811f20173fb21c36a96cc9500 | packages/gtk-doc.py | packages/gtk-doc.py | GnomePackage ('gtk-doc', version_major = '1', version_minor = '17', sources = [
'http://ftp.gnome.org/pub/gnome/sources/%{name}/%{version}/%{name}-%{version}.tar.bz2'
])
| GnomePackage ('gtk-doc', version_major = '1', version_minor = '17', configure_flags = ['--with-xml-catalog="%{prefix}/etc/xml/catalog"'], sources = [
'http://ftp.gnome.org/pub/gnome/sources/%{name}/%{version}/%{name}-%{version}.tar.bz2'
])
| Set xml catalog to the right prefix. | Set xml catalog to the right prefix.
| Python | mit | BansheeMediaPlayer/bockbuild,mono/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild | ---
+++
@@ -1,3 +1,3 @@
-GnomePackage ('gtk-doc', version_major = '1', version_minor = '17', sources = [
+GnomePackage ('gtk-doc', version_major = '1', version_minor = '17', configure_flags = ['--with-xml-catalog="%{prefix}/etc/xml/catalog"'], sources = [
'http://ftp.gnome.org/pub/gnome/sources/%{name}/%{ver... |
5be3d07995803d81e6238a561c772e856b81a367 | icekit/templatetags/search_tags.py | icekit/templatetags/search_tags.py | from django.template import Library, Node
from django.test.client import RequestFactory
register = Library()
factory = RequestFactory()
class FakeRequestNode(Node):
def render(self, context):
req = factory.get('/')
req.notifications = []
context['request'] = req
return ''
@reg... | from django.contrib.auth.models import AnonymousUser
from django.template import Library, Node
from django.test.client import RequestFactory
register = Library()
factory = RequestFactory()
class FakeRequestNode(Node):
def render(self, context):
req = factory.get('/')
req.notifications = []
... | Add anonymous user to fake request object. | Add anonymous user to fake request object.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -1,3 +1,4 @@
+from django.contrib.auth.models import AnonymousUser
from django.template import Library, Node
from django.test.client import RequestFactory
@@ -10,6 +11,7 @@
def render(self, context):
req = factory.get('/')
req.notifications = []
+ req.user = AnonymousUser(... |
94b6b97dc1e706a6560092aa29cbe4e21f052924 | froide/account/apps.py | froide/account/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AccountConfig(AppConfig):
name = 'froide.account'
verbose_name = _("Account")
def ready(self):
from froide.bounce.signals import user_email_bounced
user_email_bounced.connect(deactivate_user_a... | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from .menu import menu_registry, MenuItem
class AccountConfig(AppConfig):
name = 'froide.account'
verbose_name = _("Account")
def ready(self):
from froide.bounce.signals impo... | Make settings and requests menu items | Make settings and requests menu items | Python | mit | fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide | ---
+++
@@ -1,5 +1,8 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
+from django.urls import reverse
+
+from .menu import menu_registry, MenuItem
class AccountConfig(AppConfig):
@@ -11,6 +14,9 @@
user_email_bounced.connect(deactivate_user_after_bounce)
... |
2538ca440620de8ed08510e0ae902c82184a9daa | consts/auth_type.py | consts/auth_type.py | class AuthType(object):
"""
An auth type defines what write privileges an authenticated agent has.
"""
MATCH_VIDEO = 0
EVENT_TEAMS = 1
EVENT_MATCHES = 2
EVENT_RANKINGS = 3
EVENT_ALLIANCES = 4
EVENT_AWARDS = 5
type_names = {
MATCH_VIDEO: "match video",
EVENT_TEAMS... | class AuthType(object):
"""
An auth type defines what write privileges an authenticated agent has.
"""
EVENT_DATA = 0
MATCH_VIDEO = 1
EVENT_TEAMS = 2
EVENT_MATCHES = 3
EVENT_RANKINGS = 4
EVENT_ALLIANCES = 5
EVENT_AWARDS = 6
type_names = {
EVENT_DATA: "event data",
... | Revert "Remove AuthType.EVENT_DATA and renumber" | Revert "Remove AuthType.EVENT_DATA and renumber"
This reverts commit 38248941eb47a04b82fe52e1adca7387dafcf7f3.
| Python | mit | phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-bl... | ---
+++
@@ -2,14 +2,16 @@
"""
An auth type defines what write privileges an authenticated agent has.
"""
- MATCH_VIDEO = 0
- EVENT_TEAMS = 1
- EVENT_MATCHES = 2
- EVENT_RANKINGS = 3
- EVENT_ALLIANCES = 4
- EVENT_AWARDS = 5
+ EVENT_DATA = 0
+ MATCH_VIDEO = 1
+ EVENT_TEAMS = 2
... |
e7df1e7f3e9d8afd5cf1892df2f136751b276136 | aio_pika/transaction.py | aio_pika/transaction.py | import asyncio
from enum import Enum
import aiormq
class TransactionStates(Enum):
created = "created"
commited = "commited"
rolled_back = "rolled back"
started = "started"
class Transaction:
def __str__(self):
return self.state.value
def __init__(self, channel):
self.loop =... | import asyncio
from enum import Enum
import aiormq
class TransactionStates(Enum):
created = "created"
commited = "commited"
rolled_back = "rolled back"
started = "started"
class Transaction:
def __str__(self):
return self.state.value
def __init__(self, channel):
self.loop =... | Return self instead of select result in __aenter__ | Return self instead of select result in __aenter__ | Python | apache-2.0 | mosquito/aio-pika | ---
+++
@@ -54,7 +54,8 @@
return result
async def __aenter__(self):
- return await self.select()
+ await self.select()
+ return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if exc_type: |
e0990fcdb7e5e1c90762a71ced7492e28f24c903 | raven/utils/compat.py | raven/utils/compat.py | """
raven.utils.compat
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
try:
from urllib.error import HTTPError
except ImportError:
from urllib2 import HTTPError
try:
from urllib.request import Request... | """
raven.utils.compat
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
try:
from urllib.error import HTTPError
except ImportError:
from urllib2 import HTTPError
try:
from urllib.request import Request... | Use unittest2 if available and gracefully falls back to unittest. | Use unittest2 if available and gracefully falls back to unittest.
| Python | bsd-3-clause | getsentry/raven-python,lepture/raven-python,recht/raven-python,nikolas/raven-python,nikolas/raven-python,inspirehep/raven-python,dbravender/raven-python,smarkets/raven-python,percipient/raven-python,Photonomie/raven-python,ronaldevers/raven-python,danriti/raven-python,someonehan/raven-python,smarkets/raven-python,Photo... | ---
+++
@@ -37,7 +37,7 @@
try:
+ from unittest2 import TestCase, skipIf
+except ImportError:
from unittest import TestCase, skipIf
-except ImportError:
- from unittest2 import TestCase, skipIf
|
cbb0ed5ed66571feba22413472a5fe1a20824dbd | shared_export.py | shared_export.py | import bpy
def find_seqs(scene, select_marker):
sequences = {}
sequence_flags = {}
for marker in scene.timeline_markers:
if ":" not in marker.name or (select_marker and not marker.select):
continue
name, what = marker.name.rsplit(":", 1)
if name not in sequences:
... | import bpy
def find_seqs(scene, select_marker):
sequences = {}
sequence_flags = {}
for marker in scene.timeline_markers:
if ":" not in marker.name or (select_marker and not marker.select):
continue
name, what = marker.name.rsplit(":", 1)
what = what.lower()
if... | Make sequence marker types (:type) case insensitive | Make sequence marker types (:type) case insensitive
| Python | mit | qoh/io_scene_dts,portify/io_scene_dts | ---
+++
@@ -9,6 +9,7 @@
continue
name, what = marker.name.rsplit(":", 1)
+ what = what.lower()
if name not in sequences:
sequences[name] = {} |
7ceba1f2b83628a2b89ffbdd30e435970e8c5e91 | tests/test_kafka_streams.py | tests/test_kafka_streams.py | """
Test the top-level Kafka Streams class
"""
import pytest
from winton_kafka_streams import kafka_config
from winton_kafka_streams.errors.kafka_streams_error import KafkaStreamsError
from winton_kafka_streams.kafka_streams import KafkaStreams
from winton_kafka_streams.processor.processor import BaseProcessor
from ... | """
Test the top-level Kafka Streams class
"""
import pytest
from winton_kafka_streams import kafka_config
from winton_kafka_streams.errors.kafka_streams_error import KafkaStreamsError
from winton_kafka_streams.kafka_streams import KafkaStreams
from winton_kafka_streams.processor.processor import BaseProcessor
from ... | Use more Pythonic name for test. | Use more Pythonic name for test.
| Python | apache-2.0 | wintoncode/winton-kafka-streams | ---
+++
@@ -16,7 +16,7 @@
pass
-def test_Given_StreamAlreadyStarted_When_CallStartAgain_Then_RaiseError():
+def test__given__stream_already_started__when__call_start_again__then__raise_error():
kafka_config.NUM_STREAM_THREADS = 0
topology_builder = TopologyBuilder()
|
3fb1800548ad421520bf3f2845aad4f51f6f5839 | rapidsms_multimodem/tests/__init__.py | rapidsms_multimodem/tests/__init__.py | from test_utils import * # noqa
from test_views import * # noqa
| from test_outgoing import * # noqa
from test_utils import * # noqa
from test_views import * # noqa
| Add import for older versions of Django | Add import for older versions of Django
| Python | bsd-3-clause | caktus/rapidsms-multimodem | ---
+++
@@ -1,2 +1,3 @@
+from test_outgoing import * # noqa
from test_utils import * # noqa
from test_views import * # noqa |
075b11aa830c9a5961e9ee63e42484192990f7d3 | tools/misc/python/test-data-in-out.py | tools/misc/python/test-data-in-out.py | # TOOL test-data-in-out.py: "Test data input and output in Python" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# OUTPUT OPTIONAL missing_output.txt
import shutil
shutil.copyfile('input', 'output')
| # TOOL test-data-in-out.py: "Test data input and output in Python" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# PARAMETER delay: Delay TYPE INTEGER FROM 0 TO 1000 DEFAULT 1 (Delay in seconds)
import shutil
import time
time.sleep(delay)
shutil.copyfile('input', 'output')
| Add delay to input-output test | Add delay to input-output test
| Python | mit | chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools | ---
+++
@@ -1,9 +1,11 @@
# TOOL test-data-in-out.py: "Test data input and output in Python" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
-# OUTPUT OPTIONAL missing_output.txt
+# PARAMETER delay: Delay TYPE INTEGER FROM 0 TO 1000 DEFAULT 1 (Delay in seconds)
import shutil
+import time
... |
943d2648c17facb9dbfd4f26d335beef341e9c49 | fabfile.py | fabfile.py | from fabric.api import local
__author__ = 'derek'
def deploy(version):
local('python runtests.py')
local("git tag -a %s -m %s" % (version, version))
local('python setup.py sdist upload') | from fabric.api import local
__author__ = 'derek'
def deploy(version):
local('python runtests.py')
local("git tag -a %s -m %s" % (version, version))
local("git push origin --tags")
local('python setup.py sdist upload') | Make sure to push the tags | Make sure to push the tags
| Python | mit | winfieldco/django-mail-queue,Goury/django-mail-queue,Goury/django-mail-queue,dstegelman/django-mail-queue,dstegelman/django-mail-queue,styrmis/django-mail-queue | ---
+++
@@ -6,4 +6,5 @@
def deploy(version):
local('python runtests.py')
local("git tag -a %s -m %s" % (version, version))
+ local("git push origin --tags")
local('python setup.py sdist upload') |
3e23d60857461b7806f3616cf41b2cd9c812fa7b | fabfile.py | fabfile.py | from fabric.api import cd, sudo, env
import os
expected_vars = [
'PROJECT',
]
for var in expected_vars:
if var not in os.environ:
raise Exception('Please specify %s environment variable' % (
var,))
PROJECT = os.environ['PROJECT']
USER = os.environ.get('USER', 'jmbo')
env.path = os.path.j... | from fabric.api import cd, sudo, env
import os
expected_vars = [
'PROJECT',
]
for var in expected_vars:
if var not in os.environ:
raise Exception('Please specify %s environment variable' % (
var,))
PROJECT = os.environ['PROJECT']
USER = os.environ.get('USER', 'jmbo')
env.path = os.path.j... | Make env.path to /var/praekelt/<PROJECT> an absolute path. | Make env.path to /var/praekelt/<PROJECT> an absolute path.
| Python | bsd-3-clause | praekelt/go-rts-zambia | ---
+++
@@ -13,7 +13,7 @@
PROJECT = os.environ['PROJECT']
USER = os.environ.get('USER', 'jmbo')
-env.path = os.path.join('var', 'praekelt', PROJECT)
+env.path = os.path.join('/', 'var', 'praekelt', PROJECT)
def restart(): |
e660d8e05e54adbd0ea199a02cc188dc7007089a | fabfile.py | fabfile.py | from fabric.api import cd, sudo, env
import os
expected_vars = [
'PROJECT',
]
for var in expected_vars:
if var not in os.environ:
raise Exception('Please specify %s environment variable' % (
var,))
PROJECT = os.environ['PROJECT']
USER = os.environ.get('USER', 'jmbo')
env.path = os.path.j... | from fabric.api import cd, sudo, env
import os
PROJECT = os.environ.get('PROJECT', 'go-rts-zambia')
DEPLOY_USER = os.environ.get('DEPLOY_USER', 'jmbo')
env.path = os.path.join('/', 'var', 'praekelt', PROJECT)
def restart():
sudo('/etc/init.d/nginx restart')
sudo('supervisorctl reload')
def deploy():
w... | Fix USER in fabric file (the deploy user and ssh user aren't necessarily the same). Set default value for PROJECT (this is the go-rts-zambia repo after all). | Fix USER in fabric file (the deploy user and ssh user aren't necessarily the same). Set default value for PROJECT (this is the go-rts-zambia repo after all).
| Python | bsd-3-clause | praekelt/go-rts-zambia | ---
+++
@@ -1,17 +1,8 @@
from fabric.api import cd, sudo, env
import os
-expected_vars = [
- 'PROJECT',
-]
-
-for var in expected_vars:
- if var not in os.environ:
- raise Exception('Please specify %s environment variable' % (
- var,))
-
-PROJECT = os.environ['PROJECT']
-USER = os.environ.... |
04e8206a8610666c6027fc0f4be5e786e4bd5513 | fabfile.py | fabfile.py | set(
fab_hosts = ['startthedark.com'],
fab_user = 'startthedark',
)
def unlink_nginx():
'Un-link nginx rules for startthedark.'
sudo('rm -f /etc/nginx/sites-enabled/startthedark.com')
sudo('/etc/init.d/nginx reload')
def link_nginx():
'Link nginx rules for startthedark'
sudo('ln -s /etc/ng... | set(
fab_hosts = ['startthedark.com'],
fab_user = 'startthedark',
)
def unlink_nginx():
'Un-link nginx rules for startthedark.'
sudo('rm -f /etc/nginx/sites-enabled/startthedark.com')
sudo('/etc/init.d/nginx reload')
def link_nginx():
'Link nginx rules for startthedark'
sudo('ln -s /etc/ng... | Split out the css rebuilding into its own fab method. | Split out the css rebuilding into its own fab method.
| Python | bsd-3-clause | mvayngrib/startthedark,mvayngrib/startthedark,ericflo/startthedark,ericflo/startthedark,mvayngrib/startthedark,ericflo/startthedark | ---
+++
@@ -13,13 +13,13 @@
sudo('ln -s /etc/nginx/sites-available/startthedark.com /etc/nginx/sites-enabled/startthedark.com')
sudo('/etc/init.d/nginx reload')
+def rebuild_prod_css():
+ local('bash make_prod_css.sh')
+ local('git commit -a -m "Rebuilt Prod CSS For Commit"')
+ local('git push or... |
b8b72be48328ba0bc6e946a4ecf15c00f5f8b3b6 | director/director/config/dev.py | director/director/config/dev.py | import imp
import os
import sys
import traceback
from os.path import dirname
from configurations import values
from .common import Common, BASE_DIR, external_keys
SECRETS_DIR = os.path.join(dirname(BASE_DIR), "secrets")
class Dev(Common):
DEBUG = True
INSTALLED_APPS = Common.INSTALLED_APPS + [
'dj... | import imp
import os
import sys
import traceback
from os.path import dirname
from configurations import values
from .common import Common, BASE_DIR, external_keys
SECRETS_DIR = os.path.join(dirname(BASE_DIR), "secrets")
class Dev(Common):
DEBUG = True
INSTALLED_APPS = Common.INSTALLED_APPS + [
'dj... | Print message when secrets file is missing | Print message when secrets file is missing
| Python | apache-2.0 | stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub | ---
+++
@@ -24,11 +24,14 @@
def setup(cls):
super(Dev, cls).setup()
filename = "director_dev_secrets.py"
+ path = os.path.join(SECRETS_DIR, filename)
try:
- dev_secrets = imp.load_source(
- "dev_secrets", os.path.join(SECRETS_DIR, filename))
+ ... |
9e90fe6523e7d61d6b94f9bb37a2dbf711cd3b83 | example/__init__.py | example/__init__.py | """An example application using Confit for configuration."""
from __future__ import print_function
from __future__ import unicode_literals
import confit
import argparse
config = confit.LazyConfig('ConfitExample', __name__)
def main():
parser = argparse.ArgumentParser(description='example Confit program')
pa... | """An example application using Confit for configuration."""
from __future__ import print_function
from __future__ import unicode_literals
import confit
import argparse
config = confit.LazyConfig('ConfitExample', __name__)
def main():
parser = argparse.ArgumentParser(description='example Confit program')
pa... | Fix example to use get | Fix example to use get
| Python | mit | sampsyo/confit,sampsyo/confuse | ---
+++
@@ -29,7 +29,7 @@
config['log']['level'] = 2
else:
config['log']['level'] = 0
- print('logging level is', config['log']['level'].validate(int))
+ print('logging level is', config['log']['level'].get(int))
# Some validated/converted values.
print('directory is', config[... |
b575099c0d1f23916038172d46852a264a5f5a95 | bluebottle/utils/staticfiles_finders.py | bluebottle/utils/staticfiles_finders.py | from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in t... | from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in t... | Fix static files finder errors | Fix static files finder errors
| Python | bsd-3-clause | jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle | ---
+++
@@ -17,8 +17,9 @@
"""
tenants = Client.objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
+
if not tenant_dir:
- return
+ return []
for tenant in tenants:
if "{0}/".format(tenant.client_name) in path:
@@ -26,... |
d52d8ce18745d5ec0e722340cf09735938c8a0c0 | src/BaseUtils.py | src/BaseUtils.py | '''
Base NLP utilities
'''
def get_words(sentence):
''' Return all the words found in a sentence.
Ignore whitespace and all punctuation
>>> get_words('a most interesting piece')
>>> ['a', 'most', 'interesting', 'piece']
>>> get_words('a, most$ **interesting piece')
>>> ['a', 'most', 'interes... | '''
Base NLP utilities
'''
def get_words(sentence):
''' Return all the words found in a sentence.
Ignore whitespace and all punctuation
>>> get_words('a most interesting piece')
>>> ['a', 'most', 'interesting', 'piece']
>>> get_words('a, most$ **interesting piece')
>>> ['a', 'most', 'interes... | Replace ASCII checking chars and space with library methods | Replace ASCII checking chars and space with library methods
| Python | bsd-2-clause | ambidextrousTx/RNLTK | ---
+++
@@ -11,9 +11,8 @@
>>> get_words('a, most$ **interesting piece')
>>> ['a', 'most', 'interesting', 'piece']
'''
- clean_sentence = ''.join([char for char in sentence if ord(char) in
- xrange(97, 123) or ord(char) in xrange(75, 91)
- or ... |
716d967971d9ea23ab54d327231ba873b681a7c7 | isserviceup/services/models/service.py | isserviceup/services/models/service.py | from enum import Enum
class Status(Enum):
ok = 1 # green
maintenance = 2 # blue
minor = 3 # yellow
major = 4 # orange
critical = 5 # red
unavailable = 6 # gray
class Service(object):
@property
def id(self):
return self.__class_... | from enum import Enum
class Status(Enum):
ok = 1 # green
maintenance = 2 # blue
minor = 3 # yellow
major = 4 # orange
critical = 5 # red
unavailable = 6 # gray
class Service(object):
@property
def id(self):
return self.__class_... | Add icon_url as abstract property | Add icon_url as abstract property
| Python | apache-2.0 | marcopaz/is-service-up,marcopaz/is-service-up,marcopaz/is-service-up | ---
+++
@@ -21,6 +21,10 @@
raise NotImplemented()
@property
+ def icon_url(self):
+ raise NotImplemented()
+
+ @property
def name(self):
raise NotImplemented()
|
5233e6d7f7d4f494f62576206ede87d13e8f760d | calexicon/calendars/tests/test_other.py | calexicon/calendars/tests/test_other.py | from datetime import date as vanilla_date
from calendar_testing import CalendarTest
from calexicon.calendars.other import JulianDayNumber
class TestJulianDayNumber(CalendarTest):
def setUp(self):
self.calendar = JulianDayNumber()
def test_make_date(self):
vd = vanilla_date(2010, 8, 1)
... | from datetime import date as vanilla_date
from calendar_testing import CalendarTest
from calexicon.calendars.other import JulianDayNumber
class TestJulianDayNumber(CalendarTest):
def setUp(self):
self.calendar = JulianDayNumber()
def test_make_date(self):
vd = vanilla_date(2010, 8, 1)
... | Add a test to check the right number of days in 400 year cycles. | Add a test to check the right number of days in 400 year cycles.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual | ---
+++
@@ -23,5 +23,10 @@
d = self.calendar.from_date(vd)
self.assertEqual(d.native_representation(), {'day_number': number})
- def test_other_date(self):
+ def test_every_400_years(self):
+ days_in_400_years = 400 * 365 + 97
+ for i in range(25):
+ self.compare_dat... |
03fb3e68f9ec9432a25c60bda06fcd49d604befc | src/__init__.py | src/__init__.py | from ..override_audit import reload
reload("src", ["core", "events", "contexts", "browse", "settings_proxy"])
reload("src.commands")
from . import core
from .core import *
from .events import *
from .contexts import *
from .settings_proxy import *
from .commands import *
__all__ = [
# core
"core",
# bro... | from ..override_audit import reload
reload("src", ["core", "events", "contexts", "browse", "settings_proxy"])
reload("src.commands")
from . import core
from .core import *
from .events import *
from .contexts import *
from .settings_proxy import *
from .commands import *
__all__ = [
# core
"core",
# bro... | Add missing event listener for new overrides | Add missing event listener for new overrides
While rolling the test code for creating overrides into the base code,
we remembered to make sure that we put the event handler used to handle
override creation in place but forgot to export them to to the base
plugin so that it would actually do something.
| Python | mit | OdatNurd/OverrideAudit | ---
+++
@@ -23,6 +23,7 @@
# events/contexts
"OverrideAuditEventListener",
+ "CreateOverrideEventListener",
"OverrideAuditContextListener",
# commands/* |
f46770697d668e31518ada41d31fdb59a84f3cf6 | kokki/cookbooks/aws/recipes/default.py | kokki/cookbooks/aws/recipes/default.py |
from kokki import *
Package("python-boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol['volume_id'],
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = "attach")
if vol.get('fstype'):
... |
import os
from kokki import *
# Package("python-boto")
Execute("pip install git+http://github.com/boto/boto.git#egg=boto",
not_if = 'python -c "import boto"')
Execute("mv /usr/lib/pymodules/python2.6/boto /tmp/boto.orig",
only_if = os.path.exists("/usr/lib/pymodules/python2.6/boto"))
# Mount volumes and form... | Install github verison of boto in aws cookbook (for now) | Install github verison of boto in aws cookbook (for now)
| Python | bsd-3-clause | samuel/kokki | ---
+++
@@ -1,7 +1,12 @@
+import os
from kokki import *
-Package("python-boto")
+# Package("python-boto")
+Execute("pip install git+http://github.com/boto/boto.git#egg=boto",
+ not_if = 'python -c "import boto"')
+Execute("mv /usr/lib/pymodules/python2.6/boto /tmp/boto.orig",
+ only_if = os.path.exists("/u... |
183f9455425fa63b6ca43c5d4fe650bcf2179da5 | ironic/drivers/modules/storage/noop.py | ironic/drivers/modules/storage/noop.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Update should_write_image to return False | Update should_write_image to return False
Update should_write_image to return False | Python | apache-2.0 | SauloAislan/ironic,SauloAislan/ironic | ---
+++
@@ -29,4 +29,4 @@
pass
def should_write_image(self, task):
- return True
+ return False |
ae689c9de698daeaf8ab5275c384183cb665c903 | neutron_classifier/common/constants.py | neutron_classifier/common/constants.py | # Copyright (c) 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | # Copyright (c) 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | Remove CLASSIFIER_TYPES constant - it was never used | Remove CLASSIFIER_TYPES constant - it was never used
Change-Id: Ia6ba4453f6bc9b9de0da1e83d2dc75147fb91882
| Python | apache-2.0 | openstack/neutron-classifier,openstack/neutron-classifier | ---
+++
@@ -12,10 +12,6 @@
# License for the specific language governing permissions and limitations
# under the License.
-CLASSIFIER_TYPES = ['ip_classifier', 'ipv4_classifier', 'ipv6_classifier',
- 'transport_classifier', 'ethernet_classifier',
- 'encapsulation_classifier',... |
15db774538b4fa18c0653fb741ba14c0373867c8 | main/admin/forms.py | main/admin/forms.py | from django import forms
from main.models import Profile, LanProfile
class AdminLanProfileForm(forms.ModelForm):
class Meta:
model = LanProfile
fields = '__all__'
class AdminProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = '__all__'
def __init__(self, ... | from django import forms
from main.models import Profile, LanProfile, GRADES
class AdminLanProfileForm(forms.ModelForm):
class Meta:
model = LanProfile
fields = '__all__'
class AdminProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = '__all__'
grade = for... | Make that work with admin too | Make that work with admin too
| Python | mit | bomjacob/htxaarhuslan,bomjacob/htxaarhuslan,bomjacob/htxaarhuslan | ---
+++
@@ -1,6 +1,6 @@
from django import forms
-from main.models import Profile, LanProfile
+from main.models import Profile, LanProfile, GRADES
class AdminLanProfileForm(forms.ModelForm):
@@ -14,6 +14,8 @@
model = Profile
fields = '__all__'
+ grade = forms.ChoiceField(GRADES, require... |
c557058a7a7206167108535129bc0b160e4fe62b | nipype/testing/tests/test_utils.py | nipype/testing/tests/test_utils.py | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Test testing utilities
"""
from nipype.testing.utils import TempFATFS
from nose.tools import assert_true
def test_tempfatfs():
with TempFATFS() as tmpdir:
yield assert_true, tmpdir is not ... | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Test testing utilities
"""
import os
import warnings
from nipype.testing.utils import TempFATFS
from nose.tools import assert_true
def test_tempfatfs():
try:
fatfs = TempFATFS()
except... | Add warning for TempFATFS test | TEST: Add warning for TempFATFS test
| Python | bsd-3-clause | mick-d/nipype,carolFrohlich/nipype,FCP-INDI/nipype,sgiavasis/nipype,mick-d/nipype,FCP-INDI/nipype,FCP-INDI/nipype,carolFrohlich/nipype,carolFrohlich/nipype,FCP-INDI/nipype,mick-d/nipype,sgiavasis/nipype,mick-d/nipype,carolFrohlich/nipype,sgiavasis/nipype,sgiavasis/nipype | ---
+++
@@ -3,10 +3,17 @@
"""Test testing utilities
"""
+import os
+import warnings
from nipype.testing.utils import TempFATFS
from nose.tools import assert_true
def test_tempfatfs():
- with TempFATFS() as tmpdir:
- yield assert_true, tmpdir is not None
+ try:
+ fatfs = TempFATFS()
+ ... |
44547695f662c957f5242f7cfefd328b33d99830 | sso/backends.py | sso/backends.py | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from hashlib import sha1
class SimpleHashModelBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(username=username)
except User.Does... | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from hashlib import sha1
class SimpleHashModelBackend(ModelBackend):
supports_anonymous_user = False
supports_object_permissions = False
supports_inactive_user = False
def authenticate(self, username=No... | Update the authentication backend with upcoming features | Update the authentication backend with upcoming features
| Python | bsd-3-clause | nikdoof/test-auth | ---
+++
@@ -4,6 +4,10 @@
class SimpleHashModelBackend(ModelBackend):
+
+ supports_anonymous_user = False
+ supports_object_permissions = False
+ supports_inactive_user = False
def authenticate(self, username=None, password=None):
try: |
2515b3402c671c2949e5f3c712cb284777f2accf | examples/boilerplates/base_test_case.py | examples/boilerplates/base_test_case.py | '''
You can use this as a boilerplate for your test framework.
Define your customized library methods in a master class like this.
Then have all your test classes inherit it.
BaseTestCase will inherit SeleniumBase methods from BaseCase.
'''
from seleniumbase import BaseCase
class BaseTestCase(BaseCase):
def set... | '''
You can use this as a boilerplate for your test framework.
Define your customized library methods in a master class like this.
Then have all your test classes inherit it.
BaseTestCase will inherit SeleniumBase methods from BaseCase.
'''
from seleniumbase import BaseCase
class BaseTestCase(BaseCase):
def set... | Update boilerplate to save a screenshot before the tearDown() | Update boilerplate to save a screenshot before the tearDown()
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | ---
+++
@@ -12,10 +12,11 @@
def setUp(self):
super(BaseTestCase, self).setUp()
- # Add custom setUp code for your tests AFTER the super().setUp()
+ # <<< Add custom setUp code for tests AFTER the super().setUp() >>>
def tearDown(self):
- # Add custom tearDown code for your ... |
1b338aa716311b4c91281993e35e9beda376735a | addons/osfstorage/settings/defaults.py | addons/osfstorage/settings/defaults.py | # encoding: utf-8
import importlib
import os
import logging
from website import settings
logger = logging.getLogger(__name__)
WATERBUTLER_CREDENTIALS = {
'storage': {}
}
WATERBUTLER_SETTINGS = {
'storage': {
'provider': 'filesystem',
'folder': os.path.join(settings.BASE_PATH, 'osfstoragecach... | # encoding: utf-8
import importlib
import os
import logging
from website import settings
logger = logging.getLogger(__name__)
WATERBUTLER_CREDENTIALS = {
'storage': {}
}
WATERBUTLER_SETTINGS = {
'storage': {
'provider': 'filesystem',
'folder': os.path.join(settings.BASE_PATH, 'osfstoragecach... | Make environmental override of osfstorage settings work | Make environmental override of osfstorage settings work
Signed-off-by: Chris Wisecarver <5fccdd17c1f7bcc7e393d2cb5e2fad37705ca69f@cos.io>
| Python | apache-2.0 | CenterForOpenScience/osf.io,binoculars/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,TomBaxter/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,sloria/osf.io,crcresearch/osf.io,erinspace/osf.io,caseyrollins/osf.io,Nesiehr/osf.io,TomBaxter/osf.io,leb2dg/osf.io,pattisdr/osf.io,baylee-d/osf.io,adlius/osf.io,felliott/osf.io... | ---
+++
@@ -24,6 +24,7 @@
try:
- importlib.import_module('.{}'.format(settings.MIGRATION_ENV))
-except:
- logger.warn('No migration settings loaded for OSFStorage, falling back to local dev.')
+ mod = importlib.import_module('.{}'.format(settings.MIGRATION_ENV), package='addons.osfstorage.settings')
+ ... |
5a45a312eebe9e432b066b99d914b49a2adb920c | openfaas/yaml2json/function/handler.py | openfaas/yaml2json/function/handler.py | # Author: Milos Buncic
# Date: 2017/10/14
# Description: Convert YAML to JSON and vice versa (OpenFaaS function)
import os
import sys
import json
import yaml
def handle(data, **parms):
def yaml2json(ydata):
"""
Convert YAML to JSON (output: JSON)
"""
try:
d = yaml.load(ydata, Loader=yaml.Base... | # Author: Milos Buncic
# Date: 2017/10/14
# Description: Convert YAML to JSON and vice versa (OpenFaaS function)
import os
import sys
import json
import yaml
def yaml2json(data):
"""
Convert YAML to JSON (output: JSON)
"""
try:
d = yaml.load(data, Loader=yaml.BaseLoader)
except Exception as e:
d = ... | Make handle function to behave similar as main function | Make handle function to behave similar as main function
| Python | mit | psyhomb/serverless | ---
+++
@@ -8,31 +8,31 @@
import yaml
-def handle(data, **parms):
- def yaml2json(ydata):
- """
- Convert YAML to JSON (output: JSON)
- """
- try:
- d = yaml.load(ydata, Loader=yaml.BaseLoader)
- except Exception as e:
- d = {'error': '{}'.format(e)}
+def yaml2json(data):
+ """
+ Conv... |
bd9d08870ec3db09c41c825029c6a513ecc4d1c7 | packs/asserts/actions/object_equals.py | packs/asserts/actions/object_equals.py | import pprint
import sys
from st2actions.runners.pythonrunner import Action
__all__ = [
'AssertObjectEquals'
]
class AssertObjectEquals(Action):
def run(self, object, expected):
ret = cmp(object, expected)
if ret == 0:
sys.stdout.write('EQUAL.')
else:
pprint.... | import pprint
import sys
from st2actions.runners.pythonrunner import Action
__all__ = [
'AssertObjectEquals'
]
def cmp(x, y):
return (x > y) - (x < y)
class AssertObjectEquals(Action):
def run(self, object, expected):
ret = cmp(object, expected)
if ret == 0:
sys.stdout.wri... | Make action python 3 compatible | Make action python 3 compatible
| Python | apache-2.0 | StackStorm/st2tests,StackStorm/st2tests,StackStorm/st2tests | ---
+++
@@ -6,6 +6,10 @@
__all__ = [
'AssertObjectEquals'
]
+
+
+def cmp(x, y):
+ return (x > y) - (x < y)
class AssertObjectEquals(Action): |
22412b3f46451177286f8fc58509a69bb2d95731 | numpy/testing/setup.py | numpy/testing/setup.py | #!/usr/bin/env python3
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('testing', parent_package, top_path)
config.add_subpackage('_private')
config.add_subpackage('tests')
config.add_data_files('*.pyi')
return conf... | #!/usr/bin/env python3
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('testing', parent_package, top_path)
config.add_subpackage('_private')
config.add_subpackage('tests')
config.add_data_files('*.pyi')
config.add_... | Add support for *.pyi data-files to `np.testing._private` | BLD: Add support for *.pyi data-files to `np.testing._private`
| Python | bsd-3-clause | rgommers/numpy,numpy/numpy,endolith/numpy,pdebuyl/numpy,simongibbons/numpy,simongibbons/numpy,mhvk/numpy,seberg/numpy,mattip/numpy,jakirkham/numpy,jakirkham/numpy,mattip/numpy,mhvk/numpy,charris/numpy,seberg/numpy,anntzer/numpy,rgommers/numpy,jakirkham/numpy,mhvk/numpy,charris/numpy,anntzer/numpy,pdebuyl/numpy,rgommers... | ---
+++
@@ -7,6 +7,7 @@
config.add_subpackage('_private')
config.add_subpackage('tests')
config.add_data_files('*.pyi')
+ config.add_data_files('_private/*.pyi')
return config
if __name__ == '__main__': |
3c2663d4c8ca523d072b6e82bf872f412aba9321 | mrgeo-python/src/main/python/pymrgeo/rastermapop.py | mrgeo-python/src/main/python/pymrgeo/rastermapop.py | import copy
import json
from py4j.java_gateway import JavaClass, java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
mapop = None
gateway = None
context = None
job = None
def __init__(self, gateway=None, context=None, mapop=None, job=None):
self.gatew... | import copy
import json
from py4j.java_gateway import java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
mapop = None
gateway = None
context = None
job = None
def __init__(self, gateway=None, context=None, mapop=None, job=None):
self.gateway = gatewa... | Implement empty metadata a little differently | Implement empty metadata a little differently
| Python | apache-2.0 | ngageoint/mrgeo,ngageoint/mrgeo,ngageoint/mrgeo | ---
+++
@@ -1,7 +1,7 @@
import copy
import json
-from py4j.java_gateway import JavaClass, java_import
+from py4j.java_gateway import java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
@@ -35,9 +35,10 @@
java_import(jvm, "org.mrgeo.mapalgebra.raster.RasterMapOp")... |
b56446e0dc7c0c0fe45557461dd4fffa7f1da8d5 | django_project/setup.py | django_project/setup.py | # coding=utf-8
"""Setup file for distutils / pypi."""
try:
from ez_setup import use_setuptools
use_setuptools()
except ImportError:
pass
from setuptools import setup, find_packages
setup(
name='django-wms-client',
version='0.1.1',
author='Tim Sutton',
author_email='tim@kartoza.com',
pa... | # coding=utf-8
"""Setup file for distutils / pypi."""
try:
from ez_setup import use_setuptools
use_setuptools()
except ImportError:
pass
from setuptools import setup, find_packages
setup(
name='django-wms-client',
version='0.1.1',
author='Tim Sutton',
author_email='tim@kartoza.com',
pa... | Change requirements to look for abstract (latest) versions. | Change requirements to look for abstract (latest) versions.
| Python | bsd-2-clause | kartoza/django-wms-client,kartoza/django-wms-client,kartoza/django-wms-client,kartoza/django-wms-client | ---
+++
@@ -24,10 +24,10 @@
'maps on your django web site.'),
long_description=open('README.md').read(),
install_requires=[
- "Django==1.7",
- "django-leaflet==0.14.1",
- "psycopg2==2.5.4",
- "factory-boy==2.4.1",
+ "Django",
+ "django-leaflet",
+ "p... |
a78f56e5c4dedc4148ff3503a05705a8d343b638 | qmpy/web/views/analysis/calculation.py | qmpy/web/views/analysis/calculation.py | from django.shortcuts import render_to_response
from django.template import RequestContext
import os.path
from qmpy.models import Calculation
from ..tools import get_globals
from bokeh.embed import components
def calculation_view(request, calculation_id):
calculation = Calculation.objects.get(pk=calculation_id)
... | from django.shortcuts import render_to_response
from django.template import RequestContext
import os
from qmpy.models import Calculation
from ..tools import get_globals
from bokeh.embed import components
def calculation_view(request, calculation_id):
calculation = Calculation.objects.get(pk=calculation_id)
d... | Handle missing INCAR files gracefully | Handle missing INCAR files gracefully
| Python | mit | wolverton-research-group/qmpy,wolverton-research-group/qmpy,wolverton-research-group/qmpy,wolverton-research-group/qmpy,wolverton-research-group/qmpy | ---
+++
@@ -1,6 +1,6 @@
from django.shortcuts import render_to_response
from django.template import RequestContext
-import os.path
+import os
from qmpy.models import Calculation
from ..tools import get_globals
@@ -14,20 +14,21 @@
data['stdout'] = ''
data['stderr'] = ''
- if os.path.exists(calcula... |
a64f8aaa2822ccd280f252e0937be5027d5ec012 | censusreporter/config/prod/settings.py | censusreporter/config/prod/settings.py | from censusreporter.config.base.settings import *
import os
DEBUG = False
ROOT_URLCONF = 'censusreporter.config.prod.urls'
WSGI_APPLICATION = "censusreporter.config.prod.wsgi.application"
ALLOWED_HOSTS = [
'censusreporter.org',
'www.censusreporter.org',
'censusreporter.dokku.censusreporter.org',
]
CACHE... | from censusreporter.config.base.settings import *
import os
DEBUG = False
ROOT_URLCONF = 'censusreporter.config.prod.urls'
WSGI_APPLICATION = "censusreporter.config.prod.wsgi.application"
ALLOWED_HOSTS = [
'censusreporter.org',
'www.censusreporter.org',
'censusreporter.dokku.censusreporter.org',
]
CACHE... | Fix Dockerfile so it can cache requirements | Fix Dockerfile so it can cache requirements
| Python | mit | censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter | ---
+++
@@ -15,6 +15,6 @@
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
- 'LOCATION': os.environ.get('REDIS_URL'),
+ 'LOCATION': os.environ.get('REDIS_URL', ''),
}
} |
eb453010915f6700edd1baa0febcc634deec81dc | src/viewsapp/views.py | src/viewsapp/views.py | from decorator_plus import (
require_form_methods, require_safe_methods)
from django.shortcuts import (
get_object_or_404, redirect, render)
from .forms import ExampleForm
from .models import ExampleModel
@require_safe_methods
def model_detail(request, *args, **kwargs):
request_slug = kwargs.get('slug')
... | from decorator_plus import require_http_methods
from django.shortcuts import (
get_object_or_404, redirect, render)
from .forms import ExampleForm
from .models import ExampleModel
@require_http_methods(['GET'])
def model_detail(request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = ge... | Switch to using require_http_methods decorator. | Switch to using require_http_methods decorator.
| Python | bsd-2-clause | jambonrose/djangocon2015-views,jambonrose/djangocon2015-views | ---
+++
@@ -1,5 +1,4 @@
-from decorator_plus import (
- require_form_methods, require_safe_methods)
+from decorator_plus import require_http_methods
from django.shortcuts import (
get_object_or_404, redirect, render)
@@ -7,7 +6,7 @@
from .models import ExampleModel
-@require_safe_methods
+@require_htt... |
94e44e18832311bc063830c0a6bfe23e04e40a8d | srsly/_msgpack_api.py | srsly/_msgpack_api.py | # coding: utf8
from __future__ import unicode_literals
import gc
from . import msgpack
from .util import force_path
def msgpack_dumps(data):
return msgpack.dumps(data, use_bin_type=True)
def msgpack_loads(data):
# msgpack-python docs suggest disabling gc before unpacking large messages
gc.disable()
... | # coding: utf8
from __future__ import unicode_literals
import gc
from . import msgpack
from .util import force_path
def msgpack_dumps(data):
return msgpack.dumps(data, use_bin_type=True)
def msgpack_loads(data, use_list=True):
# msgpack-python docs suggest disabling gc before unpacking large messages
... | Allow passing use_list to msgpack_loads | Allow passing use_list to msgpack_loads
| Python | mit | explosion/srsly,explosion/srsly,explosion/srsly,explosion/srsly | ---
+++
@@ -11,10 +11,10 @@
return msgpack.dumps(data, use_bin_type=True)
-def msgpack_loads(data):
+def msgpack_loads(data, use_list=True):
# msgpack-python docs suggest disabling gc before unpacking large messages
gc.disable()
- msg = msgpack.loads(data, raw=False)
+ msg = msgpack.loads(dat... |
e78b3f53150a5f1c170b860f8719e982cf1c6f9e | integration/main.py | integration/main.py | import os
import sys
from spec import Spec, skip
from invoke import run
class Integration(Spec):
def setup(self):
from tessera.application import db
# Ensure we have a clean db target.
self.dbpath = db.engine.url.database
msg = "You seem to have a db in the default location ({0}) ... | import os
import sys
from spec import Spec, skip, eq_
from invoke import run
class Integration(Spec):
def setup(self):
from tessera.application import db
# Ensure we have a clean db target.
self.dbpath = db.engine.url.database
msg = "You seem to have a db in the default location (... | Fix state bleed, add fixture import test | Fix state bleed, add fixture import test
| Python | apache-2.0 | section-io/tessera,urbanairship/tessera,tessera-metrics/tessera,jmptrader/tessera,section-io/tessera,urbanairship/tessera,aalpern/tessera,section-io/tessera,jmptrader/tessera,filippog/tessera,aalpern/tessera,aalpern/tessera,Slach/tessera,Slach/tessera,urbanairship/tessera,urbanairship/tessera,Slach/tessera,jmptrader/te... | ---
+++
@@ -1,7 +1,7 @@
import os
import sys
-from spec import Spec, skip
+from spec import Spec, skip, eq_
from invoke import run
@@ -14,10 +14,14 @@
assert not os.path.exists(self.dbpath), msg.format(self.dbpath)
def teardown(self):
+ from tessera.application import db
# Tea... |
0ad29aa9945448236500b221fc489c1627e6693b | api.py | api.py | from collections import namedtuple
import requests
QUERY_TEMPLATE = '?token={}&domain={}'
BASE_URL = 'https://pddimp.yandex.ru/api2/'
Connection = namedtuple('Connection', ['auth', 'domain'])
def list_emails(connection):
url = '{}admin/email/list'.format(BASE_URL) + QUERY_TEMPLATE.format(*connection)
ret ... | import json
import random
import string
from collections import namedtuple
import requests
QUERY_TEMPLATE = '?token={}&domain={}'
BASE_URL = 'https://pddimp.yandex.ru/api2/'
Connection = namedtuple('Connection', ['auth', 'domain'])
class YandexException(Exception):
pass
rndstr = lambda: ''.join(random.samp... | Add create email and delete email methods | Add create email and delete email methods
| Python | mit | chrisseto/dinosaurs.sexy,chrisseto/dinosaurs.sexy | ---
+++
@@ -1,3 +1,7 @@
+import json
+import random
+import string
+
from collections import namedtuple
import requests
@@ -9,7 +13,53 @@
Connection = namedtuple('Connection', ['auth', 'domain'])
+class YandexException(Exception):
+ pass
+
+
+rndstr = lambda: ''.join(random.sample(string.ascii_letters + s... |
df325e7caee163f754c1b85cf71dab7810700933 | src/waldur_keycloak_rancher/tasks.py | src/waldur_keycloak_rancher/tasks.py | import logging
from celery import shared_task
from django.conf import settings
from waldur_keycloak.models import ProjectGroup
from waldur_rancher.models import Cluster, ClusterRole
logger = logging.getLogger(__name__)
@shared_task(name='waldur_keycloak_rancher.sync_groups')
def sync_groups():
if not settings.... | import logging
from celery import shared_task
from django.conf import settings
from waldur_keycloak.models import ProjectGroup
from waldur_rancher.enums import ClusterRoles
from waldur_rancher.models import Cluster
logger = logging.getLogger(__name__)
@shared_task(name='waldur_keycloak_rancher.sync_groups')
def sy... | Fix cluster group membership synchronization. | Fix cluster group membership synchronization.
| Python | mit | opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind | ---
+++
@@ -4,7 +4,8 @@
from django.conf import settings
from waldur_keycloak.models import ProjectGroup
-from waldur_rancher.models import Cluster, ClusterRole
+from waldur_rancher.enums import ClusterRoles
+from waldur_rancher.models import Cluster
logger = logging.getLogger(__name__)
@@ -23,7 +24,7 @@
... |
cbddfe308f4e0da728974777f10b245a966520b6 | summarize/__init__.py | summarize/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import combinations
from operator import itemgetter
from distance import jaccard
from networkx import Graph, pagerank
from nltk import tokenize
from .utils import get_stopwords, get_words
def summarize(text, sentence_count=5, language='... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import combinations
from operator import itemgetter
from distance import jaccard
from networkx import Graph, pagerank
from nltk import tokenize
from .utils import get_stopwords, get_words
def summarize(text, sentence_count=5, language='... | Fix sentence index shifting with empty sentences | Fix sentence index shifting with empty sentences
| Python | mit | despawnerer/summarize | ---
+++
@@ -17,11 +17,12 @@
wordsets = [get_words(sentence, stopwords) for sentence in sentence_list]
graph = Graph()
- pairs = combinations(enumerate(filter(None, wordsets)), 2)
+ pairs = combinations(enumerate(wordsets), 2)
for (index_a, words_a), (index_b, words_b) in pairs:
- similar... |
dc68813d5f555a01f1bdd2511d9d2de820369573 | conditional/blueprints/spring_evals.py | conditional/blueprints/spring_evals.py | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | Restructure major projects for spring evals 👷 | Restructure major projects for spring evals 👷
| Python | mit | RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional | ---
+++
@@ -16,7 +16,13 @@
'uid': 'loothelion',
'committee_meetings': 24,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
- 'major_project': 'open_container',
+ 'ma... |
3ffea173c206d4c8a58953eceb34d80fb66d609b | utils/tasks.py | utils/tasks.py | from celery.task import task
from utils import send_templated_email
@task
def send_templated_email_async(to, subject, body_template, body_dict,
from_email=None, ct="html", fail_silently=False):
return send_templated_email(to,subject, body_template, body_dict,
fro... | from celery.task import task
from utils import send_templated_email
@task
def send_templated_email_async(to, subject, body_template, body_dict,
from_email=None, ct="html", fail_silently=False, check_user_preference=True):
return send_templated_email(to,subject, body_template, body_dict,
... | Allow check_user_preferences for email to be passed from async templated email send | Allow check_user_preferences for email to be passed from async templated email send
| Python | agpl-3.0 | ReachingOut/unisubs,norayr/unisubs,wevoice/wesub,eloquence/unisubs,ujdhesa/unisubs,ujdhesa/unisubs,ReachingOut/unisubs,pculture/unisubs,eloquence/unisubs,wevoice/wesub,ReachingOut/unisubs,ofer43211/unisubs,ofer43211/unisubs,ofer43211/unisubs,wevoice/wesub,ujdhesa/unisubs,pculture/unisubs,wevoice/wesub,ujdhesa/unisubs,n... | ---
+++
@@ -3,6 +3,6 @@
@task
def send_templated_email_async(to, subject, body_template, body_dict,
- from_email=None, ct="html", fail_silently=False):
+ from_email=None, ct="html", fail_silently=False, check_user_preference=True):
return send_templated_email(... |
45963022a39f8c0f3d57199017adc78b39005d6a | openspending/lib/unicode_dict_reader.py | openspending/lib/unicode_dict_reader.py | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
class EmptyCSVError(Exception):
pass
def UnicodeDictReader(file_or_str, encoding='utf8', **kwargs):
import csv
def decode(s, enco... | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
import csv
class EmptyCSVError(Exception):
pass
class UnicodeDictReader(object):
def __init__(self, file_or_str, encoding='utf8', **... | Convert UnicodeDictReader to an iterator class, so that EmptyCSVError will get thrown on instantiation, rather than on iteration. | Convert UnicodeDictReader to an iterator class, so that EmptyCSVError will get thrown on instantiation, rather than on iteration.
| Python | agpl-3.0 | pudo/spendb,nathanhilbert/FPA_Core,USStateDept/FPA_Core,openspending/spendb,CivicVision/datahub,nathanhilbert/FPA_Core,CivicVision/datahub,spendb/spendb,johnjohndoe/spendb,johnjohndoe/spendb,spendb/spendb,USStateDept/FPA_Core,nathanhilbert/FPA_Core,pudo/spendb,openspending/spendb,johnjohndoe/spendb,openspending/spendb,... | ---
+++
@@ -1,22 +1,31 @@
# work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
+
+import csv
class EmptyCSVError(Exception):
pass
-def UnicodeDictReader(file_or_str, encoding='utf8', ... |
db935a152efc8ab730491fc860db6d4c9cf65c5f | test/test_packages.py | test/test_packages.py | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("gnupg2"),
("gnupg-agent"),
("handbrake"),... | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("gnupg2"),
("gnupg-agent"),
("handbrake"),... | Change test function as existing method deprecated | Change test function as existing method deprecated
| Python | mit | wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build | ---
+++
@@ -51,5 +51,6 @@
("xinit"),
])
-def test_packages(Package, name):
- assert Package(name).is_installed
+def test_packages(host, name):
+ pkg = host.package(name)
+ assert pkg.is_installed |
7d621db3618db90679461550fb0c952417616402 | bot.py | bot.py | import asyncio
import configparser
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self, config_filepath, command_prefix):
super().__init__(command_prefix)
self._load_config_data(config_filepath)
def _load_config_data(self, filepath):
config = configparser.ConfigParser()
... | import asyncio
import configparser
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self, config_filepath, command_prefix):
super().__init__(command_prefix)
self._load_config_data(config_filepath)
def _load_config_data(self, filepath):
config = configparser.ConfigParser()
... | Add Bot.run and an on_ready message | Add Bot.run and an on_ready message
| Python | mit | MagiChau/ZonBot | ---
+++
@@ -17,5 +17,15 @@
self.twitch_ID = config['TWITCH']['client_id']
self.carbon_key = config['CARBON']['key']
+ async def on_ready(self):
+ print("Logged in as {}".format(self.user.name))
+ print("User ID: {}".format(self.user.id))
+ print("Library: {} - {}".format(discord.__title__, discord.__versio... |
ee2ed250fdf42d0e4616f0e783ff1ace0a201514 | scripts/spat_conlisk_univariate_fig2.py | scripts/spat_conlisk_univariate_fig2.py | """
Purpose: to recreate the univariate pdfs of Conlisk et al. (2007)
in figure 2. This provides a test that the univariate pdfs are
working correctly
"""
import numpy as np
import mete
import csv
n0 = 617
c = 256
sing_pdfs = np.zeros((4, 7))
psi = [0.01, 0.25, 0.5, 0.75]
for i in range(0, len(psi)):
sing_pdfs[... | """
Purpose: to recreate the univariate pdfs of Conlisk et al. (2007)
in figure 2. This provides a test that the univariate pdfs are
working correctly
"""
import numpy as np
import mete
import matplotlib.pyplot as plt
n0 = 617
c = 256
sing_pdfs = np.zeros((4, 8))
psi = [0.01, 0.25, 0.5, 0.75]
for i in range(0, len(... | Create a pdf of the univariate pdfs instead of writing to a .csv file. | Create a pdf of the univariate pdfs instead of writing to a .csv file.
| Python | mit | weecology/mete-spatial,weecology/mete-spatial,weecology/mete-spatial,weecology/mete-spatial | ---
+++
@@ -5,21 +5,26 @@
"""
import numpy as np
import mete
-import csv
+import matplotlib.pyplot as plt
n0 = 617
c = 256
-sing_pdfs = np.zeros((4, 7))
+sing_pdfs = np.zeros((4, 8))
psi = [0.01, 0.25, 0.5, 0.75]
for i in range(0, len(psi)):
- sing_pdfs[i, : ] = [mete.single_prob(n, n0, psi[i], c) for... |
54e715f26ed62e62e8794d8084110091c8db580b | oauth_provider/utils.py | oauth_provider/utils.py | import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
oauth_request = oauth.OAuthRequest.from_request(request.meth... | import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
# Django converts Authorization header in HTTP_AUTHORIZATION... | Fix a bug introduced in the latest revision, testing auth header in initialize_server_request now, thanks Chris McMichael for the report and patch | Fix a bug introduced in the latest revision, testing auth header in initialize_server_request now, thanks Chris McMichael for the report and patch
| Python | bsd-3-clause | lukegb/django-oauth-plus,amrox/django-oauth-plus | ---
+++
@@ -9,9 +9,17 @@
def initialize_server_request(request):
"""Shortcut for initialization."""
+ # Django converts Authorization header in HTTP_AUTHORIZATION
+ # Warning: it doesn't happen in tests but it's useful, do not remove!
+ auth_header = {}
+ if 'Authorization' in request.META:
+ ... |
73fe535416dbf744752d745f0186d5406bd15d8c | test/client/local_recognizer_test.py | test/client/local_recognizer_test.py | import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
self.recognizer ... | import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
rl = RecognizerL... | Fix init of local recognizer | Fix init of local recognizer
| Python | apache-2.0 | linuxipho/mycroft-core,aatchison/mycroft-core,MycroftAI/mycroft-core,aatchison/mycroft-core,forslund/mycroft-core,linuxipho/mycroft-core,Dark5ide/mycroft-core,Dark5ide/mycroft-core,MycroftAI/mycroft-core,forslund/mycroft-core | ---
+++
@@ -12,7 +12,9 @@
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
- self.recognizer = RecognizerLoop.create_mycroft_recognizer(16000,
+ rl = RecognizerLoop()
+ self.recognizer = RecognizerLoop.create_mycroft_recognizer(rl,
+ ... |
eb06e85c7dcb93febe22d20cd7e3e694939449ba | tests/test_xelatex.py | tests/test_xelatex.py | from latex.build import LatexMkBuilder
def test_xelatex():
min_latex = r"""
\documentclass{article}
\begin{document}
Hello, world!
\end{document}
"""
builder = LatexMkBuilder(variant='xelatex')
pdf = builder.build_pdf(min_latex)
assert pdf
| from latex.build import LatexMkBuilder
def test_xelatex():
# the example below should not compile on pdflatex, but on xelatex
min_latex = r"""
\documentclass[12pt]{article}
\usepackage{fontspec}
\setmainfont{Times New Roman}
\title{Sample font document}
\author{Hubert Farnsworth}
\date{this month, 2014}
... | Make XeLaTeX test harder (to actually test xelatex being used). | Make XeLaTeX test harder (to actually test xelatex being used).
| Python | bsd-3-clause | mbr/latex | ---
+++
@@ -2,10 +2,25 @@
def test_xelatex():
+ # the example below should not compile on pdflatex, but on xelatex
min_latex = r"""
-\documentclass{article}
+\documentclass[12pt]{article}
+\usepackage{fontspec}
+
+\setmainfont{Times New Roman}
+
+ \title{Sample font document}
+ \author{Hubert Farnsworth}... |
d95d71f996483bdde4f0b27d9d9c023aef706c65 | freebasics/tests/test_env_variables.py | freebasics/tests/test_env_variables.py | from django.test import TestCase, RequestFactory
from molo.core.tests.base import MoloTestCaseMixin
from freebasics.views import HomeView
from freebasics.templatetags import freebasics_tags
class EnvTestCase(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
def test_block_ordering(self):... | from django.test import TestCase, RequestFactory
from molo.core.tests.base import MoloTestCaseMixin
from freebasics.views import HomeView
from freebasics.templatetags import freebasics_tags
class EnvTestCase(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
def test_block_ordering(self):... | Add test for custom css | Add test for custom css
| Python | bsd-2-clause | praekelt/molo-freebasics,praekelt/molo-freebasics,praekelt/molo-freebasics,praekelt/molo-freebasics | ---
+++
@@ -33,3 +33,9 @@
styles = freebasics_tags.custom_css(context='')
self.assertEquals(styles['accent_2'], 'red')
self.assertEquals(styles['text_transform'], 'lowercase')
+
+ def test_custom_css(self):
+ response = self.client.get('/')
+ self.assertContains... |
59c66d0e172b23ea7106a70866871d20bbcabe5b | timezones/__init__.py | timezones/__init__.py |
import pytz
TIMEZONE_CHOICES = zip(pytz.all_timezones, pytz.all_timezones)
|
import pytz
TIMEZONE_CHOICES = zip(pytz.common_timezones, pytz.common_timezones)
| Use common timezones and not all timezones pytz provides. | Use common timezones and not all timezones pytz provides.
git-svn-id: 13ea2b4cf383b32e0a7498d153ee882d068671f7@13 86ebb30f-654e-0410-bc0d-7bf82786d749
| Python | bsd-2-clause | mfogel/django-timezone-field,brosner/django-timezones | ---
+++
@@ -1,4 +1,4 @@
import pytz
-TIMEZONE_CHOICES = zip(pytz.all_timezones, pytz.all_timezones)
+TIMEZONE_CHOICES = zip(pytz.common_timezones, pytz.common_timezones) |
8bd738972cebd27b068250bd52db8aacea6c7876 | src/condor_tests/ornithology/plugin.py | src/condor_tests/ornithology/plugin.py | import pytest
from .scripts import SCRIPTS
# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.
@pytest.fixture(scope="session")
def path_to_sleep():
return SCRIPTS["sleep"]
| import sys
import pytest
from .scripts import SCRIPTS
# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.
@pytest.fixture(scope="session")
def path_to_sleep():
return SCRIPTS[... | Add path_to_python fixture to make writing multiplatform job scripts easier. | Add path_to_python fixture to make writing multiplatform job scripts easier.
| Python | apache-2.0 | htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor | ---
+++
@@ -1,3 +1,4 @@
+import sys
import pytest
from .scripts import SCRIPTS
@@ -9,3 +10,8 @@
@pytest.fixture(scope="session")
def path_to_sleep():
return SCRIPTS["sleep"]
+
+
+@pytest.fixture(scope="session")
+def path_to_python():
+ return sys.executable |
775170d69862aaff63231b669639a872596ed2cd | test_interpreter.py | test_interpreter.py | import unittest
import brainfuck
test_cases = [("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.", "Hello World!\n")]
class InterpreterTestCase(unittest.TestCase):
def setUp(self):
self.interpreter = brainfuck.BrainfuckInterpreter()
def runTes... | import unittest
import brainfuck
hello_case = ("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.", "Hello World!\n")
class InterpreterTestCase(unittest.TestCase):
def setUp(self):
self.interpreter = brainfuck.BrainfuckInterpreter()
def test_hel... | Add unittest for missing parenthesis | Add unittest for missing parenthesis
| Python | bsd-3-clause | handrake/brainfuck | ---
+++
@@ -1,11 +1,12 @@
import unittest
import brainfuck
-test_cases = [("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.", "Hello World!\n")]
+hello_case = ("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.-----... |
131454ffaec010442c17f748365ab491668d947f | plumeria/plugins/bing_images.py | plumeria/plugins/bing_images.py | from aiohttp import BasicAuth
from plumeria import config, scoped_config
from plumeria.command import commands, CommandError
from plumeria.config.common import nsfw
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://api.datamarket.a... | import random
from aiohttp import BasicAuth
from plumeria import config, scoped_config
from plumeria.command import commands, CommandError
from plumeria.config.common import nsfw
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://a... | Make the Bing images search pick a random top 20 image. | Make the Bing images search pick a random top 20 image.
| Python | mit | sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria | ---
+++
@@ -1,3 +1,5 @@
+import random
+
from aiohttp import BasicAuth
from plumeria import config, scoped_config
from plumeria.command import commands, CommandError
@@ -28,12 +30,12 @@
raise CommandError("Search term required!")
r = await http.get(SEARCH_URL, params=[
('$format', 'json'),
-... |
f7caec9d0c0058b5d760992172b434b461f70d90 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service... | import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service... | Remove test enforcing listening on port 1883 | Remove test enforcing listening on port 1883
| Python | mit | triplepoint/ansible-mosquitto | ---
+++
@@ -17,8 +17,6 @@
@pytest.mark.parametrize('socket_def', [
- # listening on localhost, for tcp sockets on port 1883 (MQQT)
- ('tcp://127.0.0.1:1883'),
# all IPv4 tcp sockets on port 8883 (MQQTS)
('tcp://8883'),
]) |
3dc06581d07a204a3044e3a78deb84950a6ebf74 | mtp_transaction_uploader/api_client.py | mtp_transaction_uploader/api_client.py | from urllib.parse import urljoin
from oauthlib.oauth2 import LegacyApplicationClient
from requests_oauthlib import OAuth2Session
import slumber
from . import settings
REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/')
def get_authenticated_connection():
"""
Returns:
an authenticated sl... | from urllib.parse import urljoin
from oauthlib.oauth2 import LegacyApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
import slumber
from . import settings
REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/')
def get_authenticated_connection():
"""
... | Use HTTPBasicAuth when connecting to the API | Use HTTPBasicAuth when connecting to the API
| Python | mit | ministryofjustice/money-to-prisoners-transaction-uploader | ---
+++
@@ -1,6 +1,7 @@
from urllib.parse import urljoin
from oauthlib.oauth2 import LegacyApplicationClient
+from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
import slumber
@@ -24,8 +25,7 @@
token_url=REQUEST_TOKEN_URL,
username=settings.API_USERNAME,
... |
e6933a46086f83913de307fb8803ccbfd3c55114 | mysite/mysite/tests/test_middleware.py | mysite/mysite/tests/test_middleware.py | from django.contrib.auth.models import User
from django.test import TestCase
from DjangoLibrary.middleware import FactoryBoyMiddleware
from mock import Mock
import json
class TestFactoryBoyMiddleware(TestCase):
def setUp(self):
self.middleware = FactoryBoyMiddleware()
self.request = Mock()
... | from django.contrib.auth.models import User
from django.test import TestCase
from DjangoLibrary.middleware import FactoryBoyMiddleware
from mock import Mock
import json
class TestFactoryBoyMiddleware(TestCase):
def setUp(self):
self.middleware = FactoryBoyMiddleware()
self.request = Mock()
... | Fix integration tests for Python 3. | Fix integration tests for Python 3.
| Python | apache-2.0 | kitconcept/robotframework-djangolibrary | ---
+++
@@ -28,7 +28,7 @@
self.assertEqual(201, response.status_code)
self.assertEqual(
'johndoe',
- json.loads(response.content).get('username')
+ json.loads(response.content.decode('utf-8')).get('username')
)
self.assertEqual(1, len(User.objects... |
47e5fdce2d248e6bf78addcb46e1a8f12fcc07d6 | tests/app/main/test_form_validators.py | tests/app/main/test_form_validators.py | import mock
import pytest
from flask.ext.wtf import Form
from wtforms.fields.core import Field
from wtforms.validators import StopValidation
from app.main.forms import AdminEmailAddressValidator
@mock.patch('app.main.forms.data_api_client')
class TestAdminEmailAddressValidator(object):
def setup_method(self):
... | import mock
import pytest
from flask_wtf import Form
from wtforms.fields.core import Field
from wtforms.validators import StopValidation
from app.main.forms import AdminEmailAddressValidator
@mock.patch('app.main.forms.data_api_client')
class TestAdminEmailAddressValidator(object):
def setup_method(self):
... | Tidy up test imports a bit | Tidy up test imports a bit
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend | ---
+++
@@ -1,7 +1,6 @@
import mock
import pytest
-
-from flask.ext.wtf import Form
+from flask_wtf import Form
from wtforms.fields.core import Field
from wtforms.validators import StopValidation
|
e68c38428c055f7c001011c6cc325593d2a26a81 | pyFxTrader/strategy/__init__.py | pyFxTrader/strategy/__init__.py | # -*- coding: utf-8 -*-
class Strategy(object):
TIMEFRAMES = [] # e.g. ['M30', 'H2']
def __init__(self, instrument):
self.instrument = instrument
if not self.TIMEFRAMES:
raise ValueError('Please define TIMEFRAMES variable.')
def start(self):
"""Called on strategy star... | # -*- coding: utf-8 -*-
from collections import deque
from logbook import Logger
log = Logger('pyFxTrader')
class Strategy(object):
TIMEFRAMES = [] # e.g. ['M30', 'H2']
BUFFER_SIZE = 500
feeds = {}
def __init__(self, instrument):
self.instrument = instrument
if not self.TIMEFRAM... | Add default BUFFER_SIZE for feeds | Add default BUFFER_SIZE for feeds
| Python | mit | jmelett/pyfx,jmelett/pyFxTrader,jmelett/pyfx | ---
+++
@@ -1,12 +1,27 @@
# -*- coding: utf-8 -*-
+
+from collections import deque
+
+from logbook import Logger
+
+log = Logger('pyFxTrader')
+
class Strategy(object):
TIMEFRAMES = [] # e.g. ['M30', 'H2']
+ BUFFER_SIZE = 500
+
+ feeds = {}
def __init__(self, instrument):
self.instrume... |
73d9049dea55ddfa32e4cb09f969b6ff083fee2c | tests/redisdl_test.py | tests/redisdl_test.py | import redisdl
import unittest
import json
import os.path
class RedisdlTest(unittest.TestCase):
def setUp(self):
import redis
self.r = redis.Redis()
for key in self.r.keys('*'):
self.r.delete(key)
def test_roundtrip(self):
path = os.path.join(os.path.dirname(__file_... | import redisdl
import unittest
import json
import os.path
class RedisdlTest(unittest.TestCase):
def setUp(self):
import redis
self.r = redis.Redis()
for key in self.r.keys('*'):
self.r.delete(key)
def test_roundtrip(self):
path = os.path.join(os.path.dirname(__file_... | Add tests for dumping string and unicode values | Add tests for dumping string and unicode values
| Python | bsd-2-clause | p/redis-dump-load,p/redis-dump-load,hyunchel/redis-dump-load,hyunchel/redis-dump-load | ---
+++
@@ -21,5 +21,19 @@
expected = json.loads(dump)
actual = json.loads(redump)
-
+
self.assertEqual(expected, actual)
+
+ def test_dump_string_value(self):
+ self.r.set('key', 'value')
+ dump = redisdl.dumps()
+ actual = json.loads(dump)
+ expect... |
23a0db627060afc3e1563d298c733edd8bb106a1 | src/ConfigLoader.py | src/ConfigLoader.py | import json
import sys
def load_config_file(out=sys.stdout):
default_filepath = "../resources/config/default-config.json"
user_filepath = "../resources/config/user-config.json"
try:
default_json = read_json(default_filepath)
user_json = read_json(user_filepath)
for property in use... | import json
import sys
def load_config_file(out=sys.stdout):
if sys.argv[0].endswith('nosetests'):
default_filepath = "./resources/config/default-config.json"
user_filepath = "./resources/config/user-config.json"
else:
default_filepath = "../resources/config/default-config.json"
... | Fix nosetests for config file loading | Fix nosetests for config file loading
| Python | bsd-3-clause | sky-uk/bslint | ---
+++
@@ -3,8 +3,12 @@
def load_config_file(out=sys.stdout):
- default_filepath = "../resources/config/default-config.json"
- user_filepath = "../resources/config/user-config.json"
+ if sys.argv[0].endswith('nosetests'):
+ default_filepath = "./resources/config/default-config.json"
+ use... |
4fb39abc5afef5b0ca87e5c3b40e3dc9c9c0b2ef | tests/functions_tests/test_accuracy.py | tests/functions_tests/test_accuracy.py | import unittest
import numpy
import six
import chainer
from chainer import cuda
from chainer import gradient_check
from chainer.testing import attr
if cuda.available:
cuda.init()
class TestAccuracy(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (10, 3)).astype(numpy.flo... | import unittest
import numpy
import six
import chainer
from chainer import cuda
from chainer import gradient_check
from chainer.testing import attr
if cuda.available:
cuda.init()
class TestAccuracy(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (10, 3)).astype(numpy.flo... | Add test fot shape of result of accuracy function | Add test fot shape of result of accuracy function
| Python | mit | elviswf/chainer,1986ks/chainer,cupy/cupy,ktnyt/chainer,hvy/chainer,tigerneil/chainer,rezoo/chainer,sou81821/chainer,tereka114/chainer,hvy/chainer,wavelets/chainer,jfsantos/chainer,chainer/chainer,ikasumi/chainer,okuta/chainer,aonotas/chainer,ysekky/chainer,kashif/chainer,ktnyt/chainer,niboshi/chainer,pfnet/chainer,ytoy... | ---
+++
@@ -23,6 +23,7 @@
x = chainer.Variable(x_data)
t = chainer.Variable(t_data)
y = chainer.functions.accuracy(x, t)
+ self.assertEqual((), y.data.shape)
count = 0
for i in six.moves.range(self.t.size): |
b458e34c0e6466afd3125fff6b1f36278572857b | pipes/iam/consts.py | pipes/iam/consts.py | """Constant variables for Spinnaker IAM Pipe."""
API_URL = 'http://spinnaker.build.example.com:8084'
| """Constant variables for Spinnaker IAM Pipe."""
API_URL = 'http://gate-api.build.example.com:8084'
| Update to use new gate api | Update to use new gate api
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -1,2 +1,2 @@
"""Constant variables for Spinnaker IAM Pipe."""
-API_URL = 'http://spinnaker.build.example.com:8084'
+API_URL = 'http://gate-api.build.example.com:8084' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.