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 |
|---|---|---|---|---|---|---|---|---|---|---|
664ad3a2848f7188cd1ea562ddbfd4dc6947915b | tests/test_plugins/bad_server/server.py | tests/test_plugins/bad_server/server.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2015 Kitware Inc.
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may not use this file except in compliance with the License.
# You may obtain a cop... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware Inc.
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may not use this file except in compliance with the License.
# You may obtain a copy of ... | Remove year from file copyright | Remove year from file copyright
| Python | apache-2.0 | data-exp-lab/girder,Kitware/girder,sutartmelson/girder,sutartmelson/girder,kotfic/girder,RafaelPalomar/girder,Kitware/girder,data-exp-lab/girder,RafaelPalomar/girder,adsorensen/girder,jbeezley/girder,manthey/girder,kotfic/girder,Kitware/girder,RafaelPalomar/girder,adsorensen/girder,Xarthisius/girder,Xarthisius/girder,a... | ---
+++
@@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-
###############################################################################
-# Copyright 2015 Kitware Inc.
+# Copyright Kitware Inc.
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may not use this file except in compliance wit... |
7d6e6325e0baf5f4994350a7dd52856db0cb6c8a | src/apps/processing/ala/management/commands/ala_import.py | src/apps/processing/ala/management/commands/ala_import.py | import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Import data from ALA stations, optionally you can pass date.... | import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from dateutil import relativedelta
from datetime import date, timedelta
logger = logging.getLogger(__name__)
def parse_date_range(date_str):
if len(date_str) == 4:
... | Enable ALA import by month or year | Enable ALA import by month or year
| Python | bsd-3-clause | gis4dis/poster,gis4dis/poster,gis4dis/poster | ---
+++
@@ -2,34 +2,50 @@
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
+from dateutil import relativedelta
from datetime import date, timedelta
logger = logging.getLogger(__name__)
+def parse_date_range(date_str):
+ if le... |
830a767aa42cfafc22342ff71c23419c86845fe8 | src/Classes/SubClass/SubClass.py | src/Classes/SubClass/SubClass.py | class defaultDict(dict):
def __init__(self, default=None):
dict.__init__(self)
self.default = default
def __getitem__(self, key):
try:
return dict.__getitem____(self, key)
except KeyError:
return self.default | class defaultDict(dict):
def __init__(self, default=None):
dict.__init__(self)
self.default = default
def __getitem__(self, key):
if(key in self):
return dict.__getitem__(self, key)
else:
return self.default
def get(self, key, *args):
if not args:
... | Add get and merge method. Add Main Function to use class. | [Add] Add get and merge method.
Add Main Function to use class.
| Python | mit | williamHuang5468/ExpertPython | ---
+++
@@ -4,7 +4,42 @@
self.default = default
def __getitem__(self, key):
- try:
- return dict.__getitem____(self, key)
- except KeyError:
- return self.default
+ if(key in self):
+ return dict.__getitem__(self, key)
+ else:
+ retu... |
ad2b8bce02c7b7b7ab477fc7fccc1b38fb60e63a | turbustat/statistics/input_base.py | turbustat/statistics/input_base.py | # Licensed under an MIT open source license - see LICENSE
from astropy.io.fits import PrimaryHDU
from spectral_cube import SpectralCube
from spectral_cube.lower_dimensional_structures import LowerDimensionalObject
def input_data(data):
'''
Accept a variety of input data forms and return those expected by the... | # Licensed under an MIT open source license - see LICENSE
from astropy.io.fits import PrimaryHDU
from spectral_cube import SpectralCube
from spectral_cube.lower_dimensional_structures import LowerDimensionalObject
import numpy as np
def input_data(data, no_header=False):
'''
Accept a variety of input data fo... | Allow for the case when a header isn't needed | Allow for the case when a header isn't needed
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat | ---
+++
@@ -3,26 +3,53 @@
from astropy.io.fits import PrimaryHDU
from spectral_cube import SpectralCube
from spectral_cube.lower_dimensional_structures import LowerDimensionalObject
+import numpy as np
-def input_data(data):
+def input_data(data, no_header=False):
'''
Accept a variety of input data f... |
2ef4362be90e2314b69a2ff17ccb5d25ef8905fd | rackspace/database/database_service.py | rackspace/database/database_service.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Set default version for cloud databases. | Set default version for cloud databases.
| Python | apache-2.0 | rackerlabs/rackspace-sdk-plugin,briancurtin/rackspace-sdk-plugin | ---
+++
@@ -21,6 +21,9 @@
def __init__(self, version=None):
"""Create a database service."""
+ if not version:
+ version = "v1"
+
super(DatabaseService, self).__init__(service_type="rax:database",
service_name="cloudDatabases",
... |
a307bddf490b6ad16739593d4ca51693b9a340fe | regulations/templatetags/in_context.py | regulations/templatetags/in_context.py | from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcon... | from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcon... | Fix custom template tag to work with django 1.8 | Fix custom template tag to work with django 1.8
| Python | cc0-1.0 | 18F/regulations-site,jeremiak/regulations-site,18F/regulations-site,18F/regulations-site,eregs/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,jeremiak/regulations-site,jeremiak/regulation... | ---
+++
@@ -16,7 +16,8 @@
new_context.update(context.get(field, {}))
else:
new_context[field] = value
- return self.nodelist.render(template.Context(new_context))
+ new_context = context.new(new_context)
+ return self.nodelist.render(new_context)
... |
4a6f76857a626dd756675a4fe1dd3660cf63d8b7 | alg_fibonacci.py | alg_fibonacci.py | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import print_function
import time
def fibonacci(n):
"""Get nth number of Fibonacci series by recursion."""
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
... | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import print_function
def fibonacci(n):
"""Get nth number of Fibonacci series by recursion."""
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
... | Move module time to main() | Move module time to main()
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -8,7 +8,6 @@
"""
from __future__ import print_function
-import time
def fibonacci(n):
@@ -22,6 +21,7 @@
def main():
+ import time
n = 13
print('{}th number of Fibonacci series: {}'
.format(n, fibonacci(n))) |
ea5fd30a583016b4dc858848e28168ada74deca3 | blaze/py3help.py | blaze/py3help.py | import sys
import itertools
PY3 = sys.version_info[:2] >= (3,0)
if PY3:
def dict_iteritems(d):
return d.items().__iter__()
xrange = range
_inttypes = (int,)
_strtypes = (str,)
unicode = str
imap = map
basestring = str
import urllib
urlparse = urllib.parse
else:
import _... | import sys
import itertools
PY3 = sys.version_info[:2] >= (3,0)
if PY3:
def dict_iteritems(d):
return d.items().__iter__()
xrange = range
_inttypes = (int,)
_strtypes = (str,)
unicode = str
imap = map
basestring = str
import urllib.parse as urlparse
else:
import __builtin__... | Check in fix for py3k and urlparse. | Check in fix for py3k and urlparse.
| Python | bsd-3-clause | scls19fr/blaze,markflorisson/blaze-core,ChinaQuants/blaze,jdmcbr/blaze,nkhuyu/blaze,cpcloud/blaze,LiaoPan/blaze,FrancescAlted/blaze,cowlicks/blaze,FrancescAlted/blaze,mwiebe/blaze,markflorisson/blaze-core,mwiebe/blaze,ContinuumIO/blaze,FrancescAlted/blaze,aterrel/blaze,AbhiAgarwal/blaze,jdmcbr/blaze,aterrel/blaze,China... | ---
+++
@@ -12,8 +12,7 @@
unicode = str
imap = map
basestring = str
- import urllib
- urlparse = urllib.parse
+ import urllib.parse as urlparse
else:
import __builtin__
def dict_iteritems(d): |
05b2848849553172873600ffd6344fc2b1f12d8e | example/__init__.py | example/__init__.py | from pupa.scrape import Jurisdiction
from .people import PersonScraper
class Example(Jurisdiction):
jurisdiction_id = 'ex'
def get_metadata(self):
return {
'name': 'Example',
'legislature_name': 'Example Legislature',
'legislature_url': 'http://example.com',
... | from pupa.scrape import Jurisdiction
from .people import PersonScraper
class Example(Jurisdiction):
jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example'
def get_metadata(self):
return {
'name': 'Example',
'legislature_name': 'Example Legislature',
... | Substitute a more realistic jurisdiction_id | Substitute a more realistic jurisdiction_id
| Python | bsd-3-clause | datamade/pupa,mileswwatkins/pupa,rshorey/pupa,opencivicdata/pupa,mileswwatkins/pupa,influence-usa/pupa,datamade/pupa,influence-usa/pupa,rshorey/pupa,opencivicdata/pupa | ---
+++
@@ -4,7 +4,7 @@
class Example(Jurisdiction):
- jurisdiction_id = 'ex'
+ jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example'
def get_metadata(self):
return { |
3298fff0ded49c21897a7387a7f3093c351ae04f | scripts/run_psql.py | scripts/run_psql.py | #!/usr/bin/env python
# Copyright (C) 2011 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
from acoustid.script import run_script
import subprocess
def main(script, opts, args):
subprocess.call(['psql'] + script.config.database.create_psql_args())
run_script(main)
| #!/usr/bin/env python
# Copyright (C) 2011 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
from acoustid.script import run_script
import os
def main(script, opts, args):
os.execlp('psql', 'psql', *script.config.database.create_psql_args())
run_script(main)
| Use os.exelp to launch psql | Use os.exelp to launch psql
| Python | mit | lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server | ---
+++
@@ -4,11 +4,11 @@
# Distributed under the MIT license, see the LICENSE file for details.
from acoustid.script import run_script
-import subprocess
+import os
def main(script, opts, args):
- subprocess.call(['psql'] + script.config.database.create_psql_args())
+ os.execlp('psql', 'psql', *script... |
e10f2b85775412dd60f11deea6e7a7f8b84edfbe | buysafe/urls.py | buysafe/urls.py | from django.conf.urls import patterns
urlpatterns = patterns(
'buysafe.views',
(r'^entry/(?P<order_id>\d+)/$', 'entry'),
(r'^start/$', 'start'),
(r'^success/(?P<payment_type>[01])/$', 'success'),
(r'^fail/(?P<payment_type>[01])/$', 'fail'),
(r'^check/(?P<payment_type>[01])/$', 'check')
)
| from django.conf.urls import patterns, url
urlpatterns = patterns(
'buysafe.views',
url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'),
(r'^start/$', 'start'),
(r'^success/(?P<payment_type>[01])/$', 'success'),
(r'^fail/(?P<payment_type>[01])/$', 'fail'),
(r'^check/(?P<payment_typ... | Add name for entry view URL | Add name for entry view URL
| Python | bsd-3-clause | uranusjr/django-buysafe | ---
+++
@@ -1,9 +1,9 @@
-from django.conf.urls import patterns
+from django.conf.urls import patterns, url
urlpatterns = patterns(
'buysafe.views',
- (r'^entry/(?P<order_id>\d+)/$', 'entry'),
+ url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'),
(r'^start/$', 'start'),
(r'^succe... |
202a9b2ad72ffe4ab5981f9a4a886e0a36808eb6 | tests/sentry/utils/json/tests.py | tests/sentry/utils/json/tests.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import datetime
import uuid
from sentry.utils import json
from sentry.testutils import TestCase
class JSONTest(TestCase):
def test_uuid(self):
res = uuid.uuid4()
self.assertEquals(json.dumps(res), '"%s"' % res.hex)
def test_da... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import datetime
import uuid
from sentry.utils import json
from sentry.testutils import TestCase
class JSONTest(TestCase):
def test_uuid(self):
res = uuid.uuid4()
self.assertEquals(json.dumps(res), '"%s"' % res.hex)
def test_da... | Add test for handling Infinity in json | Add test for handling Infinity in json
| Python | bsd-3-clause | mitsuhiko/sentry,ifduyue/sentry,looker/sentry,mvaled/sentry,gencer/sentry,mvaled/sentry,looker/sentry,zenefits/sentry,korealerts1/sentry,zenefits/sentry,Kryz/sentry,kevinlondon/sentry,alexm92/sentry,JamesMura/sentry,mvaled/sentry,kevinlondon/sentry,looker/sentry,beeftornado/sentry,BuildingLink/sentry,ifduyue/sentry,fel... | ---
+++
@@ -31,3 +31,7 @@
res = '<script>alert(1);</script>'
assert json.dumps(res) == '"<script>alert(1);</script>"'
assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"'
+
+ def test_inf(self):
+ res = float('inf')
+ self.assertEquals(json.dumps(res), 'nu... |
27fec389928c93ba0efe4ca1e4c5b34c3b73fa2c | snippet/__init__.py | snippet/__init__.py | """
"cms.plugins.snippet" (from djangocms) clone to extend it with some facilities
""" | """
"cms.plugins.snippet" (from djangocms) clone to extend it with some facilities
"""
__version__ = '2.3.6.1'
| Add a version base on djangocms version from where the code was cloned | Add a version base on djangocms version from where the code was cloned
| Python | bsd-3-clause | emencia/emencia-cms-snippet,emencia/emencia-cms-snippet,emencia/emencia-cms-snippet | ---
+++
@@ -1,3 +1,4 @@
"""
"cms.plugins.snippet" (from djangocms) clone to extend it with some facilities
"""
+__version__ = '2.3.6.1' |
de22e547c57be633cb32d51e93a6efe9c9e90293 | src/helper_threading.py | src/helper_threading.py | import threading
try:
import prctl
def set_thread_name(name): prctl.set_name(name)
def _thread_name_hack(self):
set_thread_name(self.name)
threading.Thread.__bootstrap_original__(self)
threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap
threading.Thread._T... | import threading
try:
import prctl
def set_thread_name(name): prctl.set_name(name)
def _thread_name_hack(self):
set_thread_name(self.name)
threading.Thread.__bootstrap_original__(self)
threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap
threading.Thread._T... | Remove buggy log message if prctl is missing | Remove buggy log message if prctl is missing
- it's not that important that you need to be informed of it, and
importing logging may cause cyclic dependencies/other problems
| Python | mit | hb9kns/PyBitmessage,hb9kns/PyBitmessage,hb9kns/PyBitmessage,hb9kns/PyBitmessage | ---
+++
@@ -10,7 +10,6 @@
threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap
threading.Thread._Thread__bootstrap = _thread_name_hack
except ImportError:
- log('WARN: prctl module is not installed. You will not be able to see thread names')
def set_thread_name(name): pass
... |
a25920e3549933e4c6c158cc9490f3eaa883ec66 | Lib/test/test_heapq.py | Lib/test/test_heapq.py | """Unittests for heapq."""
from test.test_support import verify, vereq, verbose, TestFailed
from heapq import heappush, heappop
import random
def check_invariant(heap):
# Check the heap invariant.
for pos, item in enumerate(heap):
parentpos = ((pos+1) >> 1) - 1
if parentpos >= 0:
... | """Unittests for heapq."""
from test.test_support import verify, vereq, verbose, TestFailed
from heapq import heappush, heappop
import random
def check_invariant(heap):
# Check the heap invariant.
for pos, item in enumerate(heap):
if pos: # pos 0 has no parent
parentpos = (pos-1) >> 1
... | Use the same child->parent "formula" used by heapq.py. | check_invariant(): Use the same child->parent "formula" used by heapq.py.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -8,8 +8,8 @@
def check_invariant(heap):
# Check the heap invariant.
for pos, item in enumerate(heap):
- parentpos = ((pos+1) >> 1) - 1
- if parentpos >= 0:
+ if pos: # pos 0 has no parent
+ parentpos = (pos-1) >> 1
verify(heap[parentpos] <= item)
d... |
b12b4f47d3cd701506380c914e45b9958490392c | functional_tests.py | functional_tests.py | from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://localhost:8000')
assert 'Django' in browser.title
| from selenium import webdriver
import unittest
class NewVisitorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
self.browser.quit()
def test_can_start_a_list_and_retrieve_it_later(self):
# Edith has heard about a cool new onlien to-... | Add FT specs and use unittest. | Add FT specs and use unittest.
| Python | mit | ejpreciado/superlists,ejpreciado/superlists,ejpreciado/superlists | ---
+++
@@ -1,6 +1,50 @@
from selenium import webdriver
+import unittest
-browser = webdriver.Firefox()
-browser.get('http://localhost:8000')
+class NewVisitorTest(unittest.TestCase):
-assert 'Django' in browser.title
+ def setUp(self):
+ self.browser = webdriver.Firefox()
+
+ def tearDown(self):
+ ... |
d98e33d28105c8180b591e3097af83e42599bfc5 | django_local_apps/management/commands/docker_exec.py | django_local_apps/management/commands/docker_exec.py | import logging
import docker
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
log = logging.getLogger()
class DockerExecutor(DjangoCmdBase):
def add_arguments(self, parser):
# Positional arguments
"""
:param: in the args it could be: /usr/local/bin/python /... | import logging
import docker
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
log = logging.getLogger()
class DockerExecutor(DjangoCmdBase):
def add_arguments(self, parser):
# Positional arguments
"""
:param: in the args it could be: /usr/local/bin/python /... | Remove the usage of nargs to avoid different behaviors between chronograph and command line. | Remove the usage of nargs to avoid different behaviors between chronograph and command line.
| Python | bsd-3-clause | weijia/django-local-apps,weijia/django-local-apps | ---
+++
@@ -15,15 +15,19 @@
NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help"
:return:
"""
- parser.add_argument('--container_id', nargs=1)
- parser.add_argument('--work_dir', nargs='?', default=None)
+ # for using with c... |
36e7af17c8d7c4bdb9cfd20387c470697e1bac96 | po/build-babel.py | po/build-babel.py | import subprocess
from pathlib import Path
po_path: Path = Path(__file__).resolve().parent
def run_babel(command: str, input: Path, output_file: Path, locale: str):
subprocess.run(
[
"pybabel",
command,
f"--input={str(input)}",
f"--output-file={str(output_f... | import subprocess
from pathlib import Path
po_path: Path = Path(__file__).resolve().parent
def run_babel(command: str, input: Path, output_file: Path, locale: str):
subprocess.run(
[
"pybabel",
command,
f"--input={input}",
f"--output-file={output_file}",
... | Simplify f-string to remove cast | Simplify f-string to remove cast
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | ---
+++
@@ -9,9 +9,9 @@
[
"pybabel",
command,
- f"--input={str(input)}",
- f"--output-file={str(output_file)}",
- f"--locale={str(locale)}",
+ f"--input={input}",
+ f"--output-file={output_file}",
+ f"--locale={locale... |
7cee7edabad08b01ceda0ed8f2798ebf47c87e95 | src/pycontw2016/urls.py | src/pycontw2016/urls.py | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from core.views import flat_page
from users.views import user_dashboard
urlpatterns = [
url(r'^$', TemplateView.as_v... | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from core.views import flat_page
from users.views import user_dashboard
urlpatterns = [
url(r'^$', TemplateView.as_v... | Fix catch-all URLs with prefix | Fix catch-all URLs with prefix
| Python | mit | uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016 | ---
+++
@@ -26,6 +26,10 @@
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Catch-all URL pattern must be put last.
-urlpatterns += [
- url(r'^(?P<path>.+)/$', flat_page, name='page'),
-]
+if settings.URL_PREFIX:
+ urlpatterns += [
+ url(r'^{prefix}(?P<path>.+)/$'.format... |
e2cbd73218e6f5cf5b86718f6adebd92e9fee2a3 | geotrek/trekking/tests/test_filters.py | geotrek/trekking/tests/test_filters.py | from geotrek.land.tests.test_filters import LandFiltersTest
from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory
class TrekFilterLandTest(LandFiltersTest):
filterclass = TrekFilterSet
def test_land_filters_are_well_setup(self):
filterset = TrekFilter... | # Make sure land filters are set up when testing
from geotrek.land.filters import * # NOQA
from geotrek.land.tests.test_filters import LandFiltersTest
from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory
class TrekFilterLandTest(LandFiltersTest):
filterclass = T... | Make sure land filters are set up when testing | Make sure land filters are set up when testing
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,mabhub/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,makinacorpus/... | ---
+++
@@ -1,3 +1,5 @@
+# Make sure land filters are set up when testing
+from geotrek.land.filters import * # NOQA
from geotrek.land.tests.test_filters import LandFiltersTest
from geotrek.trekking.filters import TrekFilterSet |
c1b0cfe9fdfbacf71ffbba45b4a8f7efe3fe36a7 | docker/dev_wrong_port_warning.py | docker/dev_wrong_port_warning.py | #!/usr/bin/env python
"""
Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This
provides a helpful message to anyone still trying to use port 8000
"""
import BaseHTTPServer
import sys
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(503)
... | #!/usr/bin/env python
"""
Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This
provides a helpful message to anyone still trying to use port 8000
"""
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
se... | Update wront port script to Python3 | Update wront port script to Python3
| Python | bsd-2-clause | kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat | ---
+++
@@ -5,20 +5,22 @@
provides a helpful message to anyone still trying to use port 8000
"""
-import BaseHTTPServer
import sys
+from http.server import BaseHTTPRequestHandler, HTTPServer
-class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
+
+class Handler(BaseHTTPRequestHandler):
def do_GET(self):
... |
fee10efeae410a0bc51842877ef8ffb5fe8b97af | src/file_dialogs.py | src/file_dialogs.py | #!/usr/bin/env python
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | #!/usr/bin/env python
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Add gtk implementation of open_file | Add gtk implementation of open_file
| Python | apache-2.0 | natduca/trace_event_viewer,natduca/trace_event_viewer,natduca/trace_event_viewer | ---
+++
@@ -17,8 +17,28 @@
def open_file():
message_loop.init_main_loop()
if message_loop.is_gtk:
- raise Exception("not implemented")
- else:
+ import gtk
+ dlg = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_SAVE,
+ buttons=(gtk.STOCK_CANCEL,gtk.RESP... |
6104b111b4ceaec894018b77cbea4a0de31400d4 | chainer/trainer/extensions/_snapshot.py | chainer/trainer/extensions/_snapshot.py | from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
... | from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
... | Add name to the snapshot extension | Add name to the snapshot extension
| Python | mit | hvy/chainer,jnishi/chainer,ktnyt/chainer,chainer/chainer,cupy/cupy,hvy/chainer,ktnyt/chainer,cupy/cupy,wkentaro/chainer,ysekky/chainer,kikusu/chainer,pfnet/chainer,jnishi/chainer,okuta/chainer,keisuke-umezawa/chainer,ktnyt/chainer,okuta/chainer,niboshi/chainer,niboshi/chainer,cupy/cupy,rezoo/chainer,chainer/chainer,hvy... | ---
+++
@@ -26,7 +26,7 @@
the :meth:`str.format` method.
"""
- @extension.make_extension(trigger=(1, 'epoch'))
+ @extension.make_extension(name='snapshot', trigger=(1, 'epoch'))
def ext(trainer):
fname = filename.format(trainer)
fd, tmppath = tempfile.mkstemp(prefix=fn... |
ab6b61d8d0b91ebc2d0b1b8cbd526cfbb6a45a42 | chipy_org/libs/social_auth_pipelines.py | chipy_org/libs/social_auth_pipelines.py | from django.contrib.auth import get_user_model
from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with ... | from django.contrib.auth import get_user_model
from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with ... | Check for a user from previously in the pipeline before checking for duplicate user. | Check for a user from previously in the pipeline before checking for duplicate user.
| Python | mit | chicagopython/chipy.org,tanyaschlusser/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,brianray/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,bharathelangovan/chipy.org,brianray/chipy.org,agfor/chipy.org,bharathelangovan/chipy.or... | ---
+++
@@ -7,7 +7,7 @@
def associate_by_email(*args, **kwargs):
"""Check if a user with this email already exists. If they do, don't create an account."""
backend = kwargs['backend']
- if backend.name in ['google-oauth2', 'github']:
+ if backend.name in ['google-oauth2', 'github'] or kwargs.get('use... |
62a04170e41d599d653e94afe0844576e175c314 | settings_example.py | settings_example.py | import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
CSV_FOLDER = os.getcwd()
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''... | import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by su... | Add comments on variable settings | Add comments on variable settings
| Python | mit | AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files | ---
+++
@@ -7,6 +7,7 @@
CSV_FOLDER = os.getcwd()
+# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
@@ -31,6 +32,7 @@
time: %(asctime)s
'''.strip()
+# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{mon... |
0cf45657c01349b6304470e0ee7349e9f62874f5 | lbrynet/__init__.py | lbrynet/__init__.py | import logging
__version__ = "0.19.0rc3"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
| import logging
__version__ = "0.19.0rc4"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
| Bump version 0.19.0rc3 --> 0.19.0rc4 | Bump version 0.19.0rc3 --> 0.19.0rc4
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>
| Python | mit | lbryio/lbry,lbryio/lbry,lbryio/lbry | ---
+++
@@ -1,6 +1,6 @@
import logging
-__version__ = "0.19.0rc3"
+__version__ = "0.19.0rc4"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler()) |
d03b385b5d23c321ee1d4bd2020be1452e8c1cab | pika/__init__.py | pika/__init__.py | # ***** BEGIN LICENSE BLOCK *****
#
# For copyright and licensing please refer to COPYING.
#
# ***** END LICENSE BLOCK *****
__version__ = '0.9.13p1'
from pika.connection import ConnectionParameters
from pika.connection import URLParameters
from pika.credentials import PlainCredentials
from pika.spec import BasicPrope... | # ***** BEGIN LICENSE BLOCK *****
#
# For copyright and licensing please refer to COPYING.
#
# ***** END LICENSE BLOCK *****
__version__ = '0.9.13p2'
from pika.connection import ConnectionParameters
from pika.connection import URLParameters
from pika.credentials import PlainCredentials
from pika.spec import BasicPrope... | Remove Python 2.4 support monkey patch and bump rev | Remove Python 2.4 support monkey patch and bump rev
| Python | bsd-3-clause | reddec/pika,skftn/pika,Tarsbot/pika,shinji-s/pika,jstnlef/pika,zixiliuyue/pika,fkarb/pika-python3,renshawbay/pika-python3,vrtsystems/pika,Zephor5/pika,pika/pika,vitaly-krugl/pika,knowsis/pika,hugoxia/pika,benjamin9999/pika | ---
+++
@@ -3,7 +3,7 @@
# For copyright and licensing please refer to COPYING.
#
# ***** END LICENSE BLOCK *****
-__version__ = '0.9.13p1'
+__version__ = '0.9.13p2'
from pika.connection import ConnectionParameters
from pika.connection import URLParameters
@@ -14,13 +14,3 @@
from pika.adapters.asyncore_connect... |
1382fd8afecdeca9bb1b6961a636b6502c16ad6e | log-preprocessor.py | log-preprocessor.py | __author__ = 'shawnmehan'
import csv, os, re
# # first lets open the file, which is tab delimited because of , in description field and others
with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile:
testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M
records = csv.reader(... | __author__ = 'shawnmehan'
import csv, os, re
# # first lets open the file, which is tab delimited because of , in description field and others
with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile:
testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M
records = csv.reader(... | Enumerate much more elegant to loop through list elements and regex each. | Enumerate much more elegant to loop through list elements and regex each.
| Python | apache-2.0 | smehan/App-data-reqs,smehan/App-data-reqs | ---
+++
@@ -10,8 +10,8 @@
testwriter = csv.writer(testfile, delimiter='\t')
count = 0
for row in records:
- for e in row: #TODO still need to remove \n from list elements
- e = re.sub(r'\n','',e)
+ for i, s in enumerate(row):
+ row[i] = re.sub(r'\n+', '', s)
... |
d6c5b9a19921ce2c1e3f2e30d6ce0468a5305e80 | myflaskapp/tests/test_flask_testing.py | myflaskapp/tests/test_flask_testing.py | from flask import Flask
from flask_testing import LiveServerTestCase
from myflaskapp.app import create_app
from myflaskapp.settings import DevConfig, ProdConfig
import requests
class MyTest(LiveServerTestCase):
def create_app(self):
app = create_app(DevConfig)
app.config['TESTING'] = True
... | from flask import Flask
from flask_testing import LiveServerTestCase
from myflaskapp.app import create_app
from myflaskapp.settings import DevConfig, ProdConfig
import requests
import datetime as dt
import pytest
from myflaskapp.user.models import Role, User
from myflaskapp.item.models import Item
from .factories impor... | Test with Flask-Testing to test POST request | Test with Flask-Testing to test POST request
| Python | mit | terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python | ---
+++
@@ -3,6 +3,14 @@
from myflaskapp.app import create_app
from myflaskapp.settings import DevConfig, ProdConfig
import requests
+import datetime as dt
+import pytest
+from myflaskapp.user.models import Role, User
+from myflaskapp.item.models import Item
+from .factories import UserFactory
+import requests
+fr... |
cea891a2de493ce211ccf13f4bf0c487f945985d | test_audio_files.py | test_audio_files.py | import fore.apikeys
import fore.mixer
import fore.database
import pyechonest.track
for file in fore.database.get_many_mp3(status='all'):
print("Name: {} Length: {}".format(file.filename, file.track_details['length']))
track.track_from_filename('audio/'+file.filename, force_upload=True)
| import fore.apikeys
import fore.mixer
import fore.database
import pyechonest.track
for file in fore.database.get_many_mp3(status='all'):
print("Name: {} Length: {}".format(file.filename, file.track_details['length']))
track = track.track_from_filename('audio/'+file.filename, force_upload=True)
print(track.id)
| Print out the new track id. | Print out the new track id.
| Python | artistic-2.0 | Rosuav/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension | ---
+++
@@ -5,5 +5,6 @@
for file in fore.database.get_many_mp3(status='all'):
print("Name: {} Length: {}".format(file.filename, file.track_details['length']))
- track.track_from_filename('audio/'+file.filename, force_upload=True)
+ track = track.track_from_filename('audio/'+file.filename, force_upload=True)
+ pr... |
550b48c0d1b464a782d875e30da140c742cd4b3e | tests/test_bayes.py | tests/test_bayes.py | from unittest import TestCase
from itertools import repeat, imap, izip, cycle
from spicedham.bayes import Bayes
from spicedham import Spicedham
class TestBayes(TestCase):
def test_classify(self):
sh = Spicedham()
b = Bayes(sh.config, sh.backend)
b.backend.reset()
self._traini... | from unittest import TestCase
from itertools import repeat, imap, izip, cycle
from spicedham.bayes import Bayes
from spicedham import Spicedham
class TestBayes(TestCase):
def test_classify(self):
sh = Spicedham()
b = Bayes(sh.config, sh.backend)
b.backend.reset()
self._traini... | Replace assertGreaterEqual with assertTrue(a >= b) | Replace assertGreaterEqual with assertTrue(a >= b)
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham | ---
+++
@@ -33,4 +33,4 @@
for letter in alphabet:
result = sh.backend.get_key(b.__class__.__name__, letter)
self.assertEqual(result, {'numTotal': 2, 'numSpam': 1})
- self.assertGreaterEqual(result['numTotal'], result['numSpam'])
+ self.assertTrue(result['numTot... |
2fdf35f8a9bf7a6249bc92236952655314a47080 | swapify/__init__.py | swapify/__init__.py | # -*- encoding: utf-8 -*-
__version__ = VERSION = '0.0.0' | # -*- encoding: utf-8 -*-
__author__ = 'Sebastian Vetter'
__version__ = VERSION = '0.0.0'
__license__ = 'MIT'
| Add author and lincense variables | Add author and lincense variables
| Python | mit | elbaschid/swapify | ---
+++
@@ -1,3 +1,5 @@
# -*- encoding: utf-8 -*-
+__author__ = 'Sebastian Vetter'
__version__ = VERSION = '0.0.0'
+__license__ = 'MIT' |
40897be402bd05ed5fb53e116f03d2d954720245 | astrobin_apps_platesolving/utils.py | astrobin_apps_platesolving/utils.py | # Python
import urllib2
# Django
from django.conf import settings
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
def getFromStorage(image, alias):
url = image.thumbnail(alias)
if "://" in url:
url = url.split('://')[1]
else:
url = settings.BASE_UR... | # Python
import urllib2
# Django
from django.conf import settings
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
def getFromStorage(image, alias):
def encoded(path):
return urllib2.quote(path.encode('utf-8'))
url = image.thumbnail(alias)
if "://" in url... | Fix plate-solving on local development mode | Fix plate-solving on local development mode
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | ---
+++
@@ -8,13 +8,19 @@
def getFromStorage(image, alias):
+ def encoded(path):
+ return urllib2.quote(path.encode('utf-8'))
+
url = image.thumbnail(alias)
+
if "://" in url:
- url = url.split('://')[1]
+ # We are getting the full path and must only encode the part after the pr... |
11b35c79ff8d2108d572929334e4e3f30c70eea5 | modules/__init__.py | modules/__init__.py | import argparse
import botconfig
from settings import wolfgame as var
# Todo: Allow game modes to be set via config
# Carry over settings from botconfig into settings/wolfgame.py
for setting, value in botconfig.__dict__.items():
if not setting.isupper():
continue # Not a setting
if not setting in var... | import argparse
import botconfig
from settings import wolfgame as var
# Todo: Allow game modes to be set via config
# Handle launch parameters
# Argument --debug means start in debug mode
# --verbose means to print a lot of stuff (when not in debug mode)
parser = argparse.ArgumentParser()
parser.add_argume... | Allow debug and verbose modes to be set directly from config. | Allow debug and verbose modes to be set directly from config.
| Python | bsd-2-clause | Agent-Isai/lykos,billion57/lykos,Diitto/lykos,Cr0wb4r/lykos | ---
+++
@@ -3,17 +3,6 @@
from settings import wolfgame as var
# Todo: Allow game modes to be set via config
-
-# Carry over settings from botconfig into settings/wolfgame.py
-
-for setting, value in botconfig.__dict__.items():
- if not setting.isupper():
- continue # Not a setting
- if not setting in... |
8fe8717b4e2afe6329d2dd25210371df3eab2b4f | test/test_stdlib.py | test/test_stdlib.py | # -*- coding: utf-8 -*-
"""
Tests for the standard library PEP 543 shim.
"""
import pep543.stdlib
from .backend_tests import SimpleNegotiation
class TestSimpleNegotiationStdlib(SimpleNegotiation):
BACKEND = pep543.stdlib.STDLIB_BACKEND
| # -*- coding: utf-8 -*-
"""
Tests for the standard library PEP 543 shim.
"""
import pep543
import pep543.stdlib
import pytest
from .backend_tests import SimpleNegotiation
CONTEXTS = (
pep543.stdlib.STDLIB_BACKEND.client_context,
pep543.stdlib.STDLIB_BACKEND.server_context
)
def assert_wrap_fails(context,... | Test that we reject bad TLS versions | Test that we reject bad TLS versions
| Python | mit | python-hyper/pep543 | ---
+++
@@ -2,10 +2,57 @@
"""
Tests for the standard library PEP 543 shim.
"""
+import pep543
import pep543.stdlib
+
+import pytest
from .backend_tests import SimpleNegotiation
+CONTEXTS = (
+ pep543.stdlib.STDLIB_BACKEND.client_context,
+ pep543.stdlib.STDLIB_BACKEND.server_context
+ )
+
+
+def asse... |
04608636f6e4fc004458560499338af4b871cddb | asyncio_irc/message.py | asyncio_irc/message.py | from .utils import to_bytes
class Message:
"""A message recieved from the IRC network."""
def __init__(self, raw_message):
self.raw = raw_message
self.prefix, self.command, self.params, self.suffix = self._elements()
def _elements(self):
"""
Split the raw message into it'... | from .utils import to_bytes
class Message(bytes):
"""A message recieved from the IRC network."""
def __init__(self, raw_message_bytes_ignored):
super().__init__()
self.prefix, self.command, self.params, self.suffix = self._elements()
def _elements(self):
"""
Split the raw... | Make Message a subclass of bytes | Make Message a subclass of bytes
| Python | bsd-2-clause | meshy/framewirc | ---
+++
@@ -1,11 +1,11 @@
from .utils import to_bytes
-class Message:
+class Message(bytes):
"""A message recieved from the IRC network."""
- def __init__(self, raw_message):
- self.raw = raw_message
+ def __init__(self, raw_message_bytes_ignored):
+ super().__init__()
self.pr... |
729a5c2e1276f9789733fc46fb7f48d0ac7e3178 | src/slackmoji.py | src/slackmoji.py | # pylint: disable = C0103, C0111
# Standard Library
import json
import mimetypes
from os import makedirs
from subprocess import check_output
# Third Party
import requests
def list_emojis(domain, token):
script = ['bin/list_emojis.sh {0} {1}'.format(domain, token)]
response = check_output(script, shell=True)
... | # pylint: disable = C0103, C0111
# Standard Library
import json
import mimetypes
from os import makedirs
# Third Party
import requests
def list_emojis(domain, token):
url = r'https://%s.slack.com/api/emoji.list' % domain
data = [('token', token)]
response = requests.post(url, data=data)
print "\nGot ... | Use requests to fetch emoji list | Use requests to fetch emoji list
| Python | mit | le1ia/slackmoji | ---
+++
@@ -4,22 +4,22 @@
import json
import mimetypes
from os import makedirs
-from subprocess import check_output
# Third Party
import requests
def list_emojis(domain, token):
- script = ['bin/list_emojis.sh {0} {1}'.format(domain, token)]
- response = check_output(script, shell=True)
+ url = r'h... |
48b7880fec255c7a021361211e56980be2bd4c6b | project/creditor/management/commands/addrecurring.py | project/creditor/management/commands/addrecurring.py | # -*- coding: utf-8 -*-
from creditor.models import RecurringTransaction
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Gets all RecurringTransactions and runs conditional_add_transaction()'
def handle(self, *args, **options):
for t in RecurringT... | # -*- coding: utf-8 -*-
import datetime
import itertools
import dateutil.parser
from creditor.models import RecurringTransaction
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from asylum.utils import datetime_proxy, months
class Command(BaseCommand):
help = ... | Add "since" parameter to this command | Add "since" parameter to this command
Fixes #25
| Python | mit | HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum | ---
+++
@@ -1,14 +1,33 @@
# -*- coding: utf-8 -*-
+import datetime
+import itertools
+
+import dateutil.parser
from creditor.models import RecurringTransaction
from django.core.management.base import BaseCommand, CommandError
+from django.utils import timezone
+
+from asylum.utils import datetime_proxy, months
... |
09bdc51dacfe72597105c468baf356f0b1e81012 | tests/testLabels.py | tests/testLabels.py | import json
import sys
sys.path.append('..')
from skytap.Labels import Labels # noqa
labels = Labels()
def test_labels():
"""Peform tests relating to labels."""
sys.exit()
#labels.create("barf", True)
for l in labels:
print l
| import json
import sys
sys.path.append('..')
from skytap.Labels import Labels # noqa
labels = Labels()
def test_labels():
"""Peform tests relating to labels."""
return
#labels.create("barf", True)
for l in labels:
print l
| Test modified a second time, to keep Travis happy. | Test modified a second time, to keep Travis happy.
| Python | mit | FulcrumIT/skytap,mapledyne/skytap | ---
+++
@@ -9,7 +9,7 @@
def test_labels():
"""Peform tests relating to labels."""
- sys.exit()
+ return
#labels.create("barf", True)
|
0f6128c3694b08899220a3e2b8d73c27cda7eeee | saleor/product/migrations/0117_auto_20200423_0737.py | saleor/product/migrations/0117_auto_20200423_0737.py | # Generated by Django 3.0.5 on 2020-04-23 12:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0116_auto_20200225_0237'),
]
operations = [
migrations.AlterField(
model_name='producttranslation',
name=... | # Generated by Django 3.0.5 on 2020-04-23 12:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("product", "0116_auto_20200225_0237"),
]
operations = [
migrations.AlterField(
model_name="producttranslation",
name=... | Format new migration file with black | Format new migration file with black
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -6,13 +6,13 @@
class Migration(migrations.Migration):
dependencies = [
- ('product', '0116_auto_20200225_0237'),
+ ("product", "0116_auto_20200225_0237"),
]
operations = [
migrations.AlterField(
- model_name='producttranslation',
- name='name... |
42c667ab7e1ed9cdfc711a4d5eb815492d8b1e05 | tests/test_image.py | tests/test_image.py | # -*- coding:utf-8 -*-
import os
from sigal.image import generate_image, generate_thumbnail
CURRENT_DIR = os.path.dirname(__file__)
TEST_IMAGE = 'exo20101028-b-full.jpg'
def test_image(tmpdir):
"Test the Image class."
srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE)
dstfile = str(tmpd... | # -*- coding:utf-8 -*-
import os
from sigal.image import generate_image, generate_thumbnail
CURRENT_DIR = os.path.dirname(__file__)
TEST_IMAGE = 'exo20101028-b-full.jpg'
def test_image(tmpdir):
"Test the Image class."
srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE)
dstfile = str(tmpd... | Fix a test with generate_thumbnail | Fix a test with generate_thumbnail
| Python | mit | franek/sigal,jdn06/sigal,cbosdo/sigal,jasuarez/sigal,muggenhor/sigal,jdn06/sigal,kontza/sigal,franek/sigal,t-animal/sigal,t-animal/sigal,kontza/sigal,kontza/sigal,muggenhor/sigal,elaOnMars/sigal,cbosdo/sigal,jasuarez/sigal,jdn06/sigal,Ferada/sigal,saimn/sigal,saimn/sigal,cbosdo/sigal,saimn/sigal,xouillet/sigal,elaOnMar... | ---
+++
@@ -14,5 +14,5 @@
srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE)
dstfile = str(tmpdir.join(TEST_IMAGE))
- generate_thumbnail(srcfile, dstfile, (200, 150))
+ generate_thumbnail(srcfile, dstfile, (200, 150), None)
assert os.path.isfile(dstfile) |
ccfe12391050d598ec32861ed146b66f4e907943 | noodles/entities.py | noodles/entities.py | """
Find all company names in a piece of text
extractor = EntityExtractor()
entities = extractor.entities_from_text(text)
> ['acme incorporated', 'fubar limited', ...]
TODO:
- work out a standard form to normalize company names to
- import company names into the massive regex
"""
import re
norm_reqs = (
('lt... | """
Find all company names in a piece of text
extractor = EntityExtractor()
entities = extractor.entities_from_text(text)
> ['acme incorporated', 'fubar limited', ...]
"""
COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv'
import re
import csv
norm_reqs = (
('ltd.', 'limited'),
(' bv ', 'b.v.'),
)
def norm... | Use big company list for regex entity extraction | Use big company list for regex entity extraction
| Python | mit | uf6/noodles,uf6/noodles | ---
+++
@@ -4,14 +4,12 @@
extractor = EntityExtractor()
entities = extractor.entities_from_text(text)
> ['acme incorporated', 'fubar limited', ...]
-
-TODO:
- - work out a standard form to normalize company names to
- - import company names into the massive regex
"""
+COMPANY_SOURCE_FILE = '/tmp/companies_dev.c... |
93e2ff0dd32a72efa90222988d4289c70bb55b98 | c2corg_api/models/common/fields_book.py | c2corg_api/models/common/fields_book.py | DEFAULT_FIELDS = [
'locales.title',
'locales.summary',
'locales.description',
'locales.lang',
'author',
'editor',
'activities',
'url',
'isbn',
'book_types',
'publication_date',
'langs',
'nb_pages'
]
DEFAULT_REQUIRED = [
'locales',
'locales.title',
'book_t... | DEFAULT_FIELDS = [
'locales.title',
'locales.summary',
'locales.description',
'locales.lang',
'author',
'editor',
'activities',
'url',
'isbn',
'book_types',
'publication_date',
'langs',
'nb_pages'
]
DEFAULT_REQUIRED = [
'locales',
'locales.title',
'book_t... | Add summary to book listing | Add summary to book listing
| Python | agpl-3.0 | c2corg/v6_api,c2corg/v6_api,c2corg/v6_api | ---
+++
@@ -23,6 +23,7 @@
LISTING_FIELDS = [
'locales',
'locales.title',
+ 'locales.summary',
'activities',
'author',
'quality', |
4008824b7b7bf8338b057bc0b594774cb055c794 | blinkylib/patterns/blinkypattern.py | blinkylib/patterns/blinkypattern.py | class BlinkyPattern(object):
def __init__(self, blinkytape):
self._blinkytape = blinkytape
self._animated = False
self._timebase_sec = 0.05
@property
def animated(self):
return self._animated
@property
def timebase_sec(self):
return self._timebase_sec
d... | class BlinkyPattern(object):
def __init__(self, blinkytape):
self._blinkytape = blinkytape
self._animated = False
self._timebase_sec = 0.01
@property
def animated(self):
return self._animated
@property
def timebase_sec(self):
return self._timebase_sec
d... | Decrease pattern timebase to 0.01 sec now that slow-mo bug is fixed | Decrease pattern timebase to 0.01 sec now that slow-mo bug is fixed
| Python | mit | jonspeicher/blinkyfun | ---
+++
@@ -2,7 +2,7 @@
def __init__(self, blinkytape):
self._blinkytape = blinkytape
self._animated = False
- self._timebase_sec = 0.05
+ self._timebase_sec = 0.01
@property
def animated(self): |
38845ecae177635b98a2e074355227f0c9f9834d | cartoframes/viz/widgets/__init__.py | cartoframes/viz/widgets/__init__.py | """
Widget functions to generate widgets faster.
"""
from __future__ import absolute_import
from .animation_widget import animation_widget
from .category_widget import category_widget
from .default_widget import default_widget
from .formula_widget import formula_widget
from .histogram_widget import histogram_widget
f... | """
Widget functions to generate widgets faster.
"""
from __future__ import absolute_import
from .animation_widget import animation_widget
from .category_widget import category_widget
from .default_widget import default_widget
from .formula_widget import formula_widget
from .histogram_widget import histogram_widget
f... | Add Widget and WidgetList to namespace | Add Widget and WidgetList to namespace
| Python | bsd-3-clause | CartoDB/cartoframes,CartoDB/cartoframes | ---
+++
@@ -10,6 +10,8 @@
from .formula_widget import formula_widget
from .histogram_widget import histogram_widget
from .time_series_widget import time_series_widget
+from ..widget import Widget
+from ..widget_list import WidgetList
def _inspect(widget):
@@ -19,6 +21,8 @@
__all__ = [
+ 'Widget',
+ 'Wi... |
3640a5b1976ea6c5b21617cda11324d73071fb9f | trimwhitespace.py | trimwhitespace.py | """Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(fi... | """Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(fi... | Fix for whitespace.py so that Windows will save Unix EOLs. | Fix for whitespace.py so that Windows will save Unix EOLs.
| Python | apache-2.0 | GoogleCloudPlatform/datastore-ndb-python,GoogleCloudPlatform/datastore-ndb-python | ---
+++
@@ -10,7 +10,7 @@
trimwhitespace(filepath)
def trimwhitespace(filepath):
- handle = open(filepath, 'r')
+ handle = open(filepath, 'rb')
stripped = ''
flag = False
for line in handle.readlines():
@@ -20,10 +20,13 @@
stripped += stripped_line
handle.close()
if flag:
+ print('F... |
d31d2a73127a79566651e644d105cbe2063a6e2a | webapp/publish.py | webapp/publish.py | from cloudly.pubsub import Pusher
from cloudly.tweets import Tweets
from cloudly.twitterstream import Streamer
from webapp import config
class Publisher(Pusher):
def publish(self, tweets, event):
"""Keep only relevant fields from the given tweets."""
stripped = []
for tweet in tweets:
... | from cloudly.pubsub import Pusher
from cloudly.tweets import Tweets, StreamManager, keep
from webapp import config
pubsub = Pusher.open(config.pubsub_channel)
def processor(tweets):
pubsub.publish(keep(['coordinates'], tweets), "tweets")
return len(tweets)
def start():
streamer = StreamManager('locate... | Fix for the new cloudly APi. | Fix for the new cloudly APi.
| Python | mit | hdemers/webapp-template,hdemers/webapp-template,hdemers/webapp-template | ---
+++
@@ -1,34 +1,18 @@
from cloudly.pubsub import Pusher
-from cloudly.tweets import Tweets
-from cloudly.twitterstream import Streamer
+from cloudly.tweets import Tweets, StreamManager, keep
from webapp import config
-
-class Publisher(Pusher):
- def publish(self, tweets, event):
- """Keep only re... |
4a7b548511fa0651aa0bc526302d13947941dacc | parse_push/views.py | parse_push/views.py | from django.db import IntegrityError
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import DeviceSerializer
class DeviceTokenSetter(APIView):
"""
Set a push token... | from django.db import IntegrityError
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import DeviceSerializer
class DeviceTokenSetter(APIView):
"""
Set a push token... | Return status code 200 when Device instance already exists | Return status code 200 when Device instance already exists
| Python | bsd-3-clause | willandskill/django-parse-push | ---
+++
@@ -21,4 +21,4 @@
serializer.save(user=request.user)
return Response(status=status.HTTP_201_CREATED)
except IntegrityError:
- return Response('Device instance already exists.', status=status.HTTP_409_CONFLICT)
+ return Response('Devi... |
c1f5b9e3bfa96762fdbe9f4ca54b3851b38294da | test/__init__.py | test/__init__.py | import glob, os.path, sys
# Add path to hiredis.so load path
path = glob.glob("build/lib*/hiredis/*.so")[0]
sys.path.insert(0, os.path.dirname(path))
from unittest import *
from . import reader
def tests():
suite = TestSuite()
suite.addTest(makeSuite(reader.ReaderTest))
return suite
| import glob, os.path, sys
version = sys.version.split(" ")[0]
majorminor = version[0:3]
# Add path to hiredis.so load path
path = glob.glob("build/lib*-%s/hiredis/*.so" % majorminor)[0]
sys.path.insert(0, os.path.dirname(path))
from unittest import *
from . import reader
def tests():
suite = TestSuite()
suite.a... | Add versioned path for dynamic library lookup | Add versioned path for dynamic library lookup
| Python | bsd-3-clause | badboy/hiredis-py-win,charsyam/hiredis-py,badboy/hiredis-py-win,redis/hiredis-py,charsyam/hiredis-py,badboy/hiredis-py-win,redis/hiredis-py | ---
+++
@@ -1,7 +1,10 @@
import glob, os.path, sys
+version = sys.version.split(" ")[0]
+majorminor = version[0:3]
+
# Add path to hiredis.so load path
-path = glob.glob("build/lib*/hiredis/*.so")[0]
+path = glob.glob("build/lib*-%s/hiredis/*.so" % majorminor)[0]
sys.path.insert(0, os.path.dirname(path))
from... |
3e30737c98a4a9e890d362ba4cbbb2315163bc29 | cfgov/v1/__init__.py | cfgov/v1/__init__.py | from __future__ import absolute_import # Python 2 only
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from wagtail.wagtailcore.templatetags import wagtailcore_tags
from wagtail.wagtailadmin.templatetags... | from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from wagtail.wagtailcore.templatetags import wagtailcore_tags
from wagtail.wagtailadmin.templatetags import wagtailuserbar
from jinja2 import Environment
fr... | Remove unused Python 2 support | Remove unused Python 2 support
| Python | cc0-1.0 | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh | ---
+++
@@ -1,5 +1,3 @@
-from __future__ import absolute_import # Python 2 only
-
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify |
f20c0b650da2354f3008c7a0933eb32a1409fbf0 | openacademy/model/openacademy_session.py | openacademy/model/openacademy_session.py | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
in... | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
in... | Add domain or and ilike | [REF] openacademy: Add domain or and ilike
| Python | apache-2.0 | KarenKawaii/openacademy-project | ---
+++
@@ -8,7 +8,11 @@
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
- instructor_id = fields.Many2one('res.partner', string="Instructor")
+ instructor_id = fields.Many2one('res.partner', string="Instr... |
410207e4c0a091e7b4eca9cedd08f381095f50a9 | pypeerassets/card_parsers.py | pypeerassets/card_parsers.py | '''parse cards according to deck issue mode'''
from .pautils import exponent_to_amount
def none_parser(cards):
'''parser for NONE [0] issue mode'''
return None
def custom_parser(cards, parser=None):
'''parser for CUSTOM [1] issue mode,
please provide your custom parser as argument'''
if not p... | '''parse cards according to deck issue mode'''
from .pautils import exponent_to_amount
def none_parser(cards):
'''parser for NONE [0] issue mode'''
return None
def custom_parser(cards, parser=None):
'''parser for CUSTOM [1] issue mode,
please provide your custom parser as argument'''
if not p... | Revert "change from string to int" | Revert "change from string to int"
This reverts commit a89f8f251ee95609ec4c1ea412b0aa7ec4603252.
| Python | bsd-3-clause | PeerAssets/pypeerassets | ---
+++
@@ -46,10 +46,10 @@
parsers = {
- 0: none_parser,
- 1: custom_parser,
- 2: once_parser,
- 4: multi_parser,
- 8: mono_parser,
- 16: unflushable_parser
+ 'NONE': none_parser,
+ 'CUSTOM': none_parser,
+ 'ONCE': once_parser,
+ 'MULTI': multi_parser,
+ 'MONO': mono_parser,
+ ... |
8ca30840b5477239625c93f4799f266f0a971e3d | raco/datalog/datalog_test.py | raco/datalog/datalog_test.py | import unittest
import json
import raco.fakedb
from raco import RACompiler
from raco.language import MyriaAlgebra
from myrialang import compile_to_json
class DatalogTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
def execute_query(self, query):
'''Run a te... | import unittest
import json
import raco.fakedb
from raco import RACompiler
from raco.language import MyriaAlgebra
from myrialang import compile_to_json
class DatalogTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
def execute_query(self, query):
'''Run a te... | Add query to json output in json generation test | Add query to json output in json generation test | Python | bsd-3-clause | uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco | ---
+++
@@ -29,7 +29,7 @@
# test whether we can generate json without errors
json_string = json.dumps(compile_to_json(
- "", dlog.logicalplan, dlog.physicalplan))
+ query, dlog.logicalplan, dlog.physicalplan))
assert json_string
op = dlog.physicalplan[0][1... |
b8f33283014854bfa2d92896e2061bf17de00836 | pygypsy/__init__.py | pygypsy/__init__.py | """pygypsy
Based on Hueng et all (2009)
Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system
(GYPSY) for natural and post-harvest stands in Alberta. Forestry Division,
Alberta Sustainable Resource Development, 25.
Important Acronyms:
aw = white aspen
sb = black spruce
sw = white spruce
pl... | """pygypsy
Based on Hueng et all (2009)
Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system
(GYPSY) for natural and post-harvest stands in Alberta. Forestry Division,
Alberta Sustainable Resource Development, 25.
Important Acronyms:
aw = white aspen
sb = black spruce
sw = white spruce
pl... | Revert "Try not importing basal_area_increment to init" | Revert "Try not importing basal_area_increment to init"
This reverts commit 30f9d5367085285a3100d7ec5d6a9e07734c5ccd.
| Python | mit | tesera/pygypsy,tesera/pygypsy | ---
+++
@@ -22,8 +22,13 @@
import matplotlib
from ._version import get_versions
+import pygypsy.basal_area_increment
+
__version__ = get_versions()['version']
del get_versions
# Force matplotlib to not use any Xwindows backend so that headless docker works
matplotlib.use('Agg')
+
+__all__ = ['basal_area_inc... |
72ce164a461987f7b9d35ac9a2b3a36386b7f8c9 | ui/Interactor.py | ui/Interactor.py | """
Interactor
This class can be used to simply managing callback resources.
Callbacks are often used by interactors with vtk and callbacks
are hard to keep track of.
Use multiple inheritance to inherit from this class to get access
to the convenience methods.
Observers for vtk events can be added through
AddObserver... | """
Interactor
This class can be used to simply managing callback resources.
Callbacks are often used by interactors with vtk and callbacks
are hard to keep track of.
Use multiple inheritance to inherit from this class to get access
to the convenience methods.
Observers for vtk events can be added through
AddObserver... | Add possibility of passing priority for adding an observer | Add possibility of passing priority for adding an observer
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop | ---
+++
@@ -24,7 +24,7 @@
def __init__(self):
super(Interactor, self).__init__()
- def AddObserver(self, obj, eventName, callbackFunction):
+ def AddObserver(self, obj, eventName, callbackFunction, priority=None):
"""
Creates a callback and stores the callback so that later
on the callbacks can be pro... |
e85fcd553756eab32cedca214c9b8b86ff48f8b8 | app/forms/vacancy.py | app/forms/vacancy.py | from flask_wtf import Form
from flask_babel import lazy_gettext as _ # noqa
from wtforms import StringField, SubmitField, TextAreaField, \
DateField, SelectField
from wtforms.validators import InputRequired
class VacancyForm(Form):
title = StringField(_('Title'), validators=[InputRequired(
message=_(... | from flask_wtf import Form
from flask_babel import lazy_gettext as _ # noqa
from wtforms import StringField, SubmitField, TextAreaField, \
DateField, SelectField
from wtforms.validators import InputRequired
class VacancyForm(Form):
title = StringField(_('Title'), validators=[InputRequired(
message=_(... | Make workload optional when editing vacancies | Make workload optional when editing vacancies
| Python | mit | viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct | ---
+++
@@ -19,7 +19,6 @@
('deeltijd', _('Deeltijd')),
('bijbaan', _('Bijbaan')),
('stage', _('Stage'))])
- workload = StringField(_('Workload'), validators=[InputRequired... |
2627c2c5ea6fdbff9d9979765deee8740a11c7c9 | backend/globaleaks/handlers/__init__.py | backend/globaleaks/handlers/__init__.py | # -*- encoding: utf-8 -*-
#
# In here you will find all the handlers that are tasked with handling the
# requests specified in the API.
#
# From these handlers we will be instantiating models objects that will take care
# of our business logic and the generation of the output to be sent to GLClient.
#
# In here we are ... | # -*- encoding: utf-8 -*-
#
# In here you will find all the handlers that are tasked with handling the
# requests specified in the API.
#
# From these handlers we will be instantiating models objects that will take care
# of our business logic and the generation of the output to be sent to GLClient.
#
# In here we are ... | Fix module packaging thanks to landscape.io hint | Fix module packaging thanks to landscape.io hint
| Python | agpl-3.0 | vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks | ---
+++
@@ -15,7 +15,6 @@
__all__ = ['admin',
'base',
- 'css',
'files',
'node',
'receiver', |
6728bf1fecef3ac1aea9489e7c74333ad0a3b552 | datalogger/__main__.py | datalogger/__main__.py | import sys
from PyQt5.QtWidgets import QApplication
from datalogger.bin.workspace import Workspace
from datalogger.analysis_window_testing import AnalysisWindow
def full():
app = 0
app = QApplication(sys.argv)
# Create the window
w = AnalysisWindow()
w.CurrentWorkspace = Workspace()
# Load ... | import sys
from PyQt5.QtWidgets import QApplication
from datalogger.bin.workspace import Workspace
from datalogger.analysis_window_testing import AnalysisWindow
def full():
app = 0
app = QApplication(sys.argv)
# Create the window
w = AnalysisWindow()
w.CurrentWorkspace = Workspace()
#w.Curr... | Comment out audo-discovery of addons | Comment out audo-discovery of addons
| Python | bsd-3-clause | torebutlin/cued_datalogger | ---
+++
@@ -13,10 +13,11 @@
w = AnalysisWindow()
w.CurrentWorkspace = Workspace()
+ #w.CurrentWorkspace.path = "//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/"
# Load the workspace
#CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/... |
a5faeb16a599b4260f32741846607dd05f10bc53 | myproject/myproject/project_settings.py | myproject/myproject/project_settings.py | # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDUL... | # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDUL... | Add ability to specify which settings are used via `export PRODUCTION=0' | Add ability to specify which settings are used via `export PRODUCTION=0'
| Python | unlicense | django-settings/django-settings | ---
+++
@@ -12,9 +12,12 @@
#CELERYD_PREFETCH_MULTIPLIER = 1
+import os
import sys
-if 'runserver' in sys.argv:
+if 'PRODUCTION' in os.environ and os.environ['PRODUCTION'].lower() in [True, 'y', 'yes', '1',]:
+ from production_settings import *
+elif 'runserver' in sys.argv:
from local_settings import ... |
794596fd6f55806eecca1c54e155533590108eee | openspending/lib/unicode_dict_reader.py | openspending/lib/unicode_dict_reader.py | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
import csv
class EmptyCSVError(Exception):
pass
class UnicodeDictReader(object):
def __init__(self, file_or_str, encoding='utf8', **... | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
import csv
class EmptyCSVError(Exception):
pass
class UnicodeDictReader(object):
def __init__(self, fp, encoding='utf8', **kwargs):
... | Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader | Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader
| Python | agpl-3.0 | CivicVision/datahub,nathanhilbert/FPA_Core,USStateDept/FPA_Core,johnjohndoe/spendb,openspending/spendb,spendb/spendb,CivicVision/datahub,pudo/spendb,CivicVision/datahub,nathanhilbert/FPA_Core,pudo/spendb,openspending/spendb,johnjohndoe/spendb,spendb/spendb,nathanhilbert/FPA_Core,openspending/spendb,johnjohndoe/spendb,s... | ---
+++
@@ -8,9 +8,9 @@
class UnicodeDictReader(object):
- def __init__(self, file_or_str, encoding='utf8', **kwargs):
+ def __init__(self, fp, encoding='utf8', **kwargs):
self.encoding = encoding
- self.reader = csv.DictReader(file_or_str, **kwargs)
+ self.reader = csv.DictReader(fp... |
207d4c71fbc40dd30c0099769d6f12fcb63f826e | tests/test_utils.py | tests/test_utils.py | import subprocess
from pytest import mark
from pytest_benchmark.utils import clonefunc, get_commit_info
f1 = lambda a: a
def f2(a):
return a
@mark.parametrize('f', [f1, f2])
def test_clonefunc(f):
assert clonefunc(f)(1) == f(1)
assert clonefunc(f)(1) == f(1)
def test_clonefunc_not_function():
ass... | import subprocess
from pytest import mark
from pytest_benchmark.utils import clonefunc, get_commit_info
pytest_plugins = 'pytester',
f1 = lambda a: a
def f2(a):
return a
@mark.parametrize('f', [f1, f2])
def test_clonefunc(f):
assert clonefunc(f)(1) == f(1)
assert clonefunc(f)(1) == f(1)
def test_clo... | Add missing username conf for mercurial. | Add missing username conf for mercurial.
| Python | bsd-2-clause | thedrow/pytest-benchmark,SectorLabs/pytest-benchmark,ionelmc/pytest-benchmark,aldanor/pytest-benchmark | ---
+++
@@ -1,6 +1,8 @@
import subprocess
from pytest import mark
from pytest_benchmark.utils import clonefunc, get_commit_info
+
+pytest_plugins = 'pytester',
f1 = lambda a: a
@@ -25,6 +27,12 @@
if scm == 'git':
subprocess.check_call('git config user.email you@example.com'.split())
sub... |
967cf8774a5033f310ca69e7ad86fc79b2628882 | infrastructure/aws/trigger-provision.py | infrastructure/aws/trigger-provision.py | # trigger-provision.py <indexer-provision.sh | web-server-provision.sh>
import boto3
from datetime import datetime, timedelta
import sys
import os.path
provisioners = sys.argv[1:]
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
script = ''
for provisioner in provisioners:
script += open(provisioner).re... | # trigger-provision.py <indexer-provision.sh | web-server-provision.sh>
import boto3
from datetime import datetime, timedelta
import sys
import os.path
provisioners = sys.argv[1:]
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
script = ''
for provisioner in provisioners:
script += open(provisioner).re... | Tag provisioning instances to make them easier to identify | Tag provisioning instances to make them easier to identify
| Python | mpl-2.0 | bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox | ---
+++
@@ -33,7 +33,14 @@
'SecurityGroups': ['indexer'],
'UserData': user_data,
'InstanceType': 'c3.2xlarge',
- 'BlockDeviceMappings': []
+ 'BlockDeviceMappings': [],
+ 'TagSpecifications': [{
+ 'ResourceType': 'instance',
+ 'Tags': [{
+ 'Key': 'provisioner',
+ ... |
2f31af1ea22e0bfefe2042f8d2ba5ad6ce365116 | RG/drivers/s3/secrets.py | RG/drivers/s3/secrets.py | #!/usr/bin/python
SECRETS = {
"AWS_ACCESS_KEY_ID": "AKIAI2TRFQV2HZIHUD4A",
"AWS_SECRET_ACCESS_KEY": "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"
}
| #!/usr/bin/python
SECRETS = {
"AWS_ACCESS_KEY_ID": "XXX",
"AWS_SECRET_ACCESS_KEY": "XXX"
}
| Clear S3 API key from code | Clear S3 API key from code
| Python | apache-2.0 | jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate | ---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/python
SECRETS = {
- "AWS_ACCESS_KEY_ID": "AKIAI2TRFQV2HZIHUD4A",
- "AWS_SECRET_ACCESS_KEY": "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"
+ "AWS_ACCESS_KEY_ID": "XXX",
+ "AWS_SECRET_ACCESS_KEY": "XXX"
}
|
f63a174dd35731b6737e4f653139d92bd2f57aef | lab/hookspec.py | lab/hookspec.py | import pytest
@pytest.hookspec
def pytest_lab_configure(envmanager):
"""pytestlab startup"""
@pytest.hookspec(historic=True)
def pytest_lab_addroles(config, rolemanager):
"""new role registered"""
# TODO: Hook for publishing new role **should not** be historic - this
# no longer makes sense. Roles can now... | import pytest
@pytest.hookspec
def pytest_lab_configure(envmanager):
"""pytestlab startup"""
@pytest.hookspec(historic=True)
def pytest_lab_addroles(config, rolemanager):
"""new role registered"""
# TODO: Hook for publishing new role **should not** be historic - this
# no longer makes sense. Roles can now... | Add a location destroyed hook | Add a location destroyed hook
| Python | mpl-2.0 | sangoma/pytestlab | ---
+++
@@ -30,6 +30,12 @@
@pytest.hookspec
+def pytest_lab_location_destroyed(config, location):
+ """Called when a location is released by the environment manager.
+ """
+
+
+@pytest.hookspec
def pytest_lab_add_providers(config, providermanager):
"""Called to enable adding addtional/external enviro... |
fbe7b34c575e30114c54587952c9aa919bc28d81 | south/introspection_plugins/__init__.py | south/introspection_plugins/__init__.py | # This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_o... | # This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_o... | Add import of django-annoying patch | Add import of django-annoying patch
| Python | apache-2.0 | theatlantic/django-south,theatlantic/django-south | ---
+++
@@ -6,4 +6,5 @@
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_objectpermissions
+import south.introspection_plugins.annoying_autoonetoone
|
0d8585a2ab57ca4d8f3f4ee2429a2137f2045c6a | bumblebee/modules/arch-update.py | bumblebee/modules/arch-update.py | """Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine,... | """Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine,... | Return 0 as an int rather than a string. | Return 0 as an int rather than a string.
This was causing an ocassional crash in bumblebee/engine.py threshold_state
when checkupdates fails, perhaps due to wifi not being up yet.
For me this showed up regularly on login.
| Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | ---
+++
@@ -27,7 +27,7 @@
packages.pop()
return len(packages)
- return '0'
+ return 0
def utilization(self, widget):
return 'Update Arch: {}'.format(self.packages) |
21b405f1968dd75a663b253feb19d730af34d380 | docker-entrypoint.py | docker-entrypoint.py | #!/usr/bin/env python3
# Single entry point / dispatcher for simplified running of 'pman'
import os
from argparse import RawTextHelpFormatter
from argparse import ArgumentParser
str_desc = """
NAME
docker-entrypoint.py
SYNOPSIS
docker-entrypoint.py [optional cmd args for... | #!/usr/bin/env python3
# Single entry point / dispatcher for simplified running of 'pman'
import os
from argparse import RawTextHelpFormatter
from argparse import ArgumentParser
str_desc = """
NAME
docker-entrypoint.py
SYNOPSIS
docker-entrypoint.py [optional cmd args for... | Revert to old entry point. | Revert to old entry point.
| Python | mit | danmcp/pman,FNNDSC/pman,danmcp/pman,FNNDSC/pman | ---
+++
@@ -29,7 +29,7 @@
str_otherArgs = ' '.join(unknown)
str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs)
- str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs)
+ # str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs)
return str_CMD
parser = ArgumentParser(description = s... |
9ff63d002293da44871307960d5b439b5e6ba48f | app/commands/help.py | app/commands/help.py | def proc(command, message):
return {
"data": {
"status": "ok",
"html": """
<p>
Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br>
📷 camera controls<br>
... | def proc(command, message):
return {
"data": {
"status": "ok",
"html": """
<p>
Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br>
📷 camera controls<br>
... | Remove 'lights' command for a while | Remove 'lights' command for a while
| Python | mit | alwye/spark-pi,alwye/spark-pi | ---
+++
@@ -9,10 +9,6 @@
📷 camera controls<br>
<b>camera photo</b>: I will take a photo and send it back<br>
- 💡 light controls<br>
- <b>lights on <i>color</i></b>: I will shine with the specified <i>color</i> (red, gree... |
0a6b43f2202cb63aad18c119d7d46916b4d54873 | examples/site-api.py | examples/site-api.py | #!/usr/bin/env python
# Sets up a basic site that can allow two browsers to connect to each
# other via WebRTC DataChannels, sending connection events via WebSockets.
from flask import Flask, send_from_directory
from flask_sockets import Sockets
import json
app = Flask(__name__)
sockets = Sockets(app)
channels = {}... | #!/usr/bin/env python
# Sets up a basic site that can allow two browsers to connect to each
# other via WebRTC DataChannels, sending connection events via WebSockets.
from flask import Flask, send_from_directory
from flask_sockets import Sockets
import json
app = Flask(__name__)
sockets = Sockets(app)
channels = {}... | Make it easier to load the initial page | Make it easier to load the initial page
| Python | bsd-3-clause | chadnickbok/librtcdcpp,chadnickbok/librtcdcpp | ---
+++
@@ -39,7 +39,7 @@
return app.send_from_directory('static', path)
-@app.route('/index.html')
+@app.route('/')
def serve_site():
return app.send_static_file("index.html")
|
dae9d7d67aaf2ab8d39b232d243d860d9597bbd2 | django_excel_tools/exceptions.py | django_excel_tools/exceptions.py | class BaseExcelError(Exception):
def __init__(self, message):
super(BaseExcelError, self).__init__()
self.message = message
class ValidationError(BaseExcelError):
pass
class ColumnNotEqualError(BaseExcelError):
pass
class FieldNotExist(BaseExcelError):
pass
| class BaseExcelError(Exception):
def __init__(self, message):
super(BaseExcelError, self).__init__()
self.message = message
class ValidationError(BaseExcelError):
pass
class ColumnNotEqualError(BaseExcelError):
pass
class FieldNotExist(BaseExcelError):
pass
class SerializerConfi... | Add error when serializer setup has error | Add error when serializer setup has error
| Python | mit | NorakGithub/django-excel-tools | ---
+++
@@ -15,3 +15,7 @@
class FieldNotExist(BaseExcelError):
pass
+
+
+class SerializerConfigError(BaseExcelError):
+ pass |
2e6f0934c67baf27cdf3930d48d6b733995e413f | benchmark/_interfaces.py | benchmark/_interfaces.py | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Interfaces for the benchmarking results server.
"""
from zope.interface import Interface
class IBackend(Interface):
"""
A backend for storing and querying the results.
"""
def store(result):
"""
Store a single benchmarking... | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Interfaces for the benchmarking results server.
"""
from zope.interface import Interface
class IBackend(Interface):
"""
A backend for storing and querying the results.
"""
def store(result):
"""
Store a single benchmarking... | Make the query docstring a bit clearer | Make the query docstring a bit clearer
| Python | apache-2.0 | ClusterHQ/benchmark-server,ClusterHQ/benchmark-server | ---
+++
@@ -36,7 +36,8 @@
filter for the fields that are specified in the filter.
:param dict filter: The filter in the JSON compatible format.
- :param int limit: The number of the *latest* results to return.
+ :param int limit: The number of the results to return. The
+ ... |
b2befc496741a904f8988b2ec8fa5b57aba96a91 | bin/deploy/giles_conf.py | bin/deploy/giles_conf.py | import json
sample_path = "conf/net/int_service/giles_conf.json.sample"
f = open(path, "r")
data = json.loads(f.read())
f.close()
real_path = "conf/net/int_service/giles_conf.json"
data['giles_base_url'] = 'http://50.17.111.19:8079'
f = open(real_path, "w")
f.write(json.dumps(data))
f.close()
| import json
sample_path = "conf/net/int_service/giles_conf.json.sample"
f = open(sample_path, "r")
data = json.loads(f.read())
f.close()
real_path = "conf/net/int_service/giles_conf.json"
data['giles_base_url'] = 'http://50.17.111.19:8079'
f = open(real_path, "w")
f.write(json.dumps(data))
f.close()
| Fix the path to read the sample file from | Fix the path to read the sample file from
Gah! so annoying!
| Python | bsd-3-clause | e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server | ---
+++
@@ -1,7 +1,7 @@
import json
sample_path = "conf/net/int_service/giles_conf.json.sample"
-f = open(path, "r")
+f = open(sample_path, "r")
data = json.loads(f.read())
f.close()
|
0039eefbfa546f24b3f10031e664341d60e4055c | ranger/commands.py | ranger/commands.py | from ranger.api.commands import Command
class fzf_select(Command):
"""
:fzf_select
Find a file using fzf.
With a prefix argument select only directories.
See: https://github.com/junegunn/fzf
"""
def execute(self):
import subprocess
import os.path
if self.quantifie... | from ranger.api.commands import Command
class fzf_select(Command):
"""
:fzf_select
Find a file using fzf.
With a prefix argument select only directories.
See: https://github.com/junegunn/fzf
"""
def execute(self):
import subprocess
import os.path
if self.quantifie... | Use previews in ranger fzf | Use previews in ranger fzf
| Python | mit | darthdeus/dotfiles,darthdeus/dotfiles,darthdeus/dotfiles,darthdeus/dotfiles | ---
+++
@@ -15,12 +15,12 @@
import os.path
if self.quantifier:
# match only directories
- command="fd -t d --hidden | fzf +m"
+ command="fd -t d --hidden | fzf +m --preview 'cat {}'"
# command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'pr... |
f5e8bfaf5c4f7a2131fbe0ffd0f8d14a316b907e | camoco/Exceptions.py | camoco/Exceptions.py | # Exception abstract class
class CamocoError(Exception):
pass
class CamocoExistsError(CamocoError):
'''
You tried to create a camoco object which already exists
under the same name,type combination.
'''
def __init__(self,expr,message='',*args):
self.expr = expr
self.mess... | # Exception abstract class
class CamocoError(Exception):
pass
class CamocoExistsError(CamocoError):
'''
You tried to create a camoco object which already exists
under the same name,type combination.
'''
def __init__(self,expr,message='',*args):
self.expr = expr
self.mess... | Add exception for cli command line to run interactively. | Add exception for cli command line to run interactively.
| Python | mit | schae234/Camoco,schae234/Camoco | ---
+++
@@ -39,3 +39,8 @@
'Operation requiring window, but window is 0:' + \
message.format(args)
)
+
+class CamocoInteractive(CamocoError):
+ def __init__(self,expr=None,message='',*args):
+ self.expr = expr
+ self.message = 'Camoco interactive ipython session.' |
5da928fd9b08aeb0028b71535413159da18393b4 | comics/sets/forms.py | comics/sets/forms.py | import datetime
from django import forms
from django.template.defaultfilters import slugify
from comics.core.models import Comic
from comics.sets.models import Set
class NewSetForm(forms.ModelForm):
class Meta:
model = Set
fields = ('name',)
def save(self, commit=True):
set = super(N... | import datetime
from django import forms
from django.template.defaultfilters import slugify
from comics.core.models import Comic
from comics.sets.models import Set
class NewSetForm(forms.ModelForm):
class Meta:
model = Set
fields = ('name',)
def save(self, commit=True):
set = super(N... | Exclude inactive comics from sets editing, effectively throwing them out of the set when saved | Exclude inactive comics from sets editing, effectively throwing them out of the set when saved
| Python | agpl-3.0 | datagutten/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,datagutten/comics | ---
+++
@@ -22,7 +22,7 @@
class EditSetForm(forms.ModelForm):
comics = forms.ModelMultipleChoiceField(
- Comic.objects.all(),
+ Comic.objects.filter(active=True),
required=False,
widget=forms.CheckboxSelectMultiple)
add_new_comics = forms.BooleanField( |
5425e10a39ce66d3c50e730d1e7b7878e8e88eb0 | dmoj/executors/PHP7.py | dmoj/executors/PHP7.py | from .php_executor import PHPExecutor
from dmoj.judgeenv import env
class Executor(PHPExecutor):
name = 'PHP7'
command = env['runtime'].get('php7')
fs = ['.*\.so', '/etc/localtime$', '.*\.ini$']
initialize = Executor.initialize
| from .php_executor import PHPExecutor
from dmoj.judgeenv import env
class Executor(PHPExecutor):
name = 'PHP7'
command = env['runtime'].get('php7')
fs = ['.*\.so', '/etc/localtime$', '.*\.ini$', '/dev/urandom$']
initialize = Executor.initialize
| Allow /dev/urandom for PHP 7 | Allow /dev/urandom for PHP 7 | Python | agpl-3.0 | DMOJ/judge,DMOJ/judge,DMOJ/judge | ---
+++
@@ -5,7 +5,7 @@
class Executor(PHPExecutor):
name = 'PHP7'
command = env['runtime'].get('php7')
- fs = ['.*\.so', '/etc/localtime$', '.*\.ini$']
+ fs = ['.*\.so', '/etc/localtime$', '.*\.ini$', '/dev/urandom$']
initialize = Executor.initialize |
ec8d7b035617f9239a0a52be346d8611cf77cb6f | integration-tests/features/src/utils.py | integration-tests/features/src/utils.py | """Unsorted utility functions used in integration tests."""
import requests
def download_file_from_url(url):
"""Download file from the given URL and do basic check of response."""
assert url
response = requests.get(url)
assert response.status_code == 200
assert response.text is not None
return... | """Unsorted utility functions used in integration tests."""
import requests
import subprocess
def download_file_from_url(url):
"""Download file from the given URL and do basic check of response."""
assert url
response = requests.get(url)
assert response.status_code == 200
assert response.text is n... | Add few oc wrappers for future resiliency testing | Add few oc wrappers for future resiliency testing
Not used anywhere yet.
| Python | apache-2.0 | jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common | ---
+++
@@ -1,5 +1,6 @@
"""Unsorted utility functions used in integration tests."""
import requests
+import subprocess
def download_file_from_url(url):
@@ -14,3 +15,52 @@
def split_comma_separated_list(l):
"""Split the list into elements separated by commas."""
return [i.strip() for i in l.split(','... |
65266813c6438eeb67002e17dd4cd70a00e84b5d | meta-iotqa/lib/oeqa/runtime/boottime.py | meta-iotqa/lib/oeqa/runtime/boottime.py | #[PROTEXCAT]
#\License: ALL RIGHTS RESERVED
"""System boot time"""
import os
from oeqa.oetest import oeRuntimeTest
from oeqa.runtime.helper import collect_pnp_log
class BootTimeTest(oeRuntimeTest):
def _setup(self):
(status,output) = self.target.copy_to(os.path.join(os.path.dirname(__file__), 'files','sy... | #[PROTEXCAT]
#\License: ALL RIGHTS RESERVED
"""System boot time"""
import os
from oeqa.oetest import oeRuntimeTest
from oeqa.runtime.helper import collect_pnp_log
class BootTimeTest(oeRuntimeTest):
def _setup(self):
(status, output) = self.target.copy_to(
os.path.join(os.path.dirname(__file_... | Clean the code with autopen8 | Clean the code with autopen8
| Python | mit | daweiwu/meta-iotqa-1,ostroproject/meta-iotqa,ostroproject/meta-iotqa,ostroproject/meta-iotqa,daweiwu/meta-iotqa-1,wanghongjuan/meta-iotqa-1,wanghongjuan/meta-iotqa-1,ostroproject/meta-iotqa,daweiwu/meta-iotqa-1,daweiwu/meta-iotqa-1,wanghongjuan/meta-iotqa-1,wanghongjuan/meta-iotqa-1,ostroproject/meta-iotqa,daweiwu/meta... | ---
+++
@@ -6,19 +6,30 @@
from oeqa.oetest import oeRuntimeTest
from oeqa.runtime.helper import collect_pnp_log
+
class BootTimeTest(oeRuntimeTest):
def _setup(self):
- (status,output) = self.target.copy_to(os.path.join(os.path.dirname(__file__), 'files','systemd-analyze'),"/tmp/systemd-analyze")
-... |
860e16f506d0a601540847fe21e617d8f7fbf882 | malware/pickle_tool.py | malware/pickle_tool.py | import os
import cPickle as pickle
import simplejson as json
def update_pickle(new_cache):
# print('Updated pickle')
pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2)
def check_pickle():
# print('Checking in pickle')
if not os.path.isfile('url_cache.pkl'):
malicious_url = {}
pic... | import os
import cPickle as pickle
import simplejson as json
def update_pickle(new_cache):
# print('Updated pickle')
pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2)
def check_pickle():
# print('Checking in pickle')
if not os.path.isfile('url_cache.pkl'):
malicious_url = {}
pic... | Add pickle convert to json method | Add pickle convert to json method
| Python | apache-2.0 | John-Lin/malware,John-Lin/malware | ---
+++
@@ -36,3 +36,12 @@
# cache = json.load(fp)
cache = json.load(fp, "ISO-8859-1")
return cache
+
+
+def pickle2json(pkl):
+ if os.path.isfile(pkl):
+ cache = pickle.load(open(pkl, 'rb'))
+ with open('pkl2json.json', 'wb') as fp:
+ json.dump(cache, fp)
+ else:... |
45c4c1f627f224f36c24acebbec43a17a5c59fcb | nib/plugins/lesscss.py | nib/plugins/lesscss.py | from __future__ import absolute_import, division, print_function, unicode_literals
from os import path
import sh
from nib import Processor, resource
@resource('.less')
class LessCSSProcessor(Processor):
def resource(self, resource):
filepath = path.join(self.options['resource_path'],
... | from __future__ import absolute_import, division, print_function, unicode_literals
from os import path
import sh
from nib import Processor, resource
@resource('.less')
class LessCSSProcessor(Processor):
def resource(self, resource):
filepath = path.join(self.options['resource_path'],
... | Print out file being processed, need to do to other modules, add -v flag | Print out file being processed, need to do to other modules, add -v flag
| Python | mit | jreese/nib | ---
+++
@@ -9,6 +9,7 @@
def resource(self, resource):
filepath = path.join(self.options['resource_path'],
resource.path + resource.extension)
+ print("Processing: ", filepath)
resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8')
resource.e... |
3266ecee8f9a6601d8678a91e8923c6d7137adb3 | oggm/tests/conftest.py | oggm/tests/conftest.py | import pytest
import logging
import multiprocessing as mp
from oggm import cfg, utils
import pickle
logger = logging.getLogger(__name__)
def pytest_configure(config):
if config.pluginmanager.hasplugin('xdist'):
try:
from ilock import ILock
utils.lock = ILock("oggm_xdist_download_lo... | import pytest
import logging
import getpass
from oggm import cfg, utils
logger = logging.getLogger(__name__)
def pytest_configure(config):
if config.pluginmanager.hasplugin('xdist'):
try:
from ilock import ILock
utils.lock = ILock("oggm_xdist_download_lock_" + getpass.getuser())
... | Make ilock lock name user specific | Make ilock lock name user specific
| Python | bsd-3-clause | OGGM/oggm,OGGM/oggm,bearecinos/oggm,bearecinos/oggm,juliaeis/oggm,TimoRoth/oggm,anoukvlug/oggm,TimoRoth/oggm,juliaeis/oggm,anoukvlug/oggm | ---
+++
@@ -1,8 +1,7 @@
import pytest
import logging
-import multiprocessing as mp
+import getpass
from oggm import cfg, utils
-import pickle
logger = logging.getLogger(__name__)
@@ -10,7 +9,7 @@
if config.pluginmanager.hasplugin('xdist'):
try:
from ilock import ILock
- u... |
102f7979338b948744b6af06689f928deb72f27c | spacy/tests/regression/test_issue781.py | spacy/tests/regression/test_issue781.py | # coding: utf-8
from __future__ import unicode_literals
import pytest
# Note: "chromosomes" worked previous the bug fix
@pytest.mark.models('en')
@pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocalize", "colocaliz"])])
def test_issue781(EN,... | # coding: utf-8
from __future__ import unicode_literals
import pytest
# Note: "chromosomes" worked previous the bug fix
@pytest.mark.models('en')
@pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocaliz", "colocalize"])])
def test_issue781(EN,... | Fix lemma ordering in test | Fix lemma ordering in test
| Python | mit | spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,explosion/sp... | ---
+++
@@ -6,7 +6,7 @@
# Note: "chromosomes" worked previous the bug fix
@pytest.mark.models('en')
-@pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocalize", "colocaliz"])])
+@pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chr... |
0ae9b232b82285f2fa275b8ffa5dced6b9377b0e | keyring/credentials.py | keyring/credentials.py | import os
import abc
class Credential(metaclass=abc.ABCMeta):
"""Abstract class to manage credentials"""
@abc.abstractproperty
def username(self):
return None
@abc.abstractproperty
def password(self):
return None
class SimpleCredential(Credential):
"""Simple credentials imp... | import os
import abc
class Credential(metaclass=abc.ABCMeta):
"""Abstract class to manage credentials"""
@abc.abstractproperty
def username(self):
return None
@abc.abstractproperty
def password(self):
return None
class SimpleCredential(Credential):
"""Simple credentials imp... | Add equality operator to EnvironCredential | Add equality operator to EnvironCredential
Equality operator is useful for testing EnvironCredential
| Python | mit | jaraco/keyring | ---
+++
@@ -39,6 +39,15 @@
self.user_env_var = user_env_var
self.pwd_env_var = pwd_env_var
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, EnvironCredential):
+ return NotImplemented
+
+ return (
+ self.user_env_var == other.user_env_var... |
97312b55525f81ecba3c0df1d6c2e55fa217ce83 | testsettings.py | testsettings.py | import os
import dj_database_url
DATABASES = {
"default": dj_database_url.parse(os.environ["DATABASE_URL"]),
}
INSTALLED_APPS = ("django_dbq",)
MIDDLEWARE_CLASSES = (
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewM... | import os
import dj_database_url
DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///:memory:")
DATABASES = {
"default": dj_database_url.parse(DATABASE_URL),
}
INSTALLED_APPS = ("django_dbq",)
MIDDLEWARE_CLASSES = (
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.... | Make tests run on sqlite by default | Make tests run on sqlite by default
| Python | bsd-2-clause | dabapps/django-db-queue | ---
+++
@@ -1,8 +1,11 @@
import os
import dj_database_url
+
+DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///:memory:")
+
DATABASES = {
- "default": dj_database_url.parse(os.environ["DATABASE_URL"]),
+ "default": dj_database_url.parse(DATABASE_URL),
}
INSTALLED_APPS = ("django_dbq",) |
e8c180e65dda3422ab472a6580183c715ef325c3 | easyium/decorator.py | easyium/decorator.py | __author__ = 'karl.gong'
from .exceptions import UnsupportedOperationException
def SupportedBy(*web_driver_types):
def handle_func(func):
def handle_args(*args, **kwargs):
wd_types = []
for wd_type in web_driver_types:
if isinstance(wd_type, list):
... | __author__ = 'karl.gong'
from .exceptions import UnsupportedOperationException
def SupportedBy(*web_driver_types):
def handle_func(func):
def handle_args(*args, **kwargs):
wd_types = []
for wd_type in web_driver_types:
if isinstance(wd_type, list):
... | Update error message of UnsupportedOperationException. | Update error message of UnsupportedOperationException.
| Python | apache-2.0 | KarlGong/easyium-python,KarlGong/easyium | ---
+++
@@ -16,7 +16,7 @@
current_web_driver_type = args[0].get_web_driver_type()
if current_web_driver_type not in wd_types:
raise UnsupportedOperationException(
- "This operation is not supported by web driver [%s]." % current_web_driver_type)
+ ... |
e893ac40de2dda19196c7de7d9f7767b20b23884 | headers/cpp/functions.py | headers/cpp/functions.py | #!/usr/bin/env python
#
# Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | #!/usr/bin/env python
#
# Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | Use a better function (lambda) name | Use a better function (lambda) name
git-svn-id: b0ea89ea3bf41df64b6a046736e217d0ae4a0fba@40 806ff5bb-693f-0410-b502-81bc3482ff28
| Python | apache-2.0 | myint/cppclean,myint/cppclean,myint/cppclean,myint/cppclean | ---
+++
@@ -24,8 +24,8 @@
def main(argv):
# TODO(nnorwitz): need to ignore friend method declarations.
- condition = lambda node: isinstance(node, ast.Function)
- ast.PrintAllIndentifiers(argv[1:], condition)
+ IsFunction = lambda node: isinstance(node, ast.Function)
+ ast.PrintAllIndentifiers(arg... |
60ee6a5d2ad9e85fefd973c020ef65bd212e687c | astrobin/management/commands/notify_new_blog_entry.py | astrobin/management/commands/notify_new_blog_entry.py | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from zinnia.models import Entry
from astrobin.notifications import push_notification
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
... | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import persistent_messages
from zinnia.models import Entry
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
entry = Entry.objects.a... | Fix management command to send notification about new blog post. | Fix management command to send notification about new blog post.
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | ---
+++
@@ -1,20 +1,20 @@
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
+import persistent_messages
from zinnia.models import Entry
-from astrobin.notifications import push_notification
class Command(BaseCommand):
help = "Notifies all users about most r... |
1af1a7acface58cd8a6df5671d83b0a1a3ad4f3e | tiddlywebplugins/tiddlyspace/config.py | tiddlywebplugins/tiddlyspace/config.py | """
Base configuration for TiddlySpace.
This provides the basics which may be changed in tidlywebconfig.py.
"""
from tiddlywebplugins.instancer.util import get_tiddler_locations
from tiddlywebplugins.tiddlyspace.instance import store_contents
PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
config = {
'instance_... | """
Base configuration for TiddlySpace.
This provides the basics which may be changed in tidlywebconfig.py.
"""
from tiddlywebplugins.instancer.util import get_tiddler_locations
from tiddlywebplugins.tiddlyspace.instance import store_contents
PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
config = {
'instance_... | Set the tiddlywebwiki binary limit to 1MB. | Set the tiddlywebwiki binary limit to 1MB.
| Python | bsd-3-clause | FND/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,TiddlySpace/tiddlyspace | ---
+++
@@ -24,4 +24,5 @@
'server_store': ['tiddlywebplugins.mysql', {
'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}],
'indexer': 'tiddlywebplugins.mysql',
+ 'tiddlywebwiki.binary_limit': 1048576, # 1MB
} |
18f29b2b1a99614b09591df4a60c1670c845aa9b | students/crobison/session04/dict_lab.py | students/crobison/session04/dict_lab.py | # Charles Robison
# 2016.10.18
# Dictionary and Set Lab
# Create a dictionary containing “name”, “city”, and “cake”
# for “Chris” from “Seattle” who likes “Chocolate”.
d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
| # Charles Robison
# 2016.10.18
# Dictionary and Set Lab
# Create a dictionary containing “name”, “city”, and “cake”
# for “Chris” from “Seattle” who likes “Chocolate”.
d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
#Display the dictionary.
d
# Delete the entry for “cake”.
del d['cake']
# Display the ... | Add first set of exercises. | Add first set of exercises.
| Python | unlicense | Baumelbi/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,Baumelbi/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016 | ---
+++
@@ -4,6 +4,55 @@
# Create a dictionary containing “name”, “city”, and “cake”
# for “Chris” from “Seattle” who likes “Chocolate”.
-
d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
+#Display the dictionary.
+d
+
+# Delete the entry for “cake”.
+del d['cake']
+
+# Display the dictionary.
+d
... |
c9b6387702baee3da0a3bca8b302b619e69893f7 | steel/chunks/iff.py | steel/chunks/iff.py | import collections
import io
from steel.fields.numbers import BigEndian
from steel import fields
from steel.chunks import base
__all__ = ['Chunk', 'Form']
class Chunk(base.Chunk):
id = fields.String(size=4, encoding='ascii')
size = fields.Integer(size=4, endianness=BigEndian)
payload = base... | import collections
import io
from steel.fields.numbers import BigEndian
from steel import fields
from steel.chunks import base
__all__ = ['Chunk', 'ChunkList', 'Form']
class Chunk(base.Chunk):
id = fields.String(size=4, encoding='ascii')
size = fields.Integer(size=4, endianness=BigEndian)
p... | Customize a ChunkList just for IFF chunks | Customize a ChunkList just for IFF chunks
| Python | bsd-3-clause | gulopine/steel | ---
+++
@@ -5,13 +5,19 @@
from steel import fields
from steel.chunks import base
-__all__ = ['Chunk', 'Form']
+__all__ = ['Chunk', 'ChunkList', 'Form']
class Chunk(base.Chunk):
id = fields.String(size=4, encoding='ascii')
size = fields.Integer(size=4, endianness=BigEndian)
payload = base.Paylo... |
f7d4a3df11a67e3ae679b4c8f25780538c4c3c32 | core/management/commands/send_tweets.py | core/management/commands/send_tweets.py | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5):
... | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5):
... | Use the newer PostUpdate instead of PostMedia | Use the newer PostUpdate instead of PostMedia
| Python | agpl-3.0 | osamak/student-portal,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz | ---
+++
@@ -16,7 +16,7 @@
access_token_secret=user_tokens['oauth_token_secret'],)
try:
if tweet.media_path:
- status = api.PostMedia(tweet.text, tweet.media_path)
+ status = api.PostUpdate(tweet.text, media=tweet.media_... |
7a952d605b629b9c8ef2c96c451ee4db4274d545 | suddendev/config.py | suddendev/config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.urandom(32)
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
CELERY_BROKER_URL = os.environ['CLO... | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.urandom(32)
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
CELERY_BROKER_URL = os.environ['CLO... | Set max celery connections to 1. | [NG] Set max celery connections to 1.
| Python | mit | SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev | ---
+++
@@ -22,7 +22,7 @@
CLIENT_SECRET = os.environ['CLIENT_SECRET']
REDIS_MAX_CONNECTIONS = 10
- CELERY_MAX_CONNECTIONS = 10
+ CELERY_MAX_CONNECTIONS = 1
class ProductionConfig(Config):
DEBUG = False |
70a40f50e9988fadfbc42f236881c1e3e78f40f1 | icekit/project/settings/_test.py | icekit/project/settings/_test.py | from ._develop import *
# DJANGO ######################################################################
DATABASES['default'].update({
'TEST': {
'NAME': DATABASES['default']['NAME'],
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize
'SERIALIZE': False,
},
})
INSTALLE... | from ._base import *
# DJANGO ######################################################################
ALLOWED_HOSTS = ('*', )
CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie
SESSION_COOKIE_SECURE = False # Don't require HTTPS for session cookie
DATABASES['default'].update({
'TEST': {
'... | Extend base settings for test settings. Don't use live cache backend for tests. | Extend base settings for test settings. Don't use live cache backend for tests.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -1,6 +1,11 @@
-from ._develop import *
+from ._base import *
# DJANGO ######################################################################
+
+ALLOWED_HOSTS = ('*', )
+
+CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie
+SESSION_COOKIE_SECURE = False # Don't require HTTPS for session c... |
6c74e5c2bc08fd48af9e646dc911cff5e22064cb | django_performance_recorder/__init__.py | django_performance_recorder/__init__.py | # -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from .api import record # noqa: F401
__version__ = '1.0.0'
| # -*- coding:utf-8 -*-
"""
isort:skip_file
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import six
try:
import pytest
except ImportError:
pytest = None
if pytest is not None:
if six.PY2:
pytest.register_assert_rewrite(b'django_performance_recorder.api')
... | Make assert statement rich in pytest | Make assert statement rich in pytest
| Python | mit | moumoutte/django-perf-rec,YPlan/django-perf-rec | ---
+++
@@ -1,5 +1,21 @@
# -*- coding:utf-8 -*-
+"""
+isort:skip_file
+"""
from __future__ import absolute_import, division, print_function, unicode_literals
+
+import six
+
+try:
+ import pytest
+except ImportError:
+ pytest = None
+
+if pytest is not None:
+ if six.PY2:
+ pytest.register_assert_re... |
89984eb5e9e8cdb8420ff1da07c54ce0dd265629 | tests/test_git_pre_commit_hook_utils.py | tests/test_git_pre_commit_hook_utils.py | import git_pre_commit_hook_utils as utils
def test_is_python_code_by_path():
file_at_index = utils.FileAtIndex(
contents='',
size=0,
mode='',
sha1='',
status='',
path='some/path/main.py',
)
assert file_at_index.is_python_code()
def test_is_python_code_by_c... | import git_pre_commit_hook_utils as utils
import scripttest
import os
import copy
def test_with_empty_repo(tmpdir):
os_environ = copy.deepcopy(os.environ)
os_environ['GIT_DIR'] = str(tmpdir)
os_environ['GIT_WORK_TREE'] = str(tmpdir)
env = scripttest.TestFileEnvironment(
str(tmpdir),
st... | Add test for commit to empty repo case | Add test for commit to empty repo case
| Python | mit | evvers/git-pre-commit-hook-utils | ---
+++
@@ -1,4 +1,29 @@
import git_pre_commit_hook_utils as utils
+import scripttest
+import os
+import copy
+
+
+def test_with_empty_repo(tmpdir):
+ os_environ = copy.deepcopy(os.environ)
+ os_environ['GIT_DIR'] = str(tmpdir)
+ os_environ['GIT_WORK_TREE'] = str(tmpdir)
+ env = scripttest.TestFileEnviro... |
30a173da5850a457393cfdf47b7c0db303cdd2e9 | tests/test_utils.py | tests/test_utils.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from cihai import exc, utils
def test_merge_dict():
dict1 = {'hi world': 1, 'innerdict': {'hey': 1}}
dict2 = {'innerdict': {'welcome': 2}}
expected = {'hi world': 1, 'innerdict': {'hey': 1, 'w... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from cihai import exc, utils
def test_merge_dict():
dict1 = {'hi world': 1, 'innerdict': {'hey': 1}}
dict2 = {'innerdict': {'welcome': 2}}
expected = {'hi world': 1, 'innerdict': {'hey': 1, 'w... | Test importing of module with unexisting target inside | Test importing of module with unexisting target inside
There's a coverage case where a module exists, but what's inside it
isn't covered.
| Python | mit | cihai/cihai-python,cihai/cihai,cihai/cihai | ---
+++
@@ -19,4 +19,7 @@
utils.import_string('cihai')
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
+ utils.import_string('cihai.core.nonexistingimport')
+
+ with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_strin... |
fc259061ccf048af7e657888eb655da120a6606f | panoptes/test/mount/test_ioptron.py | panoptes/test/mount/test_ioptron.py | from nose.tools import raises
import panoptes
from panoptes.mount.ioptron import Mount
class TestIOptron():
@raises(AssertionError)
def test_no_config_no_commands(self):
""" Mount needs a config """
mount = Mount()
@raises(AssertionError)
def test_config_bad_commands(self):
""" Passes in a default config ... | import nose.tools
import panoptes
from panoptes.mount.ioptron import Mount
class TestIOptron():
@nose.tools.raises(AssertionError)
def test_no_config_no_commands(self):
""" Mount needs a config """
mount = Mount()
@nose.tools.raises(AssertionError)
def test_config_bad_commands(self):
""" Passes in a defau... | Use nose.tools explicitly; test for port | Use nose.tools explicitly; test for port
| Python | mit | fmin2958/POCS,Guokr1991/POCS,joshwalawender/POCS,panoptes/POCS,joshwalawender/POCS,panoptes/POCS,panoptes/POCS,Guokr1991/POCS,fmin2958/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,joshwalawender/POCS,AstroHuntsman/POCS,Guokr1991/POCS,panoptes/POCS,fmin2958/POCS,Guokr1991/POCS,AstroHuntsman/POCS | ---
+++
@@ -1,16 +1,16 @@
-from nose.tools import raises
+import nose.tools
import panoptes
from panoptes.mount.ioptron import Mount
class TestIOptron():
- @raises(AssertionError)
+ @nose.tools.raises(AssertionError)
def test_no_config_no_commands(self):
""" Mount needs a config """
mount = Mount()
... |
d448367d68e37c2d719063b8ec2ce543fec5b5e7 | sphinxcontrib/reviewbuilder/__init__.py | sphinxcontrib/reviewbuilder/__init__.py | # -*- coding: utf-8 -*-
"""
sphinxcontrib-reviewbuilder
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2013 by the WAKAYAMA Shirou
:license: LGPLv2, see LICENSE for details.
"""
from __future__ import absolute_import
from docutils.nodes import Text, paragraph
from sphinxcontrib.reviewbuilder.review... | # -*- coding: utf-8 -*-
"""
sphinxcontrib-reviewbuilder
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2013 by the WAKAYAMA Shirou
:license: LGPLv2, see LICENSE for details.
"""
from __future__ import absolute_import
from docutils import nodes
from sphinxcontrib.reviewbuilder.reviewbuilder import R... | Access docutils standard nodes through nodes.* | Access docutils standard nodes through nodes.*
| Python | lgpl-2.1 | shirou/sphinxcontrib-reviewbuilder | ---
+++
@@ -9,20 +9,20 @@
from __future__ import absolute_import
-from docutils.nodes import Text, paragraph
+from docutils import nodes
from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder
# from japanesesupport.py
def trunc_whitespace(app, doctree, docname):
- for node in doctree.tra... |
f2f77cd326c3b121eb7e6e53dfcab3964f473451 | fileupload/models.py | fileupload/models.py | from django.db import models
class Picture(models.Model):
file = models.ImageField(upload_to="pictures")
slug = models.SlugField(max_length=50, blank=True)
def __unicode__(self):
return self.file
@models.permalink
def get_absolute_url(self):
return ('upload-new', )
def save(... | from django.db import models
class Picture(models.Model):
# This is a small demo using FileField instead of ImageField, not
# depending on PIL. You will probably want ImageField in your app.
file = models.FileField(upload_to="pictures")
slug = models.SlugField(max_length=50, blank=True)
def __uni... | Use FileField instead of ImageField, we don't need PIL in this demo. | Use FileField instead of ImageField, we don't need PIL in this demo.
| Python | mit | extremoburo/django-jquery-file-upload,indrajithi/mgc-django,Imaginashion/cloud-vision,madteckhead/django-jquery-file-upload,sigurdga/django-jquery-file-upload,vaniakov/django-jquery-file-upload,extremoburo/django-jquery-file-upload,sigurdga/django-jquery-file-upload,Imaginashion/cloud-vision,Imaginashion/cloud-vision,m... | ---
+++
@@ -2,7 +2,9 @@
class Picture(models.Model):
- file = models.ImageField(upload_to="pictures")
+ # This is a small demo using FileField instead of ImageField, not
+ # depending on PIL. You will probably want ImageField in your app.
+ file = models.FileField(upload_to="pictures")
slug = mo... |
72c9a00d691b2b91bf39e1f5bdd1ef2358d8d671 | updateCollection.py | updateCollection.py | from DataObjects.Collection import Collection
from ObjectFactories.ItemFactory import ItemFactory
import json
def main():
updateCollection(
Collection('item','Items', 'agarner', []),
ItemFactory.factory('item', [0, 'someItem', 'date', 'date']),
'collections/agarner_collections/agarner_Item_... | from DataObjects.Collection import Collection
from ObjectFactories.ItemFactory import ItemFactory
from collections import OrderedDict
import json
def main():
updateCollection(
Collection('item','Items', 'agarner', []),
ItemFactory.factory('item', [0, 'someItem', 'date', 'date']),
'collectio... | Implement base json extraction to collection functionality | Implement base json extraction to collection functionality
| Python | apache-2.0 | AmosGarner/PyInventory | ---
+++
@@ -1,30 +1,45 @@
from DataObjects.Collection import Collection
from ObjectFactories.ItemFactory import ItemFactory
+from collections import OrderedDict
import json
def main():
updateCollection(
Collection('item','Items', 'agarner', []),
ItemFactory.factory('item', [0, 'someItem',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.