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 |
|---|---|---|---|---|---|---|---|---|---|---|
fe771659b876bfe23e5b16b9648ab7ede5b314e9 | comics/crawler/crawlers/questionablecontent.py | comics/crawler/crawlers/questionablecontent.py | from comics.crawler.crawlers import BaseComicCrawler
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.feed_url = 'http://www.questionablecontent.net/QCRSS.xml'
self.parse_feed()
for entry in self.feed['entries']:
if self.timestamp_to_date(entry['updated_parsed']) ... | from comics.crawler.crawlers import BaseComicCrawler
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.feed_url = 'http://www.questionablecontent.net/QCRSS.xml'
self.parse_feed()
for entry in self.feed.entries:
if ('updated_parsed' in entry and
self... | Fix error in Questionable Content crawler when feed entry does not contain date | Fix error in Questionable Content crawler when feed entry does not contain date
| Python | agpl-3.0 | datagutten/comics,klette/comics,klette/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,klette/comics,jodal/comics,jodal/comics | ---
+++
@@ -5,10 +5,11 @@
self.feed_url = 'http://www.questionablecontent.net/QCRSS.xml'
self.parse_feed()
- for entry in self.feed['entries']:
- if self.timestamp_to_date(entry['updated_parsed']) == self.pub_date:
- self.title = entry['title']
- pie... |
523293a2785df1229159ad5d0d430195404b9334 | arc_distance/__init__.py | arc_distance/__init__.py | # Authors: Yuancheng Peng
# License: MIT
"""Computes the arc distance between a collection of points
This code is challenging because it requires efficient vectorisation of
trigonometric functions that are note natively supported in SSE/AVX. The numpy
version makes use of numpy.tile and transpose, which proves to be c... | # Authors: Yuancheng Peng
# License: MIT
"""Computes the arc distance between a collection of points
This code is challenging because it requires efficient vectorisation of
trigonometric functions that are note natively supported in SSE/AVX. The numpy
version makes use of numpy.tile and transpose, which proves to be c... | Make arc distance test size bigger to better show the difference. | Make arc distance test size bigger to better show the difference.
Now on the web site, 5 on the 7 test case have speed of 0.001, the minimal value.
| Python | mit | numfocus/python-benchmarks,numfocus/python-benchmarks | ---
+++
@@ -13,7 +13,7 @@
import numpy as np
-def make_env(n=100):
+def make_env(n=1000):
rng = np.random.RandomState(42)
a = rng.rand(n, 2)
b = rng.rand(n, 2) |
620bb416b0e44cc002679e001f1f0b8ab7792685 | bmi_tester/tests_pytest/test_grid.py | bmi_tester/tests_pytest/test_grid.py | from nose.tools import (assert_is_instance, assert_less_equal, assert_equal,
assert_greater, assert_in)
# from nose import with_setup
# from .utils import setup_func, teardown_func, all_names, all_grids, new_bmi
from .utils import all_names, all_grids
VALID_GRID_TYPES = (
"scalar",
"u... | from nose.tools import (assert_is_instance, assert_less_equal, assert_equal,
assert_greater, assert_in)
# from nose import with_setup
# from .utils import setup_func, teardown_func, all_names, all_grids, new_bmi
from .utils import all_names, all_grids
VALID_GRID_TYPES = (
"scalar",
"v... | Add vector as valid grid type. | Add vector as valid grid type.
| Python | mit | csdms/bmi-tester | ---
+++
@@ -8,6 +8,7 @@
VALID_GRID_TYPES = (
"scalar",
+ "vector",
"unstructured",
"unstructured_triangular",
"rectilinear", |
d7f744cfe542fffc398c3301699541190087ccbd | src/musicbrainz2/__init__.py | src/musicbrainz2/__init__.py | """A collection of classes for MusicBrainz.
This package contains the following modules:
1. L{model}: The MusicBrainz domain model, containing classes like
L{Artist <model.Artist>}, L{Release <model.Release>}, or
L{Track <model.Track>}
2. L{webservice}: An interface to the MusicBrainz XML web service.
3.... | """A collection of classes for MusicBrainz.
This package contains the following modules:
1. L{model}: The MusicBrainz domain model, containing classes like
L{Artist <model.Artist>}, L{Release <model.Release>}, or
L{Track <model.Track>}
2. L{webservice}: An interface to the MusicBrainz XML web service.
3.... | Set the version number to 0.3.0. | Set the version number to 0.3.0.
git-svn-id: f25caaa641ea257ccb5bc415e08f7c71e4161381@214 b0b80210-5d09-0410-99dd-b4bd03f891c0
| Python | bsd-3-clause | mineo/python-musicbrainz2 | ---
+++
@@ -21,6 +21,6 @@
@author: Matthias Friedrich <matt@mafr.de>
"""
__revision__ = '$Id$'
-__version__ = '0.2.1'
+__version__ = '0.3.0'
# EOF |
85c7784982e70b2962af0ae82d65fb0a6c12fa78 | integrations/node_js/my_first_test.py | integrations/node_js/my_first_test.py | from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_basic(self):
self.open('http://xkcd.com/353/')
self.assert_element('img[alt="Python"]')
self.click('a[rel="license"]')
text = self.get_text("div center")
self.assertTrue("reuse any of my drawings" in t... | from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_basic(self):
self.open('http://xkcd.com/353/')
self.assert_element('img[alt="Python"]')
self.click('a[rel="license"]')
text = self.get_text("div center")
self.assertTrue("reuse any of my drawings" in t... | Update a click in a test | Update a click in a test
| Python | mit | seleniumbase/SeleniumBase,mdmintz/seleniumspot,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/seleniumspot,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase | ---
+++
@@ -12,7 +12,7 @@
self.open('http://xkcd.com/1481/')
title = self.get_attribute('#comic img', 'title')
self.assertTrue('connections to the server' in title)
- self.click_link_text('Blag')
+ self.click('link=Blag')
self.assert_text('The blag of the webcomic', '... |
832f0887eb617691dc50688a35a0bef04e4e3346 | fmcapi/__init__.py | fmcapi/__init__.py | """
The fmcapi __init__.py file is called whenever someone imports the package into their program.
"""
# from .fmc import *
# from .api_objects import *
# from .helper_functions import *
import logging
# logging.getLogger(__name__).addHandler(logging.NullHandler())
# Its always good to set up a log file.
logging_for... | """
The fmcapi __init__.py file is called whenever someone imports the package into their program.
"""
# from .fmc import *
# from .api_objects import *
# from .helper_functions import *
import logging
logging.debug("In the fmcapi __init__.py file.")
def __authorship__():
"""In the FMC __authorship__() class met... | Remove file logger enabled by default | Remove file logger enabled by default
| Python | bsd-3-clause | daxm/fmcapi,daxm/fmcapi | ---
+++
@@ -6,22 +6,6 @@
# from .api_objects import *
# from .helper_functions import *
import logging
-
-# logging.getLogger(__name__).addHandler(logging.NullHandler())
-
-# Its always good to set up a log file.
-logging_format = '%(asctime)s - %(levelname)s:%(filename)s:%(lineno)s - %(message)s'
-logging_datefor... |
3cd3e40f84036dbb12f2281e58696f9104653ecc | src/adhocracy/lib/app_globals.py | src/adhocracy/lib/app_globals.py | """The application's Globals object"""
import logging
import memcache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self, config):
"""One instance of Globals is created... | """The application's Globals object"""
import logging
import memcache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self, config):
"""One instance of Globals is created... | Decrease log level for memcache setup | Decrease log level for memcache setup
| Python | agpl-3.0 | DanielNeugebauer/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,phihag/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,alkadis/vcv,alkadis/v... | ---
+++
@@ -22,7 +22,7 @@
"""
if 'memcached.server' in config:
self.cache = memcache.Client([config['memcached.server']])
- log.info("Memcache set up")
+ log.debug("Memcache set up")
log.debug("Flushing cache")
self.cache.flush_all()
... |
c7172405b835920d553aa3d5ac6d415da2253d0d | oneflow/core/social_pipeline.py | oneflow/core/social_pipeline.py | # -*- coding: utf-8 -*-
u"""
Copyright 2013-2014 Olivier Cortès <oc@1flow.io>.
This file is part of the 1flow project.
It provides {python,django}-social-auth pipeline helpers.
1flow is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by th... | # -*- coding: utf-8 -*-
u"""
Copyright 2013-2014 Olivier Cortès <oc@1flow.io>.
This file is part of the 1flow project.
It provides {python,django}-social-auth pipeline helpers.
1flow is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by th... | Remove useless/obsolete social pipeline function (it's done in social_auth post_save()+task to make pipeline independant and faster). | Remove useless/obsolete social pipeline function (it's done in social_auth post_save()+task to make pipeline independant and faster).
| Python | agpl-3.0 | 1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,WillianPaiva/1flow | ---
+++
@@ -26,34 +26,14 @@
# from django.shortcuts import redirect
-from social_auth.backends.facebook import FacebookBackend
-from social_auth.backends.twitter import TwitterBackend
-from social_auth.backends import google
+# from social_auth.backends.facebook import FacebookBackend
+# from social_auth.backend... |
44c174807d7362b5d7959f122f2a74ae9ccb7b38 | coney/request.py | coney/request.py | from .exceptions import MalformedRequestException
class Request(object):
def __init__(self, version, metadata, **kwargs):
self._version = version
self._metadata = metadata
self._arguments = kwargs
@property
def version(self):
return self._version
@property
def arg... | from .exceptions import MalformedRequestException
class Request(object):
def __init__(self, version, metadata, arguments):
self._version = version
self._metadata = metadata
self._arguments = arguments
@property
def version(self):
return self._version
@property
def... | Fix rpc argument handling when constructing a Request | Fix rpc argument handling when constructing a Request
| Python | mit | cbigler/jackrabbit | ---
+++
@@ -2,10 +2,10 @@
class Request(object):
- def __init__(self, version, metadata, **kwargs):
+ def __init__(self, version, metadata, arguments):
self._version = version
self._metadata = metadata
- self._arguments = kwargs
+ self._arguments = arguments
@property... |
033773dce75dc2c352d657443cf415775e3b30cc | erudite/components/knowledge_provider.py | erudite/components/knowledge_provider.py | """
Knowledge provider that will respond to requests made by the rdf publisher or another bot.
"""
from sleekxmpp.plugins.base import base_plugin
from rhobot.components.storage.client import StoragePayload
from rdflib.namespace import FOAF
from rhobot.namespace import RHO
import logging
logger = logging.getLogger(__na... | """
Knowledge provider that will respond to requests made by the rdf publisher or another bot.
"""
from sleekxmpp.plugins.base import base_plugin
from rhobot.components.storage.client import StoragePayload
from rdflib.namespace import FOAF
from rhobot.namespace import RHO
import logging
logger = logging.getLogger(__na... | Update knowledge provider to work with API changes. | Update knowledge provider to work with API changes.
| Python | bsd-3-clause | rerobins/rho_erudite | ---
+++
@@ -22,7 +22,7 @@
def post_init(self):
base_plugin.post_init(self)
- self.xmpp['rho_bot_rdf_publish'].add_message_handler(self._rdf_request_message)
+ self.xmpp['rho_bot_rdf_publish'].add_request_handler(self._rdf_request_message)
def _rdf_request_message(self, rdf_payload... |
b4399f3dfb8f15f1a811fbcc31453575ad83d277 | byceps/services/snippet/transfer/models.py | byceps/services/snippet/transfer/models.py | """
byceps.services.snippet.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from enum import Enum
from typing import NewType
from uuid import UUID
from attr import attrib, attrs
from ...site.transfer.models impor... | """
byceps.services.snippet.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from enum import Enum
from typing import NewType
from uuid import UUID
from attr import attrib, attrs
from ...site.transfer.models impor... | Add missing return types to scope factory methods | Add missing return types to scope factory methods
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps | ---
+++
@@ -23,11 +23,11 @@
name = attrib(type=str)
@classmethod
- def for_brand(cls, brand_id: BrandID):
+ def for_brand(cls, brand_id: BrandID) -> 'Scope':
return cls('brand', str(brand_id))
@classmethod
- def for_site(cls, site_id: SiteID):
+ def for_site(cls, site_id: SiteI... |
329fa135faca80bd9dee74989110aa6222e44e2b | landlab/io/vtk/vti.py | landlab/io/vtk/vti.py | #! /bin/env python
from landlab.io.vtk.writer import VtkWriter
from landlab.io.vtk.vtktypes import VtkUniformRectilinear
from landlab.io.vtk.vtkxml import (
VtkRootElement,
VtkGridElement,
VtkPieceElement,
VtkPointDataElement,
VtkCellDataElement,
VtkExtent,
VtkOrigin,
VtkSpacing,
)
cl... | #! /bin/env python
from landlab.io.vtk.writer import VtkWriter
from landlab.io.vtk.vtktypes import VtkUniformRectilinear
from landlab.io.vtk.vtkxml import (
VtkRootElement,
VtkGridElement,
VtkPieceElement,
VtkPointDataElement,
VtkCellDataElement,
VtkExtent,
VtkOrigin,
VtkSpacing,
)
cl... | Fix typos: encoding, data -> self.encoding, self.data | Fix typos: encoding, data -> self.encoding, self.data
| Python | mit | landlab/landlab,landlab/landlab,cmshobe/landlab,cmshobe/landlab,amandersillinois/landlab,cmshobe/landlab,amandersillinois/landlab,landlab/landlab | ---
+++
@@ -34,8 +34,8 @@
VtkPointDataElement(field.at_node, append=self.data,
encoding=self.encoding),
'CellData':
- VtkCellDataElement(field.at_cell, append=data,
- encoding=encoding),
+ ... |
1716d38b995638c6060faa0925861bd8ab4c0e2b | statsmodels/stats/tests/test_outliers_influence.py | statsmodels/stats/tests/test_outliers_influence.py | from numpy.testing import assert_almost_equal
from statsmodels.datasets import statecrime
from statsmodels.regression.linear_model import OLS
from statsmodels.stats.outliers_influence import reset_ramsey
from statsmodels.tools import add_constant
data = statecrime.load_pandas().data
def test_reset_stata():
mod ... | from numpy.testing import assert_almost_equal
from statsmodels.datasets import statecrime, get_rdataset
from statsmodels.regression.linear_model import OLS
from statsmodels.stats.outliers_influence import reset_ramsey
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tools imp... | Add pandas dataframe capability in variance_inflation_factor | ENH: Add pandas dataframe capability in variance_inflation_factor
| Python | bsd-3-clause | josef-pkt/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,bashtage... | ---
+++
@@ -1,9 +1,12 @@
from numpy.testing import assert_almost_equal
-from statsmodels.datasets import statecrime
+from statsmodels.datasets import statecrime, get_rdataset
from statsmodels.regression.linear_model import OLS
from statsmodels.stats.outliers_influence import reset_ramsey
+from statsmodels.stats.... |
c7e4fc5038cb2069193aa888c4978e9aeff995f7 | source/segue/backend/processor/background.py | source/segue/backend/processor/background.py | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import subprocess
import pickle
import base64
try:
from shlex import quote
except ImportError:
from pipes import quote
from .base import Processor
from .. import pickle_support
class BackgroundProcessor(... | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import subprocess
import pickle
import base64
try:
from shlex import quote
except ImportError:
from pipes import quote
from .base import Processor
from .. import pickle_support
class BackgroundProcessor(... | Fix failing command on Linux. | Fix failing command on Linux.
| Python | apache-2.0 | 4degrees/segue | ---
+++
@@ -41,7 +41,7 @@
'data[\'command\'](*data[\'args\'], **data[\'kw\'])'
).format(serialised.replace("'", r"\'"))
- command = ' '.join(['python', '-c', '"{0}"'.format(python_statement)])
+ command = ['python', '-c', python_statement]
process = sub... |
f2e770ec86fe60c6d1c2b5d7b606bd6c576d167d | common/djangoapps/enrollment/urls.py | common/djangoapps/enrollment/urls.py | """
URLs for the Enrollment API
"""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
EnrollmentView,
EnrollmentListView,
EnrollmentCourseDetailView
)
USERNAME_PATTERN = settings.USERNAME_PATTERN
urlpatterns = patterns(
'enrollment.views',
url(
... | """
URLs for the Enrollment API
"""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
EnrollmentView,
EnrollmentListView,
EnrollmentCourseDetailView
)
USERNAME_PATTERN = settings.USERNAME_PATTERN
urlpatterns = patterns(
'enrollment.views',
url(
... | Revert "enrollment api endpoint has been updated to accept trailing forward slashes" | Revert "enrollment api endpoint has been updated to accept trailing forward slashes"
| Python | agpl-3.0 | Edraak/edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/edx-platform | ---
+++
@@ -22,7 +22,7 @@
name='courseenrollment'
),
url(
- r'^enrollment/{course_key}'.format(course_key=settings.COURSE_ID_PATTERN),
+ r'^enrollment/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN),
EnrollmentView.as_view(),
name='courseenrollment'
... |
9a221d5b0ca59a3384b3580c996aa518aaa90b0c | stand/runner/stand_server.py | stand/runner/stand_server.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import gettext
import eventlet
import os
from stand.socketio_events import StandSocketIO
locales_path = os.path.join(os.path.dirname(__file__), '..', 'i18n', 'locales')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import gettext
import eventlet
import os
from stand.socketio_events import StandSocketIO
locales_path = os.path.join(os.path.dirname(__file__), '..', 'i18n', 'locales')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argu... | Fix problem with Python 2 to 3 | Fix problem with Python 2 to 3
| Python | apache-2.0 | eubr-bigsea/stand,eubr-bigsea/stand | ---
+++
@@ -25,7 +25,7 @@
t = gettext.translation('messages', locales_path, [args.lang],
fallback=True)
- t.install(str=True)
+ t.install()
app = create_app(config_file=args.config)
babel = create_babel_i18n(app)
@@ -33,11 +33,10 @@
stand_socket_io = StandSoc... |
4490e59bfe54874e17d3afd00ede0ad410dc7957 | numba/cuda/tests/cudapy/test_userexc.py | numba/cuda/tests/cudapy/test_userexc.py | from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim
from numba import cuda
from numba.core import config
class MyError(Exception):
pass
regex_pattern = (
r'In function [\'"]test_exc[\'"], file [\.\/\\\-a-zA-Z_0-9]+, line \d+'
)
class TestUserExc(SerialMixin, unittest.TestCase):
def ... | from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim
from numba import cuda
from numba.core import config
class MyError(Exception):
pass
regex_pattern = (
r'In function [\'"]test_exc[\'"], file [\:\.\/\\\-a-zA-Z_0-9]+, line \d+'
)
class TestUserExc(SerialMixin, unittest.TestCase):
de... | Add in windows drive pattern match. | Add in windows drive pattern match.
As title.
| Python | bsd-2-clause | gmarkall/numba,stuartarchibald/numba,stuartarchibald/numba,stonebig/numba,sklam/numba,seibert/numba,numba/numba,stonebig/numba,stuartarchibald/numba,sklam/numba,stuartarchibald/numba,cpcloud/numba,IntelLabs/numba,numba/numba,sklam/numba,cpcloud/numba,stonebig/numba,stonebig/numba,seibert/numba,gmarkall/numba,seibert/nu... | ---
+++
@@ -8,7 +8,7 @@
regex_pattern = (
- r'In function [\'"]test_exc[\'"], file [\.\/\\\-a-zA-Z_0-9]+, line \d+'
+ r'In function [\'"]test_exc[\'"], file [\:\.\/\\\-a-zA-Z_0-9]+, line \d+'
)
|
15a792e38152e9c7aa6a10bbc251e9b5f0df1341 | aurora/optim/sgd.py | aurora/optim/sgd.py | import numpy as np
from .base import Base
class SGD(Base):
def __init__(self, cost, params, lr=0.1, momentum=0.9):
super().__init__(cost, params, lr)
self.momentum = momentum
self.velocity = self._init_velocity_vec(params)
def step(self, feed_dict):
exe_output = self.executor.... | import numpy as np
from .base import Base
class SGD(Base):
def __init__(self, cost, params, lr=0.1, momentum=0.9):
super().__init__(cost, params, lr)
self.momentum = momentum
self.velocity = [np.zeros_like(param.const)for param in params]
def step(self, feed_dict):
exe_output ... | Improve velocity list initialisation in SGD | Improve velocity list initialisation in SGD
| Python | apache-2.0 | upul/Aurora,upul/Aurora,upul/Aurora | ---
+++
@@ -6,7 +6,7 @@
def __init__(self, cost, params, lr=0.1, momentum=0.9):
super().__init__(cost, params, lr)
self.momentum = momentum
- self.velocity = self._init_velocity_vec(params)
+ self.velocity = [np.zeros_like(param.const)for param in params]
def step(self, fee... |
79dc15a4db8f74bed5e06d19c5c4f8d895c04189 | flaskext/debugtoolbar/panels/versions.py | flaskext/debugtoolbar/panels/versions.py | import pkg_resources
from flaskext.debugtoolbar.panels import DebugPanel
_ = lambda x: x
flask_version = pkg_resources.working_set.require('flask')[0].version
class VersionDebugPanel(DebugPanel):
"""
Panel that displays the Django version.
"""
name = 'Version'
has_content = False
def nav_ti... | import pkg_resources
from flaskext.debugtoolbar.panels import DebugPanel
_ = lambda x: x
flask_version = pkg_resources.get_distribution('Flask').version
class VersionDebugPanel(DebugPanel):
"""
Panel that displays the Django version.
"""
name = 'Version'
has_content = False
def nav_title(se... | Modify the flask version retrieval (thanks donri) | Modify the flask version retrieval (thanks donri)
| Python | bsd-3-clause | dianchang/flask-debugtoolbar,lepture/flask-debugtoolbar,lepture/flask-debugtoolbar,dianchang/flask-debugtoolbar,dianchang/flask-debugtoolbar | ---
+++
@@ -4,7 +4,7 @@
_ = lambda x: x
-flask_version = pkg_resources.working_set.require('flask')[0].version
+flask_version = pkg_resources.get_distribution('Flask').version
class VersionDebugPanel(DebugPanel):
""" |
5351ad8324fa8388ea3b82425d03f43ac16d7313 | app.py | app.py | #!/usr/bin/env python
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
route = requests.get('htt... | #!/usr/bin/env python
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
payload = {'stop': stop}
... | Use Requests to encode stop as query param, verify API status code. | Use Requests to encode stop as query param, verify API status code.
| Python | mit | alykhank/NextRide,alykhank/NextRide | ---
+++
@@ -12,9 +12,10 @@
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
- route = requests.get('http://nextride.alykhan.com/api?stop='+str(stop)).json()
- if route:
- path = route
+ payload = {'stop': stop}
+ r = requests.get('http://nextride.alykhan.com/api', params=payload)
+... |
36b37cc3439b1b99b2496c9a8037de9e412ad151 | account_payment_partner/models/account_move_line.py | account_payment_partner/models/account_move_line.py | # Copyright 2016 Akretion (http://www.akretion.com/)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
payment_mode_id = fields.Many2one(
'account.payment.mode',
string='Pay... | # Copyright 2016 Akretion (http://www.akretion.com/)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
payment_mode_id = fields.Many2one(
'account.payment.mode',
string='Pay... | Add indexes on account payment models | Add indexes on account payment models
The fields where the indexes are added are used in searches in
account_payment_order, which becomes really slow when a database have
many lines.
| Python | agpl-3.0 | OCA/bank-payment,OCA/bank-payment | ---
+++
@@ -11,5 +11,6 @@
'account.payment.mode',
string='Payment Mode',
domain="[('company_id', '=', company_id)]",
- ondelete='restrict'
+ ondelete='restrict',
+ index=True,
) |
d0fe2fd4bc619a45d18c3e5ba911b15045366849 | api/tests/test_small_scripts.py | api/tests/test_small_scripts.py | """This module tests the small scripts - admin, model, and wsgi."""
import unittest
class SmallScriptsTest(unittest.TestCase):
def test_admin(self):
import api.admin
def test_models(self):
import api.models
def test_wsgi(self):
import apel_rest.wsgi
| """This module tests the small scripts - admin, model, and wsgi."""
# Using unittest and not django.test as no need for overhead of database
import unittest
class SmallScriptsTest(unittest.TestCase):
def test_admin(self):
"""Check that admin is importable."""
import api.admin
def test_models... | Add docstrings and comment to small scripts test | Add docstrings and comment to small scripts test
| Python | apache-2.0 | apel/rest,apel/rest | ---
+++
@@ -1,14 +1,18 @@
"""This module tests the small scripts - admin, model, and wsgi."""
+# Using unittest and not django.test as no need for overhead of database
import unittest
class SmallScriptsTest(unittest.TestCase):
def test_admin(self):
+ """Check that admin is importable."""
... |
01b17ee30889afe1eadf8ec98c187ca9b856d0f7 | connector/views.py | connector/views.py | from django.conf import settings
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseNotFound
from django.template import Template
from cancer_browser.core.http import HttpResponseSendFile
from django.core.urlresolvers import reverse
import os, re
def client_vars(request, bas... | from django.conf import settings
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseNotFound
from django.template import Template
from cancer_browser.core.http import HttpResponseSendFile
from django.core.urlresolvers import reverse
import os, re
def client_vars(request, bas... | Add mime type for sourcemaps. | Add mime type for sourcemaps.
| Python | apache-2.0 | ucscXena/ucsc-xena-client,ucscXena/ucsc-xena-client,acthp/ucsc-xena-client,ucscXena/ucsc-xena-client,ucscXena/ucsc-xena-client,ucscXena/ucsc-xena-client,acthp/ucsc-xena-client,acthp/ucsc-xena-client | ---
+++
@@ -18,7 +18,8 @@
types = {
'js': 'application/javascript',
'png': 'image/png',
- 'css': 'text/css'
+ 'css': 'text/css',
+ 'map': 'application/json'
}
|
0bf7bf5ee30ddfd1510d50f189d3bb581ec5048d | tangled/website/resources.py | tangled/website/resources.py | from tangled.web import Resource, config
from tangled.site.resources.entry import Entry
class Docs(Entry):
@config('text/html', template='tangled.website:templates/docs.mako')
def GET(self):
static_dirs = self.app.get_all('static_directory', as_dict=True)
links = []
for prefix, dir_a... | from tangled.web import Resource, config
from tangled.site.resources.entry import Entry
class Docs(Entry):
@config('text/html', template='tangled.website:templates/docs.mako')
def GET(self):
static_dirs = self.app.get_all('static_directory', as_dict=True)
links = []
for prefix, dir_a... | Add trailing slashes to docs links | Add trailing slashes to docs links
This avoids hitting the app only to have it redirect back to nginx.
| Python | mit | TangledWeb/tangled.website | ---
+++
@@ -12,7 +12,7 @@
for prefix, dir_app in static_dirs.items():
if prefix[0] == 'docs':
links.append({
- 'href': '/'.join(prefix),
+ 'href': '/'.join(prefix) + '/',
'text': prefix[1],
})
s... |
ba6b70be6bd329e952491eae387281c613794718 | pyledgertools/plugins/download/ofx.py | pyledgertools/plugins/download/ofx.py | """OFX downloader."""
from ofxtools.Client import OFXClient, BankAcct
from ofxtools.Types import DateTime
from yapsy.IPlugin import IPlugin
def make_date_kwargs(config):
return {k:DateTime().convert(v) for k,v in config.items() if k.startswith('dt')}
class OFXDownload(IPlugin):
"""OFX plugin class."""
... | """OFX downloader."""
from ofxtools.Client import OFXClient, BankAcct
from ofxtools.Types import DateTime
from yapsy.IPlugin import IPlugin
def make_date_kwargs(config):
return {k:DateTime().convert(v) for k,v in config.items() if k.startswith('dt')}
class OFXDownload(IPlugin):
"""OFX plugin class."""
... | Replace bankid with fid to avoid duplicate config options. | Replace bankid with fid to avoid duplicate config options.
| Python | unlicense | cgiacofei/pyledgertools,cgiacofei/pyledgertools | ---
+++
@@ -24,7 +24,7 @@
appver=config['appver']
)
- account = [BankAcct(config['bankid'], config['acctnum'], config['type'])]
+ account = [BankAcct(config['fid'], config['acctnum'], config['type'])]
kwargs = make_date_kwargs(config)
request = client.statemen... |
392f58abf7b163bb34e395f5818daa0a13d05342 | pyscriptic/tests/instructions_test.py | pyscriptic/tests/instructions_test.py |
from unittest import TestCase
from pyscriptic.instructions import PipetteOp, TransferGroup, PrePostMix
class PipetteOpTests(TestCase):
def setUp(self):
self.mix = PrePostMix(
volume="5:microliter",
speed="1:microliter/second",
repetitions=10,
)
def test_tr... |
from unittest import TestCase
from pyscriptic.instructions import PipetteOp, TransferGroup, PrePostMix
from pyscriptic.submit import pyobj_to_std_types
class PipetteOpTests(TestCase):
def setUp(self):
self.mix = PrePostMix(
volume="5:microliter",
speed="0.5:microliter/second",
... | Test conversion of Transfer to standard types works | Test conversion of Transfer to standard types works
| Python | bsd-2-clause | naderm/pytranscriptic,naderm/pytranscriptic | ---
+++
@@ -2,12 +2,13 @@
from unittest import TestCase
from pyscriptic.instructions import PipetteOp, TransferGroup, PrePostMix
+from pyscriptic.submit import pyobj_to_std_types
class PipetteOpTests(TestCase):
def setUp(self):
self.mix = PrePostMix(
volume="5:microliter",
- ... |
5bb4a72f9541fa59fa3770a52da6edb619f5a897 | submodules-to-glockfile.py | submodules-to-glockfile.py | #!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
for path in paths:
print "{repo} {sha}".format(
repo = path[7:],
sha = path_sha1(path)
)
def path_sha1(path):
cmd = "cd {} ... | #!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print "github.com/localhots/satan {}".format(path_sha1("."))
for path in paths:
print "{repo} {sha}".format(
repo = path[7:],
sha = ... | Add satan sha to glockfile script | Add satan sha to glockfile script
| Python | mit | localhots/satan,localhots/satan,localhots/satan,localhots/satan | ---
+++
@@ -7,6 +7,7 @@
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
+ print "github.com/localhots/satan {}".format(path_sha1("."))
for path in paths:
print "{repo} {sha}".format(
repo = path[7:], |
e72b6272469c382f14a6732514777aacbd457322 | rest_framework_json_api/exceptions.py | rest_framework_json_api/exceptions.py | from django.utils import encoding
from django.utils.translation import ugettext_lazy as _
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework_json_api.utils import format_value
def excepti... | from django.utils import encoding
from django.utils.translation import ugettext_lazy as _
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework_json_api.utils import format_value
def excepti... | Fix for some error messages that were split into several messages | Fix for some error messages that were split into several messages
The exception handler expects the error to be a list on line 33. In my
case they were a string, which lead to the split of the string into
multiple errors containing one character
| Python | bsd-2-clause | django-json-api/rest_framework_ember,Instawork/django-rest-framework-json-api,leifurhauks/django-rest-framework-json-api,hnakamur/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api,pombredanne/django-rest-framework-json-api,lukaslundgren/django-rest-framework-json-api,leo-naeka/rest_framework_... | ---
+++
@@ -30,7 +30,16 @@
if isinstance(error, dict):
errors.append(error)
else:
- for message in error:
+ if isinstance(error, list):
+ for message in error:
+ errors.append({
+ ... |
385e9c0b8af79de58efd3cf43b1981b7981d0a53 | sympy/geometry/__init__.py | sympy/geometry/__init__.py | """
A geometry module for the SymPy library. This module contains all of the
entities and functions needed to construct basic geometrical data and to
perform simple informational queries.
Usage:
======
Notes:
======
Currently the geometry module is restricted to the 2-dimensional
Euclidean space.
Examples
=... | """
A geometry module for the SymPy library. This module contains all of the
entities and functions needed to construct basic geometrical data and to
perform simple informational queries.
Usage:
======
Notes:
======
Currently the geometry module is restricted to the 2-dimensional
Euclidean space.
Examples
=... | Remove glob imports from sympy.geometry. | Remove glob imports from sympy.geometry.
| Python | bsd-3-clause | postvakje/sympy,Mitchkoens/sympy,farhaanbukhsh/sympy,sampadsaha5/sympy,kumarkrishna/sympy,MechCoder/sympy,lindsayad/sympy,maniteja123/sympy,yashsharan/sympy,sahilshekhawat/sympy,MechCoder/sympy,rahuldan/sympy,yashsharan/sympy,kevalds51/sympy,Designist/sympy,jaimahajan1997/sympy,emon10005/sympy,skidzo/sympy,mcdaniel67/s... | ---
+++
@@ -20,6 +20,7 @@
from sympy.geometry.line import Line, Ray, Segment
from sympy.geometry.ellipse import Ellipse, Circle
from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg
-from sympy.geometry.util import *
-from sympy.geometry.exceptions import *
+from sympy.geometry.util import... |
697fcbd5135c9c3610c4131fe36b9a2723be1eeb | mappyfile/__init__.py | mappyfile/__init__.py | # allow high-level functions to be accessed directly from the mappyfile module
from mappyfile.utils import load, loads, find, findall, dumps, write | # allow high-level functions to be accessed directly from the mappyfile module
from mappyfile.utils import load, loads, find, findall, dumps, write
__version__ = "0.3.0" | Add version to module init | Add version to module init
| Python | mit | geographika/mappyfile,geographika/mappyfile | ---
+++
@@ -1,2 +1,4 @@
# allow high-level functions to be accessed directly from the mappyfile module
from mappyfile.utils import load, loads, find, findall, dumps, write
+
+__version__ = "0.3.0" |
683765c26e0c852d06fd06a491e3906369ae14cd | votes/urls.py | votes/urls.py | from django.conf.urls import include, url
from django.views.generic import TemplateView
from votes.views import VoteView
urlpatterns = [
url(r'^(?P<vote_name>[\w-]+)$', VoteView.as_view()),
]
| from django.conf.urls import include, url
from django.views.generic import TemplateView
from votes.views import VoteView
urlpatterns = [
url(r'^(?P<vote_name>[\w-]+)$', VoteView.as_view(), name="vote"),
]
| Add name to vote view URL | Add name to vote view URL
| Python | mit | kuboschek/jay,kuboschek/jay,OpenJUB/jay,kuboschek/jay,OpenJUB/jay,OpenJUB/jay | ---
+++
@@ -5,5 +5,5 @@
from votes.views import VoteView
urlpatterns = [
- url(r'^(?P<vote_name>[\w-]+)$', VoteView.as_view()),
+ url(r'^(?P<vote_name>[\w-]+)$', VoteView.as_view(), name="vote"),
] |
0a60495fc2baef1c5115cd34e2c062c363dfedc8 | test/streamparse/cli/test_run.py | test/streamparse/cli/test_run.py | from __future__ import absolute_import, unicode_literals
import argparse
import unittest
from nose.tools import ok_
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from streamparse.cli.run import main, subparser_hook
class RunTestCase(unittest.TestCase):
def test_subpar... | from __future__ import absolute_import, unicode_literals
import argparse
import unittest
from nose.tools import ok_
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from streamparse.cli.run import main, subparser_hook
class RunTestCase(unittest.TestCase):
def test_subpar... | Fix mock needing config_file variable | Fix mock needing config_file variable
| Python | apache-2.0 | Parsely/streamparse,Parsely/streamparse | ---
+++
@@ -34,7 +34,8 @@
run_local_mock.assert_called_with(name='my_topo',
options={'topology.acker.executors': 1},
env_name='my_env',
- time=0)
+ ... |
b665da9bdebb6736eef08f782d7361a34dcd30c5 | bin/import_media.py | bin/import_media.py | #!/usr/bin/python
import sys
sys.path.append('.')
from vacker.importer import Importer
importer = Importer()
# Need to obtain from arguments
importer.import_directory('../sample_photos')
| #!/usr/bin/python
import sys
sys.path.append('.')
import argparse
from vacker.importer import Importer
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--directory', '-d', type=str, dest='directory',
help='Directory to import', required=True)
args = pa... | Update imported to use arg parser | Update imported to use arg parser
| Python | apache-2.0 | MatthewJohn/vacker,MatthewJohn/vacker,MatthewJohn/vacker | ---
+++
@@ -2,9 +2,19 @@
import sys
sys.path.append('.')
+import argparse
from vacker.importer import Importer
+
+parser = argparse.ArgumentParser(description='Process some integers.')
+parser.add_argument('--directory', '-d', type=str, dest='directory',
+ help='Directory to import', requi... |
07f81307d10062cc15704a09015e542197edcafa | doxylink/setup.py | doxylink/setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as stream:
long_desc = stream.read()
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-doxylink',
version='0.3',
url='http://packages.python.org/sphinxcontrib-doxylink',
download_url='http://pypi.python.... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as stream:
long_desc = stream.read()
requires = ['Sphinx>=0.6', 'pyparsing']
setup(
name='sphinxcontrib-doxylink',
version='0.3',
url='http://packages.python.org/sphinxcontrib-doxylink',
download_url='http:/... | Add pyparsing to the dependencies. | Add pyparsing to the dependencies.
| Python | bsd-2-clause | sphinx-contrib/spelling,sphinx-contrib/spelling | ---
+++
@@ -5,7 +5,7 @@
with open('README.rst') as stream:
long_desc = stream.read()
-requires = ['Sphinx>=0.6']
+requires = ['Sphinx>=0.6', 'pyparsing']
setup(
name='sphinxcontrib-doxylink', |
f5aa886ed3a38971fe49c115221c849eae1a8e10 | byceps/util/instances.py | byceps/util/instances.py | # -*- coding: utf-8 -*-
"""
byceps.util.instances
~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
class ReprBuilder(object):
"""An instance representation builder."""
def __init__(self, instance):
self.instance = instance
... | # -*- coding: utf-8 -*-
"""
byceps.util.instances
~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
class ReprBuilder(object):
"""An instance representation builder."""
def __init__(self, instance):
self.instance = instance
... | Apply `repr()` to values passed to `ReprBuilder.add`, too | Apply `repr()` to values passed to `ReprBuilder.add`, too
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps | ---
+++
@@ -19,11 +19,11 @@
def add_with_lookup(self, name):
"""Add the attribute with its value looked up on the instance."""
value = getattr(self.instance, name)
- return self.add(name, repr(value))
+ return self.add(name, value)
def add(self, name, value):
"""Ad... |
2d4310cab029269cd53c776a3da238fa375e2ee1 | DebianChangesBot/mailparsers/accepted_upload.py | DebianChangesBot/mailparsers/accepted_upload.py | # -*- coding: utf-8 -*-
from DebianChangesBot import MailParser
from DebianChangesBot.messages import AcceptedUploadMessage
class AcceptedUploadParser(MailParser):
@staticmethod
def parse(headers, body):
msg = AcceptedUploadMessage()
mapping = {
'Source': 'package',
'... | # -*- coding: utf-8 -*-
from DebianChangesBot import MailParser
from DebianChangesBot.messages import AcceptedUploadMessage
class AcceptedUploadParser(MailParser):
@staticmethod
def parse(headers, body):
if headers.get('List-Id', '') != '<debian-devel-changes.lists.debian.org>':
return
... | Check accepted uploads List-Id, otherwise we get false +ves from bugs-dist | Check accepted uploads List-Id, otherwise we get false +ves from bugs-dist
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
| Python | agpl-3.0 | xtaran/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot | ---
+++
@@ -7,6 +7,9 @@
@staticmethod
def parse(headers, body):
+ if headers.get('List-Id', '') != '<debian-devel-changes.lists.debian.org>':
+ return
+
msg = AcceptedUploadMessage()
mapping = { |
4180680c9964661d3edd9eafad23b8d90699170d | fuzzyfinder/main.py | fuzzyfinder/main.py | # -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(input, collection, accessor=lambda x: x):
"""
Args:
input (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
... | # -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(input, collection, accessor=lambda x: x):
"""
Args:
input (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
... | Use accessor to use in sort. | Use accessor to use in sort.
| Python | bsd-3-clause | amjith/fuzzyfinder | ---
+++
@@ -21,6 +21,6 @@
for item in collection:
r = regex.search(accessor(item))
if r:
- suggestions.append((len(r.group()), r.start(), item))
+ suggestions.append((len(r.group()), r.start(), accessor(item), item))
- return (z for _, _, z in sorted(suggestions))
+ ... |
e80d4b35472e692f05e986116a5910e1a9612f74 | build/android/pylib/gtest/gtest_config.py | build/android/pylib/gtest/gtest_config.py | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
... | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
... | Move andorid webkit tests to main waterfall and CQ | Move andorid webkit tests to main waterfall and CQ
They have been stable and fast on FYI bots for a week.
TBR=yfriedman@chromium.org
Review URL: https://codereview.chromium.org/12093034
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@179266 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,TheTypoMaster... | ---
+++
@@ -6,15 +6,14 @@
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
- 'TestWebKitAPI',
'sandbox_linux_unittests',
- 'webkit_unit_tests',
]
# Do not modify this list without approval of an android owner.
# This list determines which suites ar... |
17ef821757df8eadfe8bf4769e57503625464f7b | bucketeer/test/test_commit.py | bucketeer/test/test_commit.py | import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
# Constants - TODO move to config file
global existing_bucket, test_dir, test_file
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
test_file = 'bucketeer_test_file'
def setUp(self):
connec... | import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
# Constants - TODO move to config file
global existing_bucket, test_dir, test_file
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
test_file = 'bucketeer_test_file'
def setUp(self):
connec... | Refactor test name to include the word 'To' | Refactor test name to include the word 'To'
Previous: testNewFileUploadExistingBucket
Current: testNewFileUploadToExistingBucket
| Python | mit | mgarbacz/bucketeer | ---
+++
@@ -45,7 +45,7 @@
def testMain(self):
self.assertTrue(commit)
- def testNewFileUploadExistingBucket(self):
+ def testNewFileUploadToExistingBucket(self):
result = commit.commit_to_s3(existing_bucket, test_dir)
self.assertTrue(result)
|
b39ea7848141037c7829a01d789591d91a81398e | ceph_medic/tests/test_main.py | ceph_medic/tests/test_main.py | import pytest
import ceph_medic.main
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
... | import pytest
import ceph_medic.main
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
... | Add test for valid ssh_config | tests/main: Add test for valid ssh_config
Signed-off-by: Zack Cerza <d7cdf09fc0f0426e98c9978ee42da5d61fa54986@redhat.com>
| Python | mit | alfredodeza/ceph-doctor | ---
+++
@@ -12,3 +12,11 @@
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'the given ssh config path does not exist' in out.out
+
+ def test_valid_ssh_config(self, capsys):
+ ssh_config = '/etc/ssh/ssh_config'
+ argv = ["ceph-medic", "--ssh-config", ssh_co... |
36998345ef900286527a3896f70cf4a85414ccf8 | rohrpost/main.py | rohrpost/main.py | import json
from functools import partial
from . import handlers # noqa
from .message import send_error
from .registry import HANDLERS
REQUIRED_FIELDS = ['type', 'id']
try:
DECODE_ERRORS = (json.JSONDecodeError, TypeError)
except AttributeError:
# Python 3.3 and 3.4 raise a ValueError instead of json.JSOND... | import json
from functools import partial
from . import handlers # noqa
from .message import send_error
from .registry import HANDLERS
REQUIRED_FIELDS = ['type', 'id']
try:
DECODE_ERRORS = (json.JSONDecodeError, TypeError)
except AttributeError:
# Python 3.3 and 3.4 raise a ValueError instead of json.JSOND... | Use keyword arguments in code | Use keyword arguments in code
| Python | mit | axsemantics/rohrpost,axsemantics/rohrpost | ---
+++
@@ -21,26 +21,26 @@
A valid JSON object including at least an "id" and "type" field.
It then hands off further handling to the registered handler (if any).
"""
- _send_error = partial(send_error, message, None, None)
+ _send_error = partial(send_error, message=message, message_id=None, ha... |
d9a205dce1f67151ff896909413bb7128e54a4ec | dduplicated/cli.py | dduplicated/cli.py | # The client of DDuplicated tool.
from os import path as opath, getcwd
from pprint import pprint
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):... | # The client of DDuplicated tool.
from os import path as opath, getcwd
from pprint import pprint
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):... | Fix in output to help command. | Fix in output to help command.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
| Python | mit | messiasthi/dduplicated-cli | ---
+++
@@ -23,7 +23,7 @@
if len(params) == 0 or "help" in params:
commands.help()
- exit()
+ exit(0)
elif "detect" in params:
processed_files = commands.detect(get_paths(params))
@@ -36,7 +36,7 @@
else:
commands.help()
- exit()
+ exit(0)
if len(processed_files) > 0:
pprint(process... |
194557f236016ec0978e5cc465ba40e7b8dff714 | s3backup/main.py | s3backup/main.py | # -*- coding: utf-8 -*-
from s3backup.clients import compare, LocalSyncClient
def sync():
local_client = LocalSyncClient('/home/michael/Notebooks')
current = local_client.get_current_state()
index = local_client.get_index_state()
print(list(compare(current, index)))
local_client.update_index()
| # -*- coding: utf-8 -*-
import os
from s3backup.clients import compare, LocalSyncClient
def sync():
target_folder = os.path.expanduser('~/Notebooks')
local_client = LocalSyncClient(target_folder)
current = local_client.get_current_state()
index = local_client.get_index_state()
print(list(compar... | Use expanduser to prevent hardcoding username | Use expanduser to prevent hardcoding username
| Python | mit | MichaelAquilina/s3backup,MichaelAquilina/s3backup | ---
+++
@@ -1,10 +1,14 @@
# -*- coding: utf-8 -*-
+
+import os
from s3backup.clients import compare, LocalSyncClient
def sync():
- local_client = LocalSyncClient('/home/michael/Notebooks')
+ target_folder = os.path.expanduser('~/Notebooks')
+
+ local_client = LocalSyncClient(target_folder)
curr... |
a4a37a783efcfd1cbb21acc29077c8096a0a0198 | spacy/lang/pl/__init__.py | spacy/lang/pl/__init__.py | # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .stop_words import STOP_WORDS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ...language import Language
from ...attrs import LANG
from ...util import update_exc
class Polish(Language):
la... | # coding: utf8
from __future__ import unicode_literals
from .stop_words import STOP_WORDS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ...language import Language
from ...attrs import LANG
from ...util import update_exc
class Polish(Language):
lang = 'pl'
class Defaults(Language.Defaults):
... | Remove import from non-existing module | Remove import from non-existing module
| Python | mit | honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,honnibal/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/s... | ---
+++
@@ -1,7 +1,6 @@
# coding: utf8
from __future__ import unicode_literals
-from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .stop_words import STOP_WORDS
from ..tokenizer_exceptions import BASE_EXCEPTIONS |
530b1b09b7fd6215822283c22c126ce7c18ac9a9 | services/rdio.py | services/rdio.py | from werkzeug.urls import url_decode
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY
import foauth.providers
class Rdio(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.rdio.com/'
docs_url = 'http://developer.rdio.com/docs/REST/'
category = 'Music'
#... | from werkzeug.urls import url_decode
import foauth.providers
class Rdio(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.rdio.com/'
docs_url = 'http://developer.rdio.com/docs/REST/'
category = 'Music'
# URLs to interact with the API
request_token_url = '... | Allow Rdio to use default signature handling | Allow Rdio to use default signature handling
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | ---
+++
@@ -1,5 +1,4 @@
from werkzeug.urls import url_decode
-from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY
import foauth.providers
@@ -21,7 +20,6 @@
]
https = False
- signature_type = SIGNATURE_TYPE_BODY
def parse_token(self, content):
# Override standard token request ... |
7486f423d018aaf53af94bc8af8bde6d46e73e71 | class4/exercise6.py | class4/exercise6.py | from getpass import getpass
from netmiko import ConnectHandler
def main():
password = getpass()
pynet_rtr1 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 22}
pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'pa... | # Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
from getpass import getpass
from netmiko import ConnectHandler
def main():
password = getpass()
pynet_rtr1 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 22}
pynet_rtr... | Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx. | Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
| Python | apache-2.0 | linkdebian/pynet_course | ---
+++
@@ -1,3 +1,4 @@
+# Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
from getpass import getpass
from netmiko import ConnectHandler
|
3decbd1e235a6a43541bb8e9846ea1d08bec1ef8 | tools/linter_lib/pyflakes.py | tools/linter_lib/pyflakes.py | import argparse
from typing import List
from zulint.linters import run_pyflakes
def check_pyflakes(files: List[str], options: argparse.Namespace) -> bool:
suppress_patterns = [
("scripts/lib/pythonrc.py", "imported but unused"),
# Intentionally imported by zerver/lib/webhooks/common.py
(... | import argparse
from typing import List
from zulint.linters import run_pyflakes
def check_pyflakes(files: List[str], options: argparse.Namespace) -> bool:
suppress_patterns = [
("scripts/lib/pythonrc.py", "imported but unused"),
# Intentionally imported by zerver/lib/webhooks/common.py
(... | Remove settings exemption for possibly undefined star imports. | lint: Remove settings exemption for possibly undefined star imports.
Signed-off-by: Anders Kaseorg <dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com>
| Python | apache-2.0 | timabbott/zulip,eeshangarg/zulip,synicalsyntax/zulip,eeshangarg/zulip,showell/zulip,timabbott/zulip,synicalsyntax/zulip,kou/zulip,zulip/zulip,hackerkid/zulip,brainwane/zulip,punchagan/zulip,timabbott/zulip,showell/zulip,brainwane/zulip,brainwane/zulip,eeshangarg/zulip,kou/zulip,timabbott/zulip,hackerkid/zulip,zulip/zul... | ---
+++
@@ -18,7 +18,6 @@
("settings.py", "settings import *' used; unable to detect undefined names"),
("settings.py", "'from .prod_settings_template import *' used; unable to detect undefined names"),
- ("settings.py", "may be undefined, or defined from star imports"),
("settings... |
5231efb00409ffd0b1b0e1cf111d81782468cdd3 | wye/regions/forms.py | wye/regions/forms.py | from django import forms
from django.core.exceptions import ValidationError
from wye.profiles.models import UserType
from . import models
class RegionalLeadForm(forms.ModelForm):
class Meta:
model = models.RegionalLead
exclude = ()
def clean(self):
location = self.cleaned_data['loc... | from django import forms
from django.core.exceptions import ValidationError
from wye.profiles.models import UserType
from . import models
class RegionalLeadForm(forms.ModelForm):
class Meta:
model = models.RegionalLead
exclude = ()
def clean(self):
error_message = []
if (se... | Handle empty location and leads data | Handle empty location and leads data
| Python | mit | shankig/wye,harisibrahimkv/wye,shankisg/wye,shankisg/wye,shankisg/wye,harisibrahimkv/wye,pythonindia/wye,pythonindia/wye,shankig/wye,DESHRAJ/wye,harisibrahimkv/wye,pythonindia/wye,shankig/wye,shankig/wye,shankisg/wye,DESHRAJ/wye,harisibrahimkv/wye,DESHRAJ/wye,DESHRAJ/wye,pythonindia/wye | ---
+++
@@ -13,14 +13,16 @@
exclude = ()
def clean(self):
- location = self.cleaned_data['location']
error_message = []
- for u in self.cleaned_data['leads']:
- if not u.profile:
- error_message.append('Profile for user %s not found' % (u))
- ... |
e1514fa5bcc35df74295c254df65e8e99dc289a1 | speeches/util.py | speeches/util.py | from speeches.tasks import transcribe_speech
from django.forms.widgets import SplitDateTimeWidget
"""Common utility functions/classes
Things that are needed by multiple bits of code but are specific enough to
this project not to be in a separate python package"""
def start_transcribing_speech(speech):
"""Kick off... | from speeches.tasks import transcribe_speech
"""Common utility functions/classes
Things that are needed by multiple bits of code but are specific enough to
this project not to be in a separate python package"""
def start_transcribing_speech(speech):
"""Kick off a celery task to transcribe a speech"""
# We onl... | Remove BootstrapSplitDateTimeWidget as it's no longer needed | Remove BootstrapSplitDateTimeWidget as it's no longer needed
| Python | agpl-3.0 | opencorato/sayit,opencorato/sayit,opencorato/sayit,opencorato/sayit | ---
+++
@@ -1,5 +1,4 @@
from speeches.tasks import transcribe_speech
-from django.forms.widgets import SplitDateTimeWidget
"""Common utility functions/classes
Things that are needed by multiple bits of code but are specific enough to
@@ -18,27 +17,3 @@
# Finally, we can remember the new task in the mode... |
ab0fd99e1c2c336cd5ce68e5fdb8a58384bfa794 | elasticsearch.py | elasticsearch.py | #!/usr/bin/env python
import json
import requests
ES_HOST = 'localhost'
ES_PORT = '9200'
ELASTICSEARCH = 'http://{0}:{1}'.format(ES_HOST, ES_PORT)
def find_indices():
"""Find indices created by logstash."""
url = ELASTICSEARCH + '/_search'
r = requests.get(url, params={'_q': '_index like logstash%'})
... | #!/usr/bin/env python
import json
import requests
ES_HOST = 'localhost'
ES_PORT = '9200'
ELASTICSEARCH = 'http://{0}:{1}'.format(ES_HOST, ES_PORT)
def find_indices():
"""Find indices created by logstash."""
url = ELASTICSEARCH + '/_search'
r = requests.get(url, params={'_q': '_index like logstash%'})
... | Handle the case where there are no logs | Handle the case where there are no logs
| Python | apache-2.0 | mancdaz/rpc-openstack,busterswt/rpc-openstack,npawelek/rpc-maas,git-harry/rpc-openstack,sigmavirus24/rpc-openstack,jpmontez/rpc-openstack,mattt416/rpc-openstack,xeregin/rpc-openstack,busterswt/rpc-openstack,stevelle/rpc-openstack,xeregin/rpc-openstack,miguelgrinberg/rpc-openstack,cfarquhar/rpc-openstack,xeregin/rpc-ope... | ---
+++
@@ -29,7 +29,10 @@
def main():
- latest = find_indices()[-1]
+ indices = find_indices()
+ if not indices:
+ return
+ latest = indices[-1]
num_errors = get_number_of('ERROR', latest)
num_warnings = get_number_of('WARN*', latest)
print 'metric int NUMBER_OF_LOG_ERRORS {0}'... |
48cc6633a6020114f5b5eeaaf53ddb08085bfae5 | models/settings.py | models/settings.py | from openedoo_project import db
from openedoo_project import config
class Setting(db.Model):
__tablename__ = 'module_employee_site_setting'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.Text)
def serialize(self):
... | from openedoo_project import db
class Setting(db.Model):
__tablename__ = 'module_employee_site_setting'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.Text)
def serialize(self):
return {
'id': sel... | Remove Unused config imported from openedoo_project, pylint. | Remove Unused config imported from openedoo_project, pylint.
| Python | mit | openedoo/module_employee,openedoo/module_employee,openedoo/module_employee | ---
+++
@@ -1,5 +1,4 @@
from openedoo_project import db
-from openedoo_project import config
class Setting(db.Model): |
cb2746f60cd63019b41eebedb148bfc5a25c1ba0 | indra/preassembler/make_wm_ontmap.py | indra/preassembler/make_wm_ontmap.py | from indra.sources import eidos
from indra.sources.hume.make_hume_tsv import make_file
from indra.java_vm import autoclass
eidos_package = 'org.clulab.wm.eidos'
if __name__ == '__main__':
bbn_path = 'hume_examaples.tsv'
make_file(bbn_path)
sofia_path = 'sofia_examples.tsv'
om = autoclass(eidos_packag... | import sys
from indra.sources import eidos
from indra.sources.hume.make_hume_tsv import make_file as mht
from indra.sources.sofia.make_sofia_tsv import make_file as mst
from indra.java_vm import autoclass
eidos_package = 'org.clulab.wm.eidos'
if __name__ == '__main__':
sofia_ont_path = sys.argv[1]
hume_path =... | Update make WM ontmap with SOFIA | Update make WM ontmap with SOFIA
| Python | bsd-2-clause | pvtodorov/indra,johnbachman/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,johnbachman/belpy | ---
+++
@@ -1,13 +1,17 @@
+import sys
from indra.sources import eidos
-from indra.sources.hume.make_hume_tsv import make_file
+from indra.sources.hume.make_hume_tsv import make_file as mht
+from indra.sources.sofia.make_sofia_tsv import make_file as mst
from indra.java_vm import autoclass
eidos_package = 'org.cl... |
a3ec10088f379c25e0ab9c7b7e29abd2bf952806 | karld/iter_utils.py | karld/iter_utils.py | from functools import partial
from itertools import imap
from itertools import islice
from operator import itemgetter
def yield_getter_of(getter_maker, iterator):
"""
Iteratively map iterator over the result of getter_maker.
:param getter_maker: function that returns a getter function.
:param iterato... | from functools import partial
from itertools import imap
from itertools import islice
from operator import itemgetter
def yield_getter_of(getter_maker, iterator):
"""
Iteratively map iterator over the result of getter_maker.
:param getter_maker: function that returns a getter function.
:param iterato... | Use iter's sentinel arg instead of infinite loop | Use iter's sentinel arg instead of infinite loop
| Python | apache-2.0 | johnwlockwood/karl_data,johnwlockwood/stream_tap,johnwlockwood/stream_tap,johnwlockwood/iter_karld_tools | ---
+++
@@ -38,9 +38,6 @@
:type iterable: iter
"""
iterable_items = iter(iterable)
-
- while True:
- items_batch = tuple(islice(iterable_items, max_size))
- if not items_batch:
- break
+ for items_batch in iter(lambda: tuple(islice(iterable_items, max_size)),
+ ... |
67cce913a6ab960b7ddc476fa9a16adb39a69862 | compose/__init__.py | compose/__init__.py | from __future__ import absolute_import
from __future__ import unicode_literals
__version__ = '1.25.1'
| from __future__ import absolute_import
from __future__ import unicode_literals
__version__ = '1.26.0dev'
| Set dev version to 1.26.0dev after releasing 1.25.1 | Set dev version to 1.26.0dev after releasing 1.25.1
Signed-off-by: Ulysses Souza <9b58b28cc7619bff4119b8572e41bbb4dd363aab@gmail.com>
| Python | apache-2.0 | vdemeester/compose,thaJeztah/compose,vdemeester/compose,thaJeztah/compose | ---
+++
@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
-__version__ = '1.25.1'
+__version__ = '1.26.0dev' |
d8a93f06cf6d78c543607d7046017cad3acc6c32 | tests/test_callback.py | tests/test_callback.py | import tests
class CallbackTests(tests.TestCase):
def test_hello_world(self):
result = []
def hello_world(loop):
result.append('Hello World')
loop.stop()
self.loop.call_soon(hello_world, self.loop)
self.loop.run_forever()
self.assertEqual(result, ['... | import tests
class CallbackTests(tests.TestCase):
def test_hello_world(self):
result = []
def hello_world(loop):
result.append('Hello World')
loop.stop()
self.loop.call_soon(hello_world, self.loop)
self.loop.run_forever()
self.assertEqual(result, ['... | Remove a test which behaves differently depending on the the version of asyncio/trollius | Remove a test which behaves differently depending on the the version of asyncio/trollius
| Python | apache-2.0 | overcastcloud/aioeventlet | ---
+++
@@ -32,16 +32,6 @@
self.loop.run_forever()
self.assertEqual(result, ["Hello", "World"])
- def test_close_soon(self):
- def func():
- pass
-
- self.loop.close()
- # FIXME: calling call_soon() on a closed event loop should raise an
- # exception:
- ... |
5b6ac8301908777a69dbbf74eb85af8b505fa76f | download_agents.py | download_agents.py | #!/usr/bin/env python3
from __future__ import print_function
from argparse import ArgumentParser
import json
import os
from urllib.request import urlopen
import subprocess
import sys
def main():
parser = ArgumentParser()
parser.add_argument('downloads_file', metavar='downloads-file')
args = parser.parse_... | #!/usr/bin/env python3
from __future__ import print_function
from argparse import ArgumentParser
import errno
import json
import os
from urllib.request import urlopen
import subprocess
import sys
def main():
parser = ArgumentParser()
parser.add_argument('downloads_file', metavar='downloads-file')
args = ... | Create parent directories as needed. | Create parent directories as needed. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | ---
+++
@@ -2,6 +2,7 @@
from __future__ import print_function
from argparse import ArgumentParser
+import errno
import json
import os
from urllib.request import urlopen
@@ -22,6 +23,11 @@
else:
print('Downloading: {}'.format(path), end='')
sys.stdout.flush()
+ try:... |
af0f42b86a1e3f916041eb78a4332daf0f22531a | OIPA/manage.py | OIPA/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OIPA.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
from dotenv import find_dotenv, load_dotenv
load_dotenv(find_dotenv())
if __name__ == "__main__":
current_settings = os.getenv("DJANGO_SETTINGS_MODULE", None)
if not current_settings:
raise Exception(
"Please configure your .env file along-side ... | Load current settings from .env file | Load current settings from .env file
OIPA-645
| Python | agpl-3.0 | openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,openaid-IATI/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA | ---
+++
@@ -2,8 +2,20 @@
import os
import sys
+from dotenv import find_dotenv, load_dotenv
+
+load_dotenv(find_dotenv())
+
if __name__ == "__main__":
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OIPA.settings")
+ current_settings = os.getenv("DJANGO_SETTINGS_MODULE", None)
+
+ if not current_setti... |
c1b96a3ee94c25cfbe3d66eec76052badacfb38e | udata/tests/organization/test_notifications.py | udata/tests/organization/test_notifications.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from udata.models import MembershipRequest, Member
from udata.core.user.factories import UserFactory
from udata.core.organization.factories import OrganizationFactory
from udata.core.organization.notifications import (
membership_req... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import pytest
from udata.models import MembershipRequest, Member
from udata.core.user.factories import UserFactory
from udata.core.organization.factories import OrganizationFactory
from udata.core.organization.notifications import (
... | Migrate org notif tests to pytest | Migrate org notif tests to pytest
| Python | agpl-3.0 | opendatateam/udata,etalab/udata,etalab/udata,opendatateam/udata,opendatateam/udata,etalab/udata | ---
+++
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
+
+import pytest
from udata.models import MembershipRequest, Member
@@ -9,10 +11,11 @@
membership_request_notifications
)
-from .. import TestCase, DBTestMixin
+from udata.tests.helpers import asser... |
5a3935caab0bf720db6707bb7974eec2400f3701 | prompt_toolkit/key_binding/bindings/auto_suggest.py | prompt_toolkit/key_binding/bindings/auto_suggest.py | """
Key bindings for auto suggestion (for fish-style auto suggestion).
"""
from __future__ import unicode_literals
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.filters import Condition
__all__ = [
'load_auto_suggest_bindi... | """
Key bindings for auto suggestion (for fish-style auto suggestion).
"""
from __future__ import unicode_literals
import re
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.filters import Condition, emacs_mode
__all__ = [
'l... | Add alt-f binding for auto-suggestion. | Add alt-f binding for auto-suggestion.
| Python | bsd-3-clause | jonathanslenders/python-prompt-toolkit | ---
+++
@@ -2,9 +2,10 @@
Key bindings for auto suggestion (for fish-style auto suggestion).
"""
from __future__ import unicode_literals
+import re
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
-from prompt_toolkit.filters import Condition
+... |
ea3deb560aaddab4d66a84e840e10854cfad581d | nass/__init__.py | nass/__init__.py | # -*- coding: utf-8 -*-
"""
USDA National Agricultural Statistics Service API wrapper
This Python wrapper implements the public API for the USDA National
Agricultural Statistics Service. It is a very thin layer over the Requests
package.
This product uses the NASS API but is not endorsed or certified by NASS.
:copyr... | # -*- coding: utf-8 -*-
"""
USDA National Agricultural Statistics Service API wrapper
This Python wrapper implements the public API for the USDA National
Agricultural Statistics Service. It is a very thin layer over the Requests
package.
This product uses the NASS API but is not endorsed or certified by NASS.
:copyr... | Make package-level import at the top (pep8) | Make package-level import at the top (pep8)
| Python | mit | nickfrostatx/nass | ---
+++
@@ -12,8 +12,8 @@
:license: MIT, see LICENSE for more details.
"""
+from .api import NassApi
+
__author__ = 'Nick Frost'
__version__ = '0.1.1'
__license__ = 'MIT'
-
-from .api import NassApi |
fd302e3f9cbc5bcf06d47600adc3e0f0df33c114 | f8a_jobs/auth.py | f8a_jobs/auth.py | from flask import session
from flask_oauthlib.client import OAuth
import f8a_jobs.defaults as configuration
oauth = OAuth()
github = oauth.remote_app(
'github',
consumer_key=configuration.GITHUB_CONSUMER_KEY,
consumer_secret=configuration.GITHUB_CONSUMER_SECRET,
request_token_params={'scope': 'user:ema... | from flask import session
from flask_oauthlib.client import OAuth
import f8a_jobs.defaults as configuration
oauth = OAuth()
github = oauth.remote_app(
'github',
consumer_key=configuration.GITHUB_CONSUMER_KEY,
consumer_secret=configuration.GITHUB_CONSUMER_SECRET,
request_token_params={'scope': 'user:ema... | Add read organization scope for OAuth | Add read organization scope for OAuth
This will enable to access jobs service even for not public organization
members.
| Python | apache-2.0 | fabric8-analytics/fabric8-analytics-jobs,fabric8-analytics/fabric8-analytics-jobs | ---
+++
@@ -7,7 +7,7 @@
'github',
consumer_key=configuration.GITHUB_CONSUMER_KEY,
consumer_secret=configuration.GITHUB_CONSUMER_SECRET,
- request_token_params={'scope': 'user:email'},
+ request_token_params={'scope': 'user:email,read:org'},
base_url='https://api.github.com/',
request_to... |
6a2782b11bcec2c1493258957ce7e8652d6990e8 | core/build/views.py | core/build/views.py | from core.build.subnet import build_subnet
from core.network.models import Network
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse
import pdb
def build_network(request, network_pk):
network = get_object_or_404(Network, pk=network_pk)
if request.GET.pop(... | from core.build.subnet import build_subnet
from core.network.models import Network
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse
import pdb
def build_network(request, network_pk):
network = get_object_or_404(Network, pk=network_pk)
if request.GET.get(... | Revert "use pop instead of get because it doens't cause uncaught exceptions." | Revert "use pop instead of get because it doens't cause uncaught exceptions."
This reverts commit 7aa3e4128b9df890a2683faee0ebe2ee8e64ce33.
| Python | bsd-3-clause | zeeman/cyder,murrown/cyder,akeym/cyder,OSU-Net/cyder,murrown/cyder,drkitty/cyder,murrown/cyder,drkitty/cyder,akeym/cyder,akeym/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,OSU-Net/cyder,akeym/cyder,zeeman/cyder,drkitty/cyder,OSU-Net/cyder,murrown/cyder,OSU-Net/cyder | ---
+++
@@ -8,7 +8,7 @@
def build_network(request, network_pk):
network = get_object_or_404(Network, pk=network_pk)
- if request.GET.pop("raw", False):
+ if request.GET.get('raw'):
DEBUG_BUILD_STRING = build_subnet(network, raw=True)
return HttpResponse(DEBUG_BUILD_STRING)
else: |
5b0d308d1859920cc59e7241626472edb42c7856 | djangosanetesting/testrunner.py | djangosanetesting/testrunner.py | from django.test.utils import setup_test_environment, teardown_test_environment
from django.db.backends.creation import create_test_db, destroy_test_db
import nose
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
""" Run tests with nose instead of defualt test runner """
setup_test_en... | import sys
from django.conf import settings
from django.test.utils import setup_test_environment, teardown_test_environment
import nose
from nose.config import Config, all_config_files
from nose.plugins.manager import DefaultPluginManager
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
... | Use database connection instead of old-style functions | Use database connection instead of old-style functions
| Python | bsd-3-clause | Almad/django-sane-testing | ---
+++
@@ -1,20 +1,32 @@
+import sys
+
+from django.conf import settings
from django.test.utils import setup_test_environment, teardown_test_environment
-from django.db.backends.creation import create_test_db, destroy_test_db
+
import nose
+from nose.config import Config, all_config_files
+from nose.plugins.manage... |
e40797a40e1e8f76a48ffeaec2dcdb179b702062 | microdrop/tests/test_dmf_device.py | microdrop/tests/test_dmf_device.py | from path import path
from nose.tools import raises
from dmf_device import DmfDevice
from utility import Version
def test_load_dmf_device():
"""
test loading DMF device files
"""
# version 0.2.0 files
for i in [0,1]:
yield load_device, (path(__file__).parent /
... | from path import path
from nose.tools import raises
from dmf_device import DmfDevice
from utility import Version
def test_load_dmf_device():
"""
test loading DMF device files
"""
# version 0.2.0 files
for i in [0, 1]:
yield load_device, (path(__file__).parent /
... | Add test for device 0 v0.3.0 | Add test for device 0 v0.3.0
| Python | bsd-3-clause | wheeler-microfluidics/microdrop | ---
+++
@@ -10,13 +10,13 @@
"""
# version 0.2.0 files
- for i in [0,1]:
+ for i in [0, 1]:
yield load_device, (path(__file__).parent /
path('devices') /
path('device %d v%s' % (i, Version(0,2,0))))
# version 0.3.0 files
- f... |
b92fb486107ef6feb4def07f601e7390d80db565 | plugins/androidapp.py | plugins/androidapp.py | """
paragoo plugin for retrieving card on an Android app
"""
import os
import requests
from bs4 import BeautifulSoup
class AppNotFoundException(Exception):
pass
def render(site_path, params):
"""
Look up the Android app details from its Play Store listing
Format of params: <app_key>
app_key look... | """
paragoo plugin for retrieving card on an Android app
"""
import os
import requests
from bs4 import BeautifulSoup
class AppNotFoundException(Exception):
pass
def get_app_details(app_key):
url_full = 'https://play.google.com/store/apps/details?id=' + app_key
url = 'https://play.google.com/store/apps/d... | Split out the app detail lookup into function | Split out the app detail lookup into function
| Python | apache-2.0 | aquatix/paragoo,aquatix/paragoo | ---
+++
@@ -10,13 +10,7 @@
pass
-def render(site_path, params):
- """
- Look up the Android app details from its Play Store listing
- Format of params: <app_key>
- app_key looks like com.linkbubble.license.playstore
- """
- app_key = params[0]
+def get_app_details(app_key):
url_full = ... |
5344c97e7486229f9fae40bef2b73488d5aa2ffd | uchicagohvz/users/tasks.py | uchicagohvz/users/tasks.py | from celery import task
from django.conf import settings
from django.core import mail
import smtplib
@task(rate_limit=0.2)
def do_sympa_update(user, listname, subscribe):
if subscribe:
body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name())
else:
body = "QUIET DELETE %s %s" % (listname, user... | from celery import task
from django.conf import settings
from django.core import mail
import smtplib
@task
def do_sympa_update(user, listname, subscribe):
if subscribe:
body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name())
else:
body = "QUIET DELETE %s %s" % (listname, user.email)
email =... | Remove rate limit from do_sympa_update | Remove rate limit from do_sympa_update | Python | mit | kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz | ---
+++
@@ -5,7 +5,7 @@
import smtplib
-@task(rate_limit=0.2)
+@task
def do_sympa_update(user, listname, subscribe):
if subscribe:
body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) |
5c9bc019ea1461a82b9dbdd4b3df5c55be2a8274 | unihan_db/__about__.py | unihan_db/__about__.py | __title__ = 'unihan-db'
__package_name__ = 'unihan_db'
__description__ = 'SQLAlchemy models for UNIHAN database'
__version__ = '0.1.0'
__author__ = 'Tony Narlock'
__email__ = 'cihai@git-pull.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2017 Tony Narlock'
| __title__ = 'unihan-db'
__package_name__ = 'unihan_db'
__description__ = 'SQLAlchemy models for UNIHAN database'
__version__ = '0.1.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/cihai/unihan-db'
__pypi__ = 'https://pypi.org/project/unihan-db/'
__email__ = 'cihai@git-pull.com'
__license__ = 'MIT'
__cop... | Update to cihai software foundation, add github and pypi | Metadata: Update to cihai software foundation, add github and pypi
| Python | mit | cihai/unihan-db | ---
+++
@@ -3,6 +3,8 @@
__description__ = 'SQLAlchemy models for UNIHAN database'
__version__ = '0.1.0'
__author__ = 'Tony Narlock'
+__github__ = 'https://github.com/cihai/unihan-db'
+__pypi__ = 'https://pypi.org/project/unihan-db/'
__email__ = 'cihai@git-pull.com'
__license__ = 'MIT'
-__copyright__ = 'Copyright... |
131129b96995c0055ea0a7e27d7491a833e46566 | wwwhisper_auth/assets.py | wwwhisper_auth/assets.py | # wwwhisper - web access control.
# Copyright (C) 2013 Jan Wrobel <jan@mixedbit.org>
import os
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from django.views.decorators.cache import cache_page
from django.views.generic import View
from wwwhisper_auth imp... | # wwwhisper - web access control.
# Copyright (C) 2013-2022 Jan Wrobel <jan@mixedbit.org>
import os
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from django.views.decorators.cache import cache_page
from django.views.generic import View
from wwwhisper_aut... | Use 'open' instead of 'file' (no longer available in Python 3). | Use 'open' instead of 'file' (no longer available in Python 3).
| Python | mit | wrr/wwwhisper,wrr/wwwhisper,wrr/wwwhisper,wrr/wwwhisper | ---
+++
@@ -1,5 +1,5 @@
# wwwhisper - web access control.
-# Copyright (C) 2013 Jan Wrobel <jan@mixedbit.org>
+# Copyright (C) 2013-2022 Jan Wrobel <jan@mixedbit.org>
import os
@@ -15,7 +15,7 @@
def __init__(self, prefix, *args):
assert prefix is not None
- self.body = file(os.path.join(p... |
68fe680266f705bea2b33e614d7aac2ae13b46a2 | url_shortener/forms.py | url_shortener/forms.py | # -*- coding: utf-8 -*-
from flask_wtf import Form
from wtforms import StringField, validators
from .validation import not_spam
class ShortenedUrlForm(Form):
url = StringField(
'Url to be shortened',
[
validators.DataRequired(),
validators.URL(message="A valid url is requi... | # -*- coding: utf-8 -*-
from flask_wtf import Form
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedUrlForm(Form):
url = StringField(
'Url to be shortened',
[
validators.DataRequired(),
validators.URL(message="A va... | Replace not_spam validator with not_blacklisted_nor_spam in form class | Replace not_spam validator with not_blacklisted_nor_spam in form class
| Python | mit | piotr-rusin/url-shortener,piotr-rusin/url-shortener | ---
+++
@@ -2,7 +2,7 @@
from flask_wtf import Form
from wtforms import StringField, validators
-from .validation import not_spam
+from .validation import not_blacklisted_nor_spam
class ShortenedUrlForm(Form):
@@ -11,6 +11,6 @@
[
validators.DataRequired(),
validators.URL(mes... |
1cf354d834fbb81260c88718c57533a546fc9dfa | src/robots/actions/attitudes.py | src/robots/actions/attitudes.py | import logging; logger = logging.getLogger("robot." + __name__)
from robots.exception import RobotError
from robots.actions.look_at import sweep
from robots.action import *
###############################################################################
@action
def sorry(robot, speed = 0.5):
return sweep(robot,... | import logging; logger = logging.getLogger("robot." + __name__)
import random
from robots.exception import RobotError
from robots.lowlevel import *
from robots.actions.look_at import sweep
from robots.action import *
###############################################################################
@action
@workswit... | Update the knowledge base according to the emotion | [actions/attitude] Update the knowledge base according to the emotion
| Python | isc | chili-epfl/pyrobots,chili-epfl/pyrobots-nao | ---
+++
@@ -1,7 +1,10 @@
import logging; logger = logging.getLogger("robot." + __name__)
+
+import random
from robots.exception import RobotError
+from robots.lowlevel import *
from robots.actions.look_at import sweep
from robots.action import *
@@ -9,6 +12,52 @@
@action
+@workswith(ALL)
+def satisfied... |
4a0f4bb837151a28b8c9f495db4f9bd33eb45a77 | src/python/expedient_geni/backends.py | src/python/expedient_geni/backends.py | '''
Created on Aug 12, 2010
@author: jnaous
'''
import logging
import re
from django.contrib.auth.backends import RemoteUserBackend
from django.conf import settings
from expedient.common.permissions.shortcuts import give_permission_to
from django.contrib.auth.models import User
logger = logging.getLogger("expedient_g... | '''
Created on Aug 12, 2010
@author: jnaous
'''
import logging
import traceback
from django.contrib.auth.backends import RemoteUserBackend
from sfa.trust.gid import GID
from expedient_geni.utils import get_user_urn, urn_to_username
from geni.util.urn_util import URN
logger = logging.getLogger("expedient_geni.backends... | Use urn from certificate to create username | Use urn from certificate to create username
| Python | bsd-3-clause | avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf | ---
+++
@@ -4,15 +4,13 @@
@author: jnaous
'''
import logging
-import re
+import traceback
from django.contrib.auth.backends import RemoteUserBackend
-from django.conf import settings
-from expedient.common.permissions.shortcuts import give_permission_to
-from django.contrib.auth.models import User
+from sfa.trust... |
8c51722bff4460b33a33d0380b75047649119175 | pyhpeimc/__init__.py | pyhpeimc/__init__.py | #!/usr/bin/env python
# -*- coding: <encoding-name> -*-
'''
Copyright 2015 Hewlett Packard Enterprise Development LP
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/... | #!/usr/bin/env python
# -*- coding: ascii -*-
'''
Copyright 2015 Hewlett Packard Enterprise Development LP
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.... | Fix in groups.py for get_custom_views function. | Fix in groups.py for get_custom_views function.
| Python | apache-2.0 | HPNetworking/HP-Intelligent-Management-Center,HPENetworking/PYHPEIMC,netmanchris/PYHPEIMC | ---
+++
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-# -*- coding: <encoding-name> -*-
+# -*- coding: ascii -*-
'''
Copyright 2015 Hewlett Packard Enterprise Development LP |
cf03026a27f8f7d35430807d2295bf062c4e0ca9 | master/skia_master_scripts/android_factory.py | master/skia_master_scripts/android_factory.py | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility class to build the Skia master BuildFactory's for Android buildbots.
Overrides SkiaFactory with any Android-specific steps."""
from skia_mas... | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility class to build the Skia master BuildFactory's for Android buildbots.
Overrides SkiaFactory with any Android-specific steps."""
from skia_mas... | Add RunTests step for Android buildbots | Add RunTests step for Android buildbots
Requires https://codereview.appspot.com/5966078 ('Add AddRunCommandList(), a cleaner way of running multiple shell commands as a single buildbot step') to work.
Review URL: https://codereview.appspot.com/5975072
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@3594 2bbb7eff... | Python | bsd-3-clause | google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Ti... | ---
+++
@@ -21,9 +21,32 @@
if clobber:
self._skia_cmd_obj.AddClean()
- self._skia_cmd_obj.AddRun(
- run_command='../android/bin/android_make all -d xoom %s' % (
+ self._skia_cmd_obj.AddRunCommand(
+ command='../android/bin/android_make all -d nexus_s %s' % (
self._make_f... |
b3a9027940f854f84cbf8f05af79c1f98a56d349 | pretix/settings.py | pretix/settings.py | from pretix.settings import * # noqa
SECRET_KEY = "{{secret_key}}"
LOGGING["handlers"]["mail_admins"]["include_html"] = True # noqa
STATICFILES_STORAGE = (
"django.contrib.staticfiles.storage.ManifestStaticFilesStorage" # noqa
)
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",... | from pretix.settings import * # noqa
SECRET_KEY = "{{secret_key}}"
LOGGING["handlers"]["mail_admins"]["include_html"] = True # noqa
STATICFILES_STORAGE = (
"django.contrib.staticfiles.storage.ManifestStaticFilesStorage" # noqa
)
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",... | Allow all languages on pretix | Allow all languages on pretix
| Python | mit | patrick91/pycon,patrick91/pycon | ---
+++
@@ -18,6 +18,10 @@
}
}
+# Allow all the languages
+# see: pretix/settings.py#L425-L435
+LANGUAGES = [(k, v) for k, v in ALL_LANGUAGES] # noqa
+
USE_X_FORWARDED_HOST = True
SITE_URL = "https://tickets.pycon.it"
|
d343ba2abc476e1c6a26e273b9262aa5974b8ab5 | fireplace/rules.py | fireplace/rules.py | """
Base game rules (events, etc)
"""
from .actions import Attack, Damage, Destroy, Hit
from .dsl.selector import FRIENDLY_HERO, MINION, SELF
POISONOUS = Damage(MINION, None, SELF).on(Destroy(Damage.TARGETS))
class WeaponRules:
base_events = [
Attack(FRIENDLY_HERO).on(Hit(SELF, 1))
]
| """
Base game rules (events, etc)
"""
from .actions import Attack, Damage, Destroy, Hit
from .dsl.selector import FRIENDLY_HERO, MINION, SELF
POISONOUS = Damage(MINION, None, SELF).on(Destroy(Damage.TARGETS))
class WeaponRules:
base_events = [
Attack(FRIENDLY_HERO).after(Hit(SELF, 1))
]
| Move Weapon durability hits to Attack.after() | Move Weapon durability hits to Attack.after()
| Python | agpl-3.0 | smallnamespace/fireplace,smallnamespace/fireplace,jleclanche/fireplace,amw2104/fireplace,NightKev/fireplace,beheh/fireplace,Ragowit/fireplace,Ragowit/fireplace,amw2104/fireplace | ---
+++
@@ -10,5 +10,5 @@
class WeaponRules:
base_events = [
- Attack(FRIENDLY_HERO).on(Hit(SELF, 1))
+ Attack(FRIENDLY_HERO).after(Hit(SELF, 1))
] |
639824dfa86b2aa98b1ae2ca3d4a5cec6ca329ea | nbgrader/preprocessors/__init__.py | nbgrader/preprocessors/__init__.py | from .headerfooter import IncludeHeaderFooter
from .lockcells import LockCells
from .clearsolutions import ClearSolutions
from .findstudentid import FindStudentID
from .saveautogrades import SaveAutoGrades
from .displayautogrades import DisplayAutoGrades
from .computechecksums import ComputeChecksums
from .savecells im... | from .headerfooter import IncludeHeaderFooter
from .lockcells import LockCells
from .clearsolutions import ClearSolutions
from .saveautogrades import SaveAutoGrades
from .displayautogrades import DisplayAutoGrades
from .computechecksums import ComputeChecksums
from .savecells import SaveCells
from .overwritecells impor... | Remove FindStudentID from preprocessors init | Remove FindStudentID from preprocessors init
| Python | bsd-3-clause | EdwardJKim/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,ellisonbg/nbgrader,alope107/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,dementrock/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,jdfreder/nbgrader,jdfreder/nbgrader,ellisonbg/nbgrader,alope107/nbgrader,jupyter/nbgrader,module... | ---
+++
@@ -1,7 +1,6 @@
from .headerfooter import IncludeHeaderFooter
from .lockcells import LockCells
from .clearsolutions import ClearSolutions
-from .findstudentid import FindStudentID
from .saveautogrades import SaveAutoGrades
from .displayautogrades import DisplayAutoGrades
from .computechecksums import Co... |
83080df101aca13b9b044996a013794c94ab82ed | pronto/parsers/obo.py | pronto/parsers/obo.py | import os
import fastobo
from .base import BaseParser
from ._fastobo import FastoboParser
class OboParser(FastoboParser, BaseParser):
@classmethod
def can_parse(cls, path, buffer):
return buffer.lstrip().startswith((b"format-version:", b"[Term", b"[Typedef"))
def parse_from(self, handle):
... | import os
import fastobo
from .base import BaseParser
from ._fastobo import FastoboParser
class OboParser(FastoboParser, BaseParser):
@classmethod
def can_parse(cls, path, buffer):
return buffer.lstrip().startswith((b"format-version:", b"[Term", b"[Typedef"))
def parse_from(self, handle):
... | Make sure to parse OBO documents in order | Make sure to parse OBO documents in order
| Python | mit | althonos/pronto | ---
+++
@@ -13,7 +13,7 @@
def parse_from(self, handle):
# Load the OBO document through an iterator using fastobo
- doc = fastobo.iter(handle)
+ doc = fastobo.iter(handle, ordered=True)
# Extract metadata from the OBO header and resolve imports
self.ont.metadata = sel... |
44e062dd5f302c5eed66e2d54858e1b8f78b745b | src/data.py | src/data.py | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%... | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%... | Add site number and application type to properties. For better filtering of new and old biz. | Add site number and application type to properties. For better filtering of new and old biz.
| Python | unlicense | datascopeanalytics/chicago-new-business,datascopeanalytics/chicago-new-business | ---
+++
@@ -34,8 +34,16 @@
)
@property
+ def application_type(self):
+ return self['APPLICATION TYPE']
+
+ @property
def account_number(self):
return self['ACCOUNT NUMBER']
+
+ @property
+ def site_number(self):
+ return self['SITE NUMBER']
@property
... |
fec974d5eceed68fdfc2b30e4c4a0f78dfbb8808 | messagebird/base.py | messagebird/base.py | from datetime import datetime
class Base(object):
def load(self, data):
for name, value in data.items():
if hasattr(self, name):
setattr(self, name, value)
return self
def value_to_time(self, value):
if value != None:
return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S+00:00')
| from datetime import datetime
class Base(object):
def load(self, data):
for name, value in list(data.items()):
if hasattr(self, name):
setattr(self, name, value)
return self
def value_to_time(self, value):
if value != None:
return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S+00:00'... | Update dict.items() for Python 3 compatibility | Update dict.items() for Python 3 compatibility
In Python 3 `items()` return iterators, and a list is never fully
build. The `items()` method in Python 3 works like `viewitems()` in
Python 2.7.
For more information see:
https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instead-of-lists
| Python | bsd-2-clause | messagebird/python-rest-api | ---
+++
@@ -2,7 +2,7 @@
class Base(object):
def load(self, data):
- for name, value in data.items():
+ for name, value in list(data.items()):
if hasattr(self, name):
setattr(self, name, value)
|
e7a09ad3e3d57291aa509cd45b8d3ae7a4cadaf8 | scripts/delete_couchdb_collection.py | scripts/delete_couchdb_collection.py | import sys
import argparse
import os
from harvester.couchdb_init import get_couchdb
import couchdb
from harvester.couchdb_sync_db_by_collection import delete_collection
def confirm_deletion(cid):
prompt = "Are you sure you want to delete all couchdb " + \
"documents for %s? yes to confirm\n" % cid
... | #! /bin/env python
import sys
import argparse
import os
from harvester.couchdb_init import get_couchdb
import couchdb
from harvester.couchdb_sync_db_by_collection import delete_collection
def confirm_deletion(cid):
prompt = "Are you sure you want to delete all couchdb " + \
"documents for %s? yes to c... | Make it runnable directly from cli, no python in front | Make it runnable directly from cli, no python in front
| Python | bsd-3-clause | mredar/harvester,mredar/harvester,ucldc/harvester,barbarahui/harvester,ucldc/harvester,barbarahui/harvester | ---
+++
@@ -1,3 +1,4 @@
+#! /bin/env python
import sys
import argparse
import os |
733d48510c4d6d8f4b9f07b6e33075cc20d1720a | gewebehaken/app.py | gewebehaken/app.py | # -*- coding: utf-8 -*-
"""
Gewebehaken
~~~~~~~~~~~
The WSGI application
:Copyright: 2015 `Jochen Kupperschmidt <http://homework.nwsnet.de/>`_
:License: MIT, see LICENSE for details.
"""
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitt... | # -*- coding: utf-8 -*-
"""
Gewebehaken
~~~~~~~~~~~
The WSGI application
:Copyright: 2015 `Jochen Kupperschmidt <http://homework.nwsnet.de/>`_
:License: MIT, see LICENSE for details.
"""
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitt... | Remove default route for serving static files from URL map. | Remove default route for serving static files from URL map.
| Python | mit | homeworkprod/gewebehaken | ---
+++
@@ -20,7 +20,7 @@
def create_app(log_filename=None):
"""Create the actual application."""
- app = Flask(__name__)
+ app = Flask(__name__, static_folder=None)
if log_filename:
configure_logging(app, log_filename) |
75db5105d609a2b28f19ee675de866425e2c5c3e | salt/modules/cp.py | salt/modules/cp.py | '''
Minion side functions for salt-cp
'''
import os
def recv(files, dest):
'''
Used with salt-cp, pass the files dict, and the destination
'''
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.is... | '''
Minion side functions for salt-cp
'''
# Import python libs
import os
# Import salt libs
import salt.simpleauth
def recv(files, dest):
'''
Used with salt-cp, pass the files dict, and the destination.
This function recieves small fast copy files from the master via salt-cp
'''
ret = {}
for ... | Add in the minion module function to download files from the master | Add in the minion module function to download files from the master
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -1,11 +1,17 @@
'''
Minion side functions for salt-cp
'''
+# Import python libs
import os
+
+# Import salt libs
+import salt.simpleauth
def recv(files, dest):
'''
- Used with salt-cp, pass the files dict, and the destination
+ Used with salt-cp, pass the files dict, and the destination.
+
... |
1f3eb1c526171b0ee8d2cab05e182c067bfb6c2e | tests/unit/modules/defaults_test.py | tests/unit/modules/defaults_test.py | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import (
MagicMock,
patch,
NO_MOCK,
NO_MOCK_REASON
)
imp... | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import (
MagicMock,
patch,
NO_MOCK,
NO_MOCK_REASON
)
imp... | Remove useless mocked unit test | Remove useless mocked unit test
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -30,16 +30,6 @@
'''
Test cases for salt.modules.defaults
'''
- # 'get' function tests: 1
-
- def test_get(self):
- '''
- Test if it execute a defaults client run and return a dict
- '''
- mock = MagicMock(return_value='')
- with patch.dict(defaults.__... |
794a233a70ac8cdd4fc0812bd651757b35e605f2 | tests/unit/utils/test_sanitizers.py | tests/unit/utils/test_sanitizers.py | # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from salt.ext.six import text_type as text
# Import Salt Libs
from salt.utils.sanitizers import clean
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
from tests.support.moc... | # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from salt.ext.six import text_type as text
# Import Salt Libs
from salt.utils.sanitizers import clean, mask_args_value
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
from ... | Add unit test for masking key:value of YAML | Add unit test for masking key:value of YAML
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -5,7 +5,7 @@
from salt.ext.six import text_type as text
# Import Salt Libs
-from salt.utils.sanitizers import clean
+from salt.utils.sanitizers import clean, mask_args_value
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
@@ -47,3 +47,11 @@
assert response == 'so... |
b222fbbbcca019a1849e70cc46b1527fa5fe2082 | database.py | database.py | from redis import StrictRedis
class QuizDB(StrictRedis):
def get_all_quizzes(self):
return self.smembers('quiz')
| from redis import StrictRedis
class QuizDB(StrictRedis):
def get_all_quizzes(self):
return self.smembers('quiz')
def get_question(self, quizid, questionid):
return self.hget("{0}:question".format(quizid), questionid)
| Add function to get a question | Add function to get a question
| Python | bsd-2-clause | estreeper/quizalicious,estreeper/quizalicious,estreeper/quizalicious | ---
+++
@@ -3,3 +3,7 @@
class QuizDB(StrictRedis):
def get_all_quizzes(self):
return self.smembers('quiz')
+
+ def get_question(self, quizid, questionid):
+ return self.hget("{0}:question".format(quizid), questionid)
+ |
bf9addce584961e30456c74b767afe05ca5dbb71 | tests/test_it.py | tests/test_it.py | import requests
def test_notifications_admin_index():
# response = requests.request("GET", "http://localhost:6012")
response = requests.request("GET", "http://notifications-admin.herokuapp.com/")
assert response.status_code == 200
assert 'GOV.UK Notify' in response.content
| import requests
def test_notifications_admin_index():
# response = requests.request("GET", "http://localhost:6012")
response = requests.request("GET", "http://notifications-admin.herokuapp.com/")
assert response.status_code == 200
assert 'GOV.UK Notify' in str(response.content)
| Convert bytes to str for assertion | Convert bytes to str for assertion
| Python | mit | alphagov/notifications-functional-tests,alphagov/notifications-functional-tests | ---
+++
@@ -5,4 +5,4 @@
# response = requests.request("GET", "http://localhost:6012")
response = requests.request("GET", "http://notifications-admin.herokuapp.com/")
assert response.status_code == 200
- assert 'GOV.UK Notify' in response.content
+ assert 'GOV.UK Notify' in str(response.content) |
26d7b8a1e0fef6b32b5705634fe40504a6aa258d | tests/test_elsewhere_twitter.py | tests/test_elsewhere_twitter.py | from __future__ import print_function, unicode_literals
from gittip.elsewhere import twitter
from gittip.testing import Harness
class TestElsewhereTwitter(Harness):
def test_get_user_info_gets_user_info(self):
twitter.TwitterAccount(self.db, "1", {'screen_name': 'alice'}).opt_in('alice')
expecte... | from __future__ import print_function, unicode_literals
from gittip.elsewhere import twitter
from gittip.testing import Harness
class TestElsewhereTwitter(Harness):
def test_get_user_info_gets_user_info(self):
twitter.TwitterAccount(self.db, "1", {'screen_name': 'alice'}).opt_in('alice')
expecte... | Add a test for Twitter accounts with long identifier. | Add a test for Twitter accounts with long identifier.
| Python | mit | gratipay/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,studio666/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,studio666/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,studio666/gratipay.com,gratipay/... | ---
+++
@@ -11,3 +11,9 @@
expected = {"screen_name": "alice"}
actual = twitter.get_user_info(self.db, 'alice')
assert actual == expected
+
+ def test_get_user_info_gets_user_info_long(self):
+ twitter.TwitterAccount(self.db, 2147483648, {'screen_name': 'alice'}).opt_in('alice')
+ ... |
a6bed0c1de2fc437d3ad84f0b22d27d4706eb5ab | presentations/urls.py | presentations/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'presentations.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'presentations.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', incl... | Add URL routing to app | Add URL routing to app
| Python | mit | masonsbro/presentations | ---
+++
@@ -9,4 +9,5 @@
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
+ url(r'^', include('presentationsapp.urls')),
) |
dd2d5e96672fc7870434f030ca63f6d7111642f9 | resources/launchers/alfanousDesktop.py | resources/launchers/alfanousDesktop.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import alfanousDesktop.Gui
alfanousDesktop.Gui.main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
# The paths should be generated by setup script
sys.argv.extend(
'-i', '/usr/share/alfanous-indexes/',
'-l', '/usr/locale/',
'-c', '/usr/share/alfanous-config/')
from alfanousDesktop.Gui import *
main()
| Add resource paths to python launcher script (proxy) | Add resource paths to python launcher script (proxy)
Former-commit-id: 7d20874c43637f1236442333f60a88ec653f53f2 | Python | agpl-3.0 | muslih/alfanous,muslih/alfanous,muslih/alfanous,muslih/alfanous,muslih/alfanous,muslih/alfanous,muslih/alfanous | ---
+++
@@ -1,6 +1,14 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-import alfanousDesktop.Gui
+import sys
-alfanousDesktop.Gui.main()
+# The paths should be generated by setup script
+sys.argv.extend(
+ '-i', '/usr/share/alfanous-indexes/',
+ '-l', '/usr/locale/',
+ '-c', '/usr/share/alfanous-config/')
+
+... |
ed8139a505a93c3a99fbb147817cc5695aa0ffc7 | service/settings/local.py | service/settings/local.py | import os
from service.settings.production import *
DEBUG = { 0: False, 1: True }[int(os.getenv('DEBUG'))]
if DEBUG:
MIDDLEWARE += [
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
INSTALLED_APPS += [
'debug_toolbar',
]
INTERNAL_IPS = (
'127.0.0.1',
# Docker ... | import os
from service.settings.production import *
DEBUG = { 0: False, 1: True }[int(os.getenv('DEBUG'))]
# SSL/HTTPS Security
## Set SECURE_SSL_REDIRECT to True, so that requests over HTTP are redirected to HTTPS.
SECURE_PROXY_SSL_HEADER = None
SECURE_SSL_REDIRECT = False
## Use ‘secure’ cookies.
SESSION_COOKIE_... | Disable SSL/HTTPS (reverts to default values) | Disable SSL/HTTPS (reverts to default values)
Needing to explicitly set something to it’s default value perhaps isn’t ideal. | Python | unlicense | Mystopia/fantastic-doodle | ---
+++
@@ -4,6 +4,19 @@
DEBUG = { 0: False, 1: True }[int(os.getenv('DEBUG'))]
+# SSL/HTTPS Security
+
+## Set SECURE_SSL_REDIRECT to True, so that requests over HTTP are redirected to HTTPS.
+SECURE_PROXY_SSL_HEADER = None
+SECURE_SSL_REDIRECT = False
+
+## Use ‘secure’ cookies.
+SESSION_COOKIE_SECURE = False
... |
7cf3741070cba4d4e0016a7175158ec5993fd7f2 | klein/__init__.py | klein/__init__.py | from functools import wraps
from twisted.internet import reactor
from twisted.web.server import Site
from klein.decorators import expose
from klein.resource import KleinResource
routes = {}
def route(r):
def deco(f):
# Swallow self.
# XXX hilariously, staticmethod would be *great* here.
... | Add a couple things for Bottle-like behavior. | Add a couple things for Bottle-like behavior.
| Python | mit | macmania/klein,brighid/klein,hawkowl/klein,macmania/klein,joac/klein,alex/klein,joac/klein,brighid/klein | ---
+++
@@ -0,0 +1,26 @@
+from functools import wraps
+
+from twisted.internet import reactor
+from twisted.web.server import Site
+
+from klein.decorators import expose
+from klein.resource import KleinResource
+
+routes = {}
+
+def route(r):
+ def deco(f):
+ # Swallow self.
+ # XXX hilariously, sta... | |
7669e6c65d46615c8e52e53dba5a1b4812e34a02 | soccerstats/api.py | soccerstats/api.py | """
Blueprint implementing the API wrapper.
:author: 2013, Pascal Hartig <phartig@weluse.de>
:license: BSD
"""
import json
from flask import Blueprint, request, abort
from .utils import JSONError
from .calc import calculate_scores
api = Blueprint('api', __name__, url_prefix='/v1')
class ScoresResponse(object):
... | """
Blueprint implementing the API wrapper.
:author: 2013, Pascal Hartig <phartig@weluse.de>
:license: BSD
"""
import json
from flask import Blueprint, request, abort
from .utils import JSONError
from .calc import calculate_scores
api = Blueprint('api', __name__, url_prefix='/v1')
class ScoresResponse(object):
... | Return sorted values for scores | Return sorted values for scores
| Python | bsd-3-clause | passy/soccer-stats-backend | ---
+++
@@ -19,8 +19,13 @@
self.scores = scores
self.errors = errors
+ @property
+ def sorted_scores(self):
+ # Sort by descending by value
+ return dict(sorted(self.scores.items(), key=lambda x: -x[1]))
+
def to_json(self):
- return {'scores': self.scores, 'errors'... |
3eaf0ea514b0f78906af7e614079f3a90624bcc7 | estimate.py | estimate.py | #!/usr/bin/python3
from sys import stdin
def estimateConf(conf):
"""Estimate configuration from a string."""
confElements = [int(x) for x in conf.split(sep=" ")]
disk = confElements[0]
print(disk)
procRates = confElements[1:]
print(procRates)
def estimateConfsFromInput():
"""Parse and es... | #!/usr/bin/python3
from sys import stdin
def calcExhaustion(disk, procRates):
"""Calculate how many seconds before the disk is filled.
procRates lists the rates at which each process fills 1 byte of disk
space."""
print(disk)
print(procRates)
def estimateConf(conf):
"""Estimate ... | Create fn for calculating exhaustion | Create fn for calculating exhaustion
| Python | mit | MattHeard/EstimateDiskExhaustion | ---
+++
@@ -2,14 +2,20 @@
from sys import stdin
+def calcExhaustion(disk, procRates):
+ """Calculate how many seconds before the disk is filled.
+
+ procRates lists the rates at which each process fills 1 byte of disk
+ space."""
+ print(disk)
+ print(procRates)
def estimateConf(co... |
93ac186e90790c17014d905fd2f85e7e7dde1271 | osbrain/__init__.py | osbrain/__init__.py | import os
import Pyro4
Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle')
Pyro4.config.SERIALIZERS_ACCEPTED.add('dill')
Pyro4.config.SERIALIZER = 'dill'
Pyro4.config.THREADPOOL_SIZE = 16
Pyro4.config.SERVERTYPE = 'thread'
Pyro4.config.REQUIRE_EXPOSE = False
Pyro4.config.COMMTIMEOUT = 0.
Pyro4.config.DETAILED_TRACEBACK = T... | import os
import Pyro4
Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle')
Pyro4.config.SERIALIZERS_ACCEPTED.add('dill')
Pyro4.config.SERIALIZER = 'dill'
Pyro4.config.THREADPOOL_SIZE = 16
Pyro4.config.SERVERTYPE = 'thread'
Pyro4.config.REQUIRE_EXPOSE = False
Pyro4.config.COMMTIMEOUT = 0.
Pyro4.config.DETAILED_TRACEBACK = T... | Set default linger to 1 second | Set default linger to 1 second
| Python | apache-2.0 | opensistemas-hub/osbrain | ---
+++
@@ -11,7 +11,7 @@
os.environ['OSBRAIN_DEFAULT_TRANSPORT'] = 'ipc'
os.environ['OSBRAIN_DEFAULT_SAFE'] = 'true'
os.environ['OSBRAIN_DEFAULT_SERIALIZER'] = 'pickle'
-os.environ['OSBRAIN_DEFAULT_LINGER'] = '-1'
+os.environ['OSBRAIN_DEFAULT_LINGER'] = '1'
__version__ = '0.4.0'
|
8e2596db204d2f6779280309aaa06d90872e9fb2 | tests/test_bot_support.py | tests/test_bot_support.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/search?q=insta... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/sea... | Add test on check file if exist | Add test on check file if exist
| Python | apache-2.0 | instagrambot/instabot,ohld/instabot,instagrambot/instabot | ---
+++
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+
+import os
import pytest
@@ -20,3 +22,14 @@
])
def test_extract_urls(self, url, result):
assert self.BOT.extract_urls(url) == result
+
+ def test_check_if_file_exist(self):
+ test_file = open(... |
3c00c5de9d0bd6ecf860d09b786db9625e212102 | tools/perf_expectations/PRESUBMIT.py | tools/perf_expectations/PRESUBMIT.py | #!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on ... | #!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on ... | Use full pathname to perf_expectations in test. | Use full pathname to perf_expectations in test.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/266055
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@28770 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | adobe/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,... | ---
+++
@@ -13,12 +13,12 @@
'tests.perf_expectations_unittest',
]
-PERF_EXPECTATIONS = 'perf_expectations.json'
+PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
- if PERF_EXPECT... |
490ce27b6e9213cd9200b6fb42e7676af58abd58 | zou/app/models/custom_action.py | zou/app/models/custom_action.py | from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class CustomAction(db.Model, BaseMixin, SerializerMixin):
name = db.Column(db.String(80), nullable=False)
url = db.Column(db.String(400))
| from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class CustomAction(db.Model, BaseMixin, SerializerMixin):
name = db.Column(db.String(80), nullable=False)
url = db.Column(db.String(400))
entity_type = db.Column(db.String(40), default="a... | Add entity type column to actions | Add entity type column to actions
| Python | agpl-3.0 | cgwire/zou | ---
+++
@@ -6,3 +6,4 @@
class CustomAction(db.Model, BaseMixin, SerializerMixin):
name = db.Column(db.String(80), nullable=False)
url = db.Column(db.String(400))
+ entity_type = db.Column(db.String(40), default="all") |
76d9ff900204678423208967b4578764013984ad | tests/test-recipes/metadata/always_include_files_glob/run_test.py | tests/test-recipes/metadata/always_include_files_glob/run_test.py | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert sor... | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set... | Test sets instead of lists | Test sets instead of lists
| Python | bsd-3-clause | dan-blanchard/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,sandhujasmine/conda-build,dan-blanchard/conda-build,ilastik/conda-build,frol/conda-build,mwcraig/conda-build,rmcgibbo/conda-build,shastings517/conda-build,shastings517/conda-build,shastings517/conda-build,sandhujasmine/conda-build,frol/conda-build,... | ---
+++
@@ -11,9 +11,9 @@
info = json.load(fh)
if sys.platform == 'darwin':
- assert sorted(info['files']) == ['lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib']
+ assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}
elif s... |
025c3f6b73c97fdb58b1a492efcb6efe44cfdab0 | twisted/plugins/caldav.py | twisted/plugins/caldav.py | from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.python import reflect
def serviceMakerProperty(propname):
def getProperty(self):
return getattr(reflect.namedClass(self.serviceMakerClass), propname)
return prop... | from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.python import reflect
from twisted.internet.protocol import Factory
Factory.noisy = False
def serviceMakerProperty(propname):
def getProperty(self):
return getattr(... | Set Factory.noisy to False by default | Set Factory.noisy to False by default
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@3933 e27351fd-9f3e-4f54-a53b-843176b1656c
| Python | apache-2.0 | trevor/calendarserver,trevor/calendarserver,trevor/calendarserver | ---
+++
@@ -3,6 +3,10 @@
from twisted.application.service import IServiceMaker
from twisted.python import reflect
+
+from twisted.internet.protocol import Factory
+Factory.noisy = False
+
def serviceMakerProperty(propname):
def getProperty(self):
@@ -13,12 +17,13 @@
class TAP(object):
implements(I... |
1a16d598c902218a8112841219f89044724155da | smatic/templatetags/smatic_tags.py | smatic/templatetags/smatic_tags.py | import os
from commands import getstatusoutput
from django import template
from django.conf import settings
from django.utils._os import safe_join
register = template.Library()
def scss(file_path):
"""
Converts an scss file into css and returns the output
"""
input_path = safe_join(settings.SMATIC... | import os
from commands import getstatusoutput
from django import template
from django.conf import settings
from django.utils._os import safe_join
register = template.Library()
@register.simple_tag
def scss(file_path):
"""
Convert an scss file into css and returns the output.
"""
input_path = safe_jo... | Tidy up the code, and don't make settings.SASS_BIN a requirement (default to 'sass') | Tidy up the code, and don't make settings.SASS_BIN a requirement (default to 'sass')
| Python | bsd-3-clause | lincolnloop/django-smatic | ---
+++
@@ -6,32 +6,35 @@
register = template.Library()
+
+@register.simple_tag
def scss(file_path):
"""
- Converts an scss file into css and returns the output
+ Convert an scss file into css and returns the output.
"""
input_path = safe_join(settings.SMATIC_SCSS_PATH, file_path)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.