commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 19 3.3k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
025927fa19bb96095a2ea1c53524945f1f9590ce | spur/results.py | spur/results.py | def result(return_code, output, stderr_output, allow_error=False):
if allow_error or return_code == 0:
return ExecutionResult(return_code, output, stderr_output)
else:
raise RunProcessError(return_code, output, stderr_output)
class RunProcessError(RuntimeError):
def __init__(self, return_c... | def result(return_code, output, stderr_output, allow_error=False):
result = ExecutionResult(return_code, output, stderr_output)
if allow_error or return_code == 0:
return result
else:
raise result.to_error()
class RunProcessError(RuntimeError):
def __init__(self, return_code, output, s... | Move logic for creating RunProcessError to ExecutionResult.to_error | Move logic for creating RunProcessError to ExecutionResult.to_error
| Python | bsd-2-clause | mwilliamson/spur.py | def result(return_code, output, stderr_output, allow_error=False):
result = ExecutionResult(return_code, output, stderr_output)
if allow_error or return_code == 0:
return result
else:
raise result.to_error()
class RunProcessError(RuntimeError):
def __init__(self, return_code, output, s... | Move logic for creating RunProcessError to ExecutionResult.to_error
def result(return_code, output, stderr_output, allow_error=False):
if allow_error or return_code == 0:
return ExecutionResult(return_code, output, stderr_output)
else:
raise RunProcessError(return_code, output, stderr_output)
... |
3daa15b0ccb3fc4891daf55724cbeaa705f923e5 | scripts/clio_daemon.py | scripts/clio_daemon.py |
import logging
import simpledaemon
class clio_daemon(simpledaemon.Daemon):
default_conf = 'clio_daemon.conf'
section = 'clio'
def run(self):
import eventlet
from clio.store import app
logger = logging.getLogger()
if logger.handlers:
[app.logger.addHandler(h) f... |
import simpledaemon
class clio_daemon(simpledaemon.Daemon):
default_conf = 'clio_daemon.conf'
section = 'clio'
def run(self):
import eventlet
from clio.store import app
eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app)
if __name__ == '__... | Revert "output flask logging into simpledaemon's log file." | Revert "output flask logging into simpledaemon's log file."
This is completely superfluous - logging does this already
automatically.
This reverts commit 18091efef351ecddb1d29ee7d01d0a7fb567a7b7.
| Python | apache-2.0 | geodelic/clio,geodelic/clio |
import simpledaemon
class clio_daemon(simpledaemon.Daemon):
default_conf = 'clio_daemon.conf'
section = 'clio'
def run(self):
import eventlet
from clio.store import app
eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app)
if __name__ == '__... | Revert "output flask logging into simpledaemon's log file."
This is completely superfluous - logging does this already
automatically.
This reverts commit 18091efef351ecddb1d29ee7d01d0a7fb567a7b7.
import logging
import simpledaemon
class clio_daemon(simpledaemon.Daemon):
default_conf = 'clio_daemon.conf'
s... |
4e3f10cc417f28badc34646cc89fcd9d0307b4be | utility/lambdas/s3-static-site-deploy/lambda_function.py | utility/lambdas/s3-static-site-deploy/lambda_function.py | # import boto3
def lambda_handler(event, context):
pass
| # Invoked by: CloudFormation
# Returns: A `Data` object to a pre-signed URL
#
# Deploys the contents of a versioned zip file object from one bucket in S3
# to a another bucket
import sys
import boto3
from botocore.client import Config
import io
import zipfile
import os
import urllib.request
import json
import tracebac... | Add S3 static deploy custom resource Lambda function | Add S3 static deploy custom resource Lambda function
| Python | mit | PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure | # Invoked by: CloudFormation
# Returns: A `Data` object to a pre-signed URL
#
# Deploys the contents of a versioned zip file object from one bucket in S3
# to a another bucket
import sys
import boto3
from botocore.client import Config
import io
import zipfile
import os
import urllib.request
import json
import tracebac... | Add S3 static deploy custom resource Lambda function
# import boto3
def lambda_handler(event, context):
pass
|
ebc4acb745287762cc8cb0a18fb97ed3e01c9ab0 | mkerefuse/util.py | mkerefuse/util.py | from lxml import html
class XPathObject(object):
input_properties = {}
"""Dict of keys (property names) and XPaths (to read vals from)"""
@classmethod
def FromHTML(cls, html_contents):
inst = cls()
print("Reading through {b} bytes for {c} properties...".format(
b=len(html_... | import json
from lxml import html
class XPathObject(object):
input_properties = {}
"""Dict of keys (property names) and XPaths (to read vals from)"""
@classmethod
def FromHTML(cls, html_contents):
inst = cls()
print("Reading through {b} bytes for {c} properties...".format(
... | Add json library for repr() calls | Add json library for repr() calls
| Python | unlicense | tomislacker/python-mke-trash-pickup,tomislacker/python-mke-trash-pickup | import json
from lxml import html
class XPathObject(object):
input_properties = {}
"""Dict of keys (property names) and XPaths (to read vals from)"""
@classmethod
def FromHTML(cls, html_contents):
inst = cls()
print("Reading through {b} bytes for {c} properties...".format(
... | Add json library for repr() calls
from lxml import html
class XPathObject(object):
input_properties = {}
"""Dict of keys (property names) and XPaths (to read vals from)"""
@classmethod
def FromHTML(cls, html_contents):
inst = cls()
print("Reading through {b} bytes for {c} properties.... |
9bb7dc9c8f7b5208c332017df8b1501315e2601f | py/gaarf/utils.py | py/gaarf/utils.py | # Copyright 2022 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2022 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Fix incorrect signature for get_customer_ids function | Fix incorrect signature for get_customer_ids function
Change-Id: Ib44af3ac6437ad9fa4cbfd9fda9b055b7eff4547
| Python | apache-2.0 | google/ads-api-report-fetcher,google/ads-api-report-fetcher,google/ads-api-report-fetcher,google/ads-api-report-fetcher | # Copyright 2022 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Fix incorrect signature for get_customer_ids function
Change-Id: Ib44af3ac6437ad9fa4cbfd9fda9b055b7eff4547
# Copyright 2022 Google LLC
#
# 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
#
# ... |
0f7816676eceb42f13786408f1d1a09527919a1e | Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py | Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 12:04:18 2015
@author: wirkert
"""
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german... | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 12:04:18 2015
@author: wirkert
"""
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german... | Change SpectrometerReader a little so it can handle more data formats. | Change SpectrometerReader a little so it can handle more data formats.
| Python | bsd-3-clause | MITK/MITK,iwegner/MITK,RabadanLab/MITKats,RabadanLab/MITKats,iwegner/MITK,fmilano/mitk,fmilano/mitk,RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,fmilano/mitk,MITK/MITK,RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,fmilano/mitk,iwegner/MITK,fmilano/mitk,MITK/MITK,iwegner/MITK,iwegner/MITK,MITK/MITK,MITK/MITK,... | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 12:04:18 2015
@author: wirkert
"""
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german... | Change SpectrometerReader a little so it can handle more data formats.
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 12:04:18 2015
@author: wirkert
"""
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def re... |
1b310904b641dda7ad74e98a24f62d573bbd81f8 | chrome/browser/policy/PRESUBMIT.py | chrome/browser/policy/PRESUBMIT.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Chromium presubmit script for chrome/browser/policy.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on ... | Send try jobs that touch policy code to the linux_chromeos bot too. | Send try jobs that touch policy code to the linux_chromeos bot too.
Review URL: https://chromiumcodereview.appspot.com/10473015
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@140268 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,Jonekee/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,keishi/chromium,dednal/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,keishi/chromium,pozdnyakov/chromium-crossw... | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Chromium presubmit script for chrome/browser/policy.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on ... | Send try jobs that touch policy code to the linux_chromeos bot too.
Review URL: https://chromiumcodereview.appspot.com/10473015
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@140268 0039d316-1c4b-4281-b951-d872f2087c98
| |
9d4647dca6f5e356f807d6885019d41a4b6d4847 | skimage/measure/__init__.py | skimage/measure/__init__.py | from .find_contours import find_contours
from ._regionprops import regionprops, perimeter
from ._structural_similarity import structural_similarity
from ._polygon import approximate_polygon, subdivide_polygon | from .find_contours import find_contours
from ._regionprops import regionprops, perimeter
from ._structural_similarity import structural_similarity
from ._polygon import approximate_polygon, subdivide_polygon
__all__ = ['find_contours',
'regionprops',
'perimeter',
'structural_similarit... | Add __all__ to measure package | Add __all__ to measure package
| Python | bsd-3-clause | robintw/scikit-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,newville/scikit-image,bennlich/scikit-image,paalge/scikit-image,chriscrosscutler/scikit-image,michaelaye/scikit-image,rjeli/scikit-image,rjeli/scikit-image,keflavich/scikit-image,pratapvardhan/scikit-image,oew1v07/scikit-image,bennlich/sci... | from .find_contours import find_contours
from ._regionprops import regionprops, perimeter
from ._structural_similarity import structural_similarity
from ._polygon import approximate_polygon, subdivide_polygon
__all__ = ['find_contours',
'regionprops',
'perimeter',
'structural_similarit... | Add __all__ to measure package
from .find_contours import find_contours
from ._regionprops import regionprops, perimeter
from ._structural_similarity import structural_similarity
from ._polygon import approximate_polygon, subdivide_polygon |
591aaa938c22b797fc6bbeb5050ec489cc966a47 | tests/run_tests.py | tests/run_tests.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import main
from test_core import *
from test_lazy import *
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Hack to allow us to run tests before installing.
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..')))
from unittest import main
from test_core import *
from test_lazy import *
if __name__ == '__main__':
main()
| Make running unit tests more friendly | Make running unit tests more friendly
| Python | mit | CovenantEyes/py_stringlike | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Hack to allow us to run tests before installing.
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..')))
from unittest import main
from test_core import *
from test_lazy import *
if __name__ == '__main__':
main()
| Make running unit tests more friendly
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import main
from test_core import *
from test_lazy import *
if __name__ == '__main__':
main()
|
8c37c1ae7f42d22a186de4751a56209ebdd77ec4 | dr27demo/dr27app/test_settings.py | dr27demo/dr27app/test_settings.py | from .base_settings import *
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'driver27-cache-app'
}
} | Add settings for django tests. | Add settings for django tests.
| Python | mit | SRJ9/django-driver27,SRJ9/django-driver27,SRJ9/django-driver27 | from .base_settings import *
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'driver27-cache-app'
}
} | Add settings for django tests.
| |
69e34aff3a25b33fa804ca97e327ad4f818f7d14 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='pyhaproxy',
version='0.2.2',
keywords=('haproxy', 'parse'),
description='A Python library to parse haproxy configuration file',
license='MIT License',
install_requires=[],
include_package_data=True,
package_data={
'pyhapr... | from setuptools import setup, find_packages
setup(
name='pyhaproxy',
version='0.2.4',
keywords=('haproxy', 'parse'),
description='A Python library to parse haproxy configuration file',
license='MIT License',
install_requires=[],
include_package_data=True,
package_data={
'pyhapr... | Add additional filestring param for parser.Parse method. | version2.4: Add additional filestring param for parser.Parse method.
| Python | mit | imjoey/pyhaproxy | from setuptools import setup, find_packages
setup(
name='pyhaproxy',
version='0.2.4',
keywords=('haproxy', 'parse'),
description='A Python library to parse haproxy configuration file',
license='MIT License',
install_requires=[],
include_package_data=True,
package_data={
'pyhapr... | version2.4: Add additional filestring param for parser.Parse method.
from setuptools import setup, find_packages
setup(
name='pyhaproxy',
version='0.2.2',
keywords=('haproxy', 'parse'),
description='A Python library to parse haproxy configuration file',
license='MIT License',
install_requires=... |
b3c60add1a75975b2e420747b545219ae954b1e2 | sort-readlist.py | sort-readlist.py | #!/usr/bin/python
import logging
import re
import subprocess
import sys
import os
import calibre_config
from calibre.library.database2 import LibraryDatabase2
from calibre.utils.config import prefs
import args
TODO_DIR = os.path.join(os.environ['HOME'], 'Dropbox', 'todo')
ISSUE_PATTERN = re.compile('(\d+) (.*)$')
... | Sort to-read list by publication date | Sort to-read list by publication date
| Python | mit | xchewtoyx/comicmgt,xchewtoyx/comicmgt | #!/usr/bin/python
import logging
import re
import subprocess
import sys
import os
import calibre_config
from calibre.library.database2 import LibraryDatabase2
from calibre.utils.config import prefs
import args
TODO_DIR = os.path.join(os.environ['HOME'], 'Dropbox', 'todo')
ISSUE_PATTERN = re.compile('(\d+) (.*)$')
... | Sort to-read list by publication date
| |
73af0eed3ce746154b957af5c05137f9e432c7a3 | tests/test_pkgmanifest.py | tests/test_pkgmanifest.py | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
import requests
from platformio.util import get_api_result
def pytest_generate_tests(metafunc):
if "package_data" not in metafunc.fixturenames:
return
pkgs_manifest = get_api_result("/packages")
assert isinstance(pkgs_manif... | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
import requests
from platformio.util import get_api_result
def pytest_generate_tests(metafunc):
if "package_data" not in metafunc.fixturenames:
return
pkgs_manifest = get_api_result("/packages")
assert isinstance(pkgs_manif... | Add "application/octet-stream" mime type for package | Add "application/octet-stream" mime type for package
| Python | apache-2.0 | bkudria/platformio,awong1900/platformio,bkudria/platformio,platformio/platformio,jrobeson/platformio,platformio/platformio-core,TimJay/platformio,jrobeson/platformio,eiginn/platformio,platformio/platformio-core,bkudria/platformio,TimJay/platformio,TimJay/platformio,awong1900/platformio,valeros/platformio,ZachMassia/pla... | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
import requests
from platformio.util import get_api_result
def pytest_generate_tests(metafunc):
if "package_data" not in metafunc.fixturenames:
return
pkgs_manifest = get_api_result("/packages")
assert isinstance(pkgs_manif... | Add "application/octet-stream" mime type for package
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
import requests
from platformio.util import get_api_result
def pytest_generate_tests(metafunc):
if "package_data" not in metafunc.fixturenames:
return
pkgs_manifest = get_ap... |
f733300f622a4ffc1f0179c90590d543dc37113e | weber_utils/pagination.py | weber_utils/pagination.py | import functools
from flask import jsonify, request
from flask.ext.sqlalchemy import Pagination
from .request_utils import dictify_model, error_abort
def paginate_query(query, default_page_size=100, renderer=dictify_model):
try:
page_size = int(request.args.get("page_size", default_page_size))
pag... | import functools
from flask import jsonify, request
from flask.ext.sqlalchemy import Pagination
from .request_utils import dictify_model, error_abort
def paginate_query(query, default_page_size=100, renderer=dictify_model):
try:
page_size = int(request.args.get("page_size", default_page_size))
pag... | Allow renderer argument to paginated_view decorator | Allow renderer argument to paginated_view decorator
| Python | bsd-3-clause | vmalloc/weber-utils | import functools
from flask import jsonify, request
from flask.ext.sqlalchemy import Pagination
from .request_utils import dictify_model, error_abort
def paginate_query(query, default_page_size=100, renderer=dictify_model):
try:
page_size = int(request.args.get("page_size", default_page_size))
pag... | Allow renderer argument to paginated_view decorator
import functools
from flask import jsonify, request
from flask.ext.sqlalchemy import Pagination
from .request_utils import dictify_model, error_abort
def paginate_query(query, default_page_size=100, renderer=dictify_model):
try:
page_size = int(request.... |
e7cbed6df650851b2d44bf48f2b94291822f0b91 | recipes/sos-notebook/run_test.py | recipes/sos-notebook/run_test.py | # Test that sos kernel is installed
import jupyter_client
try:
jupyter_client.kernelspec.get_kernel_spec('sos')
except jupyter_client.kernelspec.NoSuchKernel:
print('sos kernel was not installed')
print('The following kernels are installed:')
print('jupyter_client.kernelspec.find_kernel_specs()')
... | # Test that sos kernel is installed
import jupyter_client
try:
jupyter_client.kernelspec.get_kernel_spec('sos')
except jupyter_client.kernelspec.NoSuchKernel:
print('sos kernel was not installed')
print('The following kernels are installed:')
print('jupyter_client.kernelspec.find_kernel_specs()')
... | Add test of kernel switch. | Add test of kernel switch.
| Python | bsd-3-clause | kwilcox/staged-recipes,scopatz/staged-recipes,patricksnape/staged-recipes,asmeurer/staged-recipes,mcs07/staged-recipes,patricksnape/staged-recipes,birdsarah/staged-recipes,mcs07/staged-recipes,hadim/staged-recipes,basnijholt/staged-recipes,goanpeca/staged-recipes,synapticarbors/staged-recipes,kwilcox/staged-recipes,asm... | # Test that sos kernel is installed
import jupyter_client
try:
jupyter_client.kernelspec.get_kernel_spec('sos')
except jupyter_client.kernelspec.NoSuchKernel:
print('sos kernel was not installed')
print('The following kernels are installed:')
print('jupyter_client.kernelspec.find_kernel_specs()')
... | Add test of kernel switch.
# Test that sos kernel is installed
import jupyter_client
try:
jupyter_client.kernelspec.get_kernel_spec('sos')
except jupyter_client.kernelspec.NoSuchKernel:
print('sos kernel was not installed')
print('The following kernels are installed:')
print('jupyter_client.kernelspe... |
66091bae24425c633d60dabfa1d1ee85869b20cb | platformio/debug/config/native.py | platformio/debug/config/native.py | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Disable GDB "startup-with-shell" only on Unix platform | Disable GDB "startup-with-shell" only on Unix platform
| Python | apache-2.0 | platformio/platformio-core,platformio/platformio-core,platformio/platformio | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Disable GDB "startup-with-shell" only on Unix platform
# Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apac... |
42415eb9bab1d4e5ac5b4c5bafe5234d0a617367 | migrations/versions/770_set_submitted_at_for_old_brief_responses.py | migrations/versions/770_set_submitted_at_for_old_brief_responses.py | """set submitted at for old brief responses
Revision ID: 770
Revises: 760
Create Date: 2016-10-25 11:10:53.245586
"""
# revision identifiers, used by Alembic.
revision = '770'
down_revision = '760'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.execute(... | Add migration that sets `submitted_at` for old brief responses | Add migration that sets `submitted_at` for old brief responses
For any brief response that does not have a `submitted_at` time,
we add one based on the `created_at` time. As we will now be looking
at `submitted_at` rather than `created_at` to indicate a submitted
brief response, we need to migrate all older brief resp... | Python | mit | alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api | """set submitted at for old brief responses
Revision ID: 770
Revises: 760
Create Date: 2016-10-25 11:10:53.245586
"""
# revision identifiers, used by Alembic.
revision = '770'
down_revision = '760'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.execute(... | Add migration that sets `submitted_at` for old brief responses
For any brief response that does not have a `submitted_at` time,
we add one based on the `created_at` time. As we will now be looking
at `submitted_at` rather than `created_at` to indicate a submitted
brief response, we need to migrate all older brief resp... | |
94c98ad923f1a136bcf14b81d559f634c1bc262e | populous/generators/select.py | populous/generators/select.py | from .base import Generator
class Select(Generator):
def get_arguments(self, table=None, where=None, pk='id', **kwargs):
super(Select, self).get_arguments(**kwargs)
self.table = table
self.where = where
self.pk = pk
def generate(self):
backend = self.blueprint.backen... | from .base import Generator
from .vars import parse_vars
class Select(Generator):
def get_arguments(self, table=None, where=None, pk='id', **kwargs):
super(Select, self).get_arguments(**kwargs)
self.table = table
self.where = parse_vars(where)
self.pk = pk
def generate(self)... | Handle where with variables in Select generator | Handle where with variables in Select generator
| Python | mit | novafloss/populous | from .base import Generator
from .vars import parse_vars
class Select(Generator):
def get_arguments(self, table=None, where=None, pk='id', **kwargs):
super(Select, self).get_arguments(**kwargs)
self.table = table
self.where = parse_vars(where)
self.pk = pk
def generate(self)... | Handle where with variables in Select generator
from .base import Generator
class Select(Generator):
def get_arguments(self, table=None, where=None, pk='id', **kwargs):
super(Select, self).get_arguments(**kwargs)
self.table = table
self.where = where
self.pk = pk
def genera... |
741776ce931eeb14156ca89f61ad94211d727eff | setup.py | setup.py | from setuptools import setup, find_packages
from sys import version_info
assert version_info >= (2,7)
setup(
name='molly',
version='2.0dev',
packages=find_packages(exclude=['tests']),
url='http://mollyproject.org/',
author='The Molly Project',
setup_requires=['setuptools'],
tests_require=[... | from setuptools import setup, find_packages
from sys import version_info
assert version_info >= (2,7)
setup(
name='molly',
version='2.0dev',
packages=find_packages(exclude=['tests']),
include_package_data=True,
url='http://mollyproject.org/',
author='The Molly Project',
setup_requires=['se... | Include templates, etc, with install | Include templates, etc, with install
| Python | apache-2.0 | ManchesterIO/mollyproject-next,ManchesterIO/mollyproject-next,ManchesterIO/mollyproject-next | from setuptools import setup, find_packages
from sys import version_info
assert version_info >= (2,7)
setup(
name='molly',
version='2.0dev',
packages=find_packages(exclude=['tests']),
include_package_data=True,
url='http://mollyproject.org/',
author='The Molly Project',
setup_requires=['se... | Include templates, etc, with install
from setuptools import setup, find_packages
from sys import version_info
assert version_info >= (2,7)
setup(
name='molly',
version='2.0dev',
packages=find_packages(exclude=['tests']),
url='http://mollyproject.org/',
author='The Molly Project',
setup_requir... |
8d014f6bc3994fabf3c0658e6884648ad9a8f2c2 | quizalicious.py | quizalicious.py | from flask import Flask, render_template
from redis import StrictRedis
import random
import config
app = Flask(__name__)
app.debug = config.DEBUG
db = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT)
@app.route('/')
def main():
available_quizzes = db.smembers('quizzes')
return render_template('tem... | from flask import Flask, render_template
from redis import StrictRedis
import random
import config
app = Flask(__name__)
app.debug = config.DEBUG
db = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT)
@app.route('/')
def main():
available_quizzes = db.smembers('quizzes')
return render_template('mai... | Change key lookups and fix typos | Change key lookups and fix typos
Revamped the way URLs were handled from Redis by differentiating the URL
friendly name from the actual name. Fixed bad paths in render_template
for all routes.
| Python | bsd-2-clause | estreeper/quizalicious,estreeper/quizalicious,estreeper/quizalicious | from flask import Flask, render_template
from redis import StrictRedis
import random
import config
app = Flask(__name__)
app.debug = config.DEBUG
db = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT)
@app.route('/')
def main():
available_quizzes = db.smembers('quizzes')
return render_template('mai... | Change key lookups and fix typos
Revamped the way URLs were handled from Redis by differentiating the URL
friendly name from the actual name. Fixed bad paths in render_template
for all routes.
from flask import Flask, render_template
from redis import StrictRedis
import random
import config
app = Flask(__name__)
app... |
c171359ca9e50328a09f98af2cb5b0f6cd6f7e50 | pombola/south_africa/management/commands/south_africa_import_new_constituency_office_locations.py | pombola/south_africa/management/commands/south_africa_import_new_constituency_office_locations.py | """Command to import PMG's constitiency office data
PMG are undertaking an exercise to visit all the constituency
offices and collect accurate locations and photographs.
The data from this is available at
https://app.m4jam.com/app/campaigns/2298/export/
This script parses the resulting CSV file and updates our data
... | Add a script to import new constituency office locations. | Add a script to import new constituency office locations.
PMG are conducting an exercise to go to all the constituency offices
and get accurate locations for them and photographs. The data they
collect is available as a CSV, and this new management command
processes that CSV and updates our data with the improved loca... | Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola | """Command to import PMG's constitiency office data
PMG are undertaking an exercise to visit all the constituency
offices and collect accurate locations and photographs.
The data from this is available at
https://app.m4jam.com/app/campaigns/2298/export/
This script parses the resulting CSV file and updates our data
... | Add a script to import new constituency office locations.
PMG are conducting an exercise to go to all the constituency offices
and get accurate locations for them and photographs. The data they
collect is available as a CSV, and this new management command
processes that CSV and updates our data with the improved loca... | |
da5ca6baf75b2230e3e8a62066bebaa96a16bf3d | test/server.py | test/server.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Server used for tests
"""
import sys
import os
# ensure sys knows about pyqode.core in the test env
sys.path.insert(0, os.getcwd())
from pyqode.core import backend
if __name__ == '__main__':
print('Server started')
print(sys.path)
print(os.getcwd())
ba... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Server used for tests
"""
import sys
import os
# ensure sys knows about pyqode.core in the test env
sys.path.insert(0, os.getcwd())
sys.path.insert(0, os.path.abspath(".."))
from pyqode.core import backend
if __name__ == '__main__':
print('Server started')
pri... | Fix test suite on travis (restore previous path config) | Fix test suite on travis (restore previous path config)
| Python | mit | pyQode/pyqode.core,zwadar/pyqode.core,pyQode/pyqode.core | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Server used for tests
"""
import sys
import os
# ensure sys knows about pyqode.core in the test env
sys.path.insert(0, os.getcwd())
sys.path.insert(0, os.path.abspath(".."))
from pyqode.core import backend
if __name__ == '__main__':
print('Server started')
pri... | Fix test suite on travis (restore previous path config)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Server used for tests
"""
import sys
import os
# ensure sys knows about pyqode.core in the test env
sys.path.insert(0, os.getcwd())
from pyqode.core import backend
if __name__ == '__main__':
print('Server st... |
38e570e50976ee863fddd00129ce2d1782b06ca5 | examples/manual_stats_reporting.py | examples/manual_stats_reporting.py | """
Example of a manual_report() function that can be used either as a context manager
(with statement), or a decorator, to manually add entries to Locust's statistics.
Usage as a context manager:
with manual_report("stats entry name"):
# Run time of this block will be reported under a stats entry called... | Add example with a manual_report decorator/context manager that can be used to easily measure the time of functions/code blocks and manually report them as stats entries to the Locust statistics | Add example with a manual_report decorator/context manager that can be used to easily measure the time of functions/code blocks and manually report them as stats entries to the Locust statistics | Python | mit | mbeacom/locust,mbeacom/locust,mbeacom/locust,locustio/locust,locustio/locust,mbeacom/locust,locustio/locust,locustio/locust | """
Example of a manual_report() function that can be used either as a context manager
(with statement), or a decorator, to manually add entries to Locust's statistics.
Usage as a context manager:
with manual_report("stats entry name"):
# Run time of this block will be reported under a stats entry called... | Add example with a manual_report decorator/context manager that can be used to easily measure the time of functions/code blocks and manually report them as stats entries to the Locust statistics
| |
7f611e99d36089bc6836042ba8aec2df02a56f3a | pymemcache/test/test_serde.py | pymemcache/test/test_serde.py | from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
import pytest
import six
@pytest.mark.unit()
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value... | from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer, FLAG_PICKLE,
FLAG_INTEGER, FLAG_LONG, FLAG_TEXT)
import pytest
import six
@pytest.mark.unit()
class TestSerde(TestCase):
def check(sel... | Test for expected flags with serde tests | Test for expected flags with serde tests
| Python | apache-2.0 | bwalks/pymemcache,sontek/pymemcache,pinterest/pymemcache,ewdurbin/pymemcache,pinterest/pymemcache,sontek/pymemcache | from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer, FLAG_PICKLE,
FLAG_INTEGER, FLAG_LONG, FLAG_TEXT)
import pytest
import six
@pytest.mark.unit()
class TestSerde(TestCase):
def check(sel... | Test for expected flags with serde tests
from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
import pytest
import six
@pytest.mark.unit()
class TestSerde(TestCase):
def check(self, value):
serialized, flags ... |
62ec4eca706bbb521d02ec597c0c18a949b37e52 | sysctl/tests/test_sysctl_setvalue.py | sysctl/tests/test_sysctl_setvalue.py | import os
import sysctl
from sysctl.tests import SysctlTestBase
class TestSysctlANum(SysctlTestBase):
def test_sysctl_setvalue(self):
dummy = sysctl.filter('kern.dummy')[0]
try:
self.command("/sbin/sysctl kern.dummy=0")
except:
if os.getuid() == 0:
... | Add test to set a sysctl value | Add test to set a sysctl value
| Python | bsd-2-clause | williambr/py-sysctl,williambr/py-sysctl | import os
import sysctl
from sysctl.tests import SysctlTestBase
class TestSysctlANum(SysctlTestBase):
def test_sysctl_setvalue(self):
dummy = sysctl.filter('kern.dummy')[0]
try:
self.command("/sbin/sysctl kern.dummy=0")
except:
if os.getuid() == 0:
... | Add test to set a sysctl value
| |
e08a382e215569b2ad147ea82d7ede1319722724 | configurator/__init__.py | configurator/__init__.py | """Adaptive configuration dialogs.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(version=None): # overwritten by setup.py
if version is None:
pkg_dir = os.path.dirname(__file__)
src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir... | """Adaptive configuration dialogs.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(version=None): # overwritten by setup.py
if version is None:
pkg_dir = os.path.dirname(__file__)
src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir... | Use git describe --always in _get_version() | Use git describe --always in _get_version()
Travis CI does a truncated clone and causes 'git describe' to fail if
the version tag is not part of the truncated history.
| Python | apache-2.0 | yasserglez/configurator,yasserglez/configurator | """Adaptive configuration dialogs.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(version=None): # overwritten by setup.py
if version is None:
pkg_dir = os.path.dirname(__file__)
src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir... | Use git describe --always in _get_version()
Travis CI does a truncated clone and causes 'git describe' to fail if
the version tag is not part of the truncated history.
"""Adaptive configuration dialogs.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(versi... |
6755255332039ab3c0ea60346f61420b52e2f474 | tests/functional/test_l10n.py | tests/functional/test_l10n.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | Fix intermittent failure in l10n language selector test | Fix intermittent failure in l10n language selector test
| Python | mpl-2.0 | sgarrity/bedrock,TheoChevalier/bedrock,craigcook/bedrock,mkmelin/bedrock,TheoChevalier/bedrock,Sancus/bedrock,hoosteeno/bedrock,sylvestre/bedrock,schalkneethling/bedrock,Sancus/bedrock,analytics-pros/mozilla-bedrock,sylvestre/bedrock,glogiotatidis/bedrock,jgmize/bedrock,kyoshino/bedrock,mkmelin/bedrock,gerv/bedrock,dav... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | Fix intermittent failure in l10n language selector test
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage... |
4cdc120fbf654a6ce43bdb455ce89f7524ef9cd4 | images/demo/ipython_notebook_config.py | images/demo/ipython_notebook_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy... | Configure the IPython notebook user settings | Configure the IPython notebook user settings
| Python | bsd-3-clause | marscher/tmpnb,willjharmer/tmpnb,marscher/tmpnb,ianabc/tmpnb,willjharmer/tmpnb,parente/tmpnb,betatim/tmpnb,iamjakob/tmpnb,jupyter/tmpnb,ianabc/tmpnb,iamjakob/tmpnb,captainsafia/tmpnb,cannin/tmpnb,zischwartz/tmpnb,malev/tmpnb,ianabc/tmpnb,ianabc/tmpnb,parente/tmpnb,parente/tmpnb,jupyter/tmpnb,betatim/tmpnb,rgbkrk/tmpnb,... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy... | Configure the IPython notebook user settings
| |
987c54559cb52370fc459a30cdbdfd0e38c5ef62 | plata/context_processors.py | plata/context_processors.py | import plata
def plata_context(request):
"""
Adds a few variables from Plata to the context if they are available:
* ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
* ``plata.order``: The current order
* ``plata.contact``: The current contact instance
"""
shop = plata.... | import plata
def plata_context(request):
"""
Adds a few variables from Plata to the context if they are available:
* ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
* ``plata.order``: The current order
* ``plata.contact``: The current contact instance
* ``plata.price_includ... | Add the variable `plata.price_includes_tax` to the template context | Add the variable `plata.price_includes_tax` to the template context
| Python | bsd-3-clause | armicron/plata,armicron/plata,stefanklug/plata,armicron/plata | import plata
def plata_context(request):
"""
Adds a few variables from Plata to the context if they are available:
* ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
* ``plata.order``: The current order
* ``plata.contact``: The current contact instance
* ``plata.price_includ... | Add the variable `plata.price_includes_tax` to the template context
import plata
def plata_context(request):
"""
Adds a few variables from Plata to the context if they are available:
* ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
* ``plata.order``: The current order
* ``pla... |
d48e59f4b1174529a4d2eca8731472a5bf371621 | simpleseo/templatetags/seo.py | simpleseo/templatetags/seo.py | from django.template import Library
from django.utils.translation import get_language
from simpleseo import settings
from simpleseo.models import SeoMetadata
register = Library()
@register.filter
def single_quotes(description):
return description.replace('\"', '\'')
@register.inclusion_tag('simpleseo/metadata... | from django.forms.models import model_to_dict
from django.template import Library
from django.utils.translation import get_language
from simpleseo import settings
from simpleseo.models import SeoMetadata
register = Library()
@register.filter
def single_quotes(description):
return description.replace('\"', '\'')... | Allow to set default value in template | Allow to set default value in template
| Python | bsd-3-clause | Glamping-Hub/django-painless-seo,Glamping-Hub/django-painless-seo,AMongeMoreno/django-painless-seo,AMongeMoreno/django-painless-seo | from django.forms.models import model_to_dict
from django.template import Library
from django.utils.translation import get_language
from simpleseo import settings
from simpleseo.models import SeoMetadata
register = Library()
@register.filter
def single_quotes(description):
return description.replace('\"', '\'')... | Allow to set default value in template
from django.template import Library
from django.utils.translation import get_language
from simpleseo import settings
from simpleseo.models import SeoMetadata
register = Library()
@register.filter
def single_quotes(description):
return description.replace('\"', '\'')
@re... |
eb15038cd582e087225985947e4b98ffbc86d812 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('git_externals/__init__.py') as fp:
exec(fp.read())
classifiers = [
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('git_externals/__init__.py') as fp:
exec(fp.read())
classifiers = [
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming... | Remove version requirement, add pathlib | Remove version requirement, add pathlib
| Python | mit | develersrl/git-externals,develersrl/git-externals,develersrl/git-externals | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('git_externals/__init__.py') as fp:
exec(fp.read())
classifiers = [
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming... | Remove version requirement, add pathlib
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('git_externals/__init__.py') as fp:
exec(fp.read())
classifiers = [
'Development Status :: 4 - Beta',
'Programm... |
5bdc9a7834c67ac7e39c9674b328a68e42467efc | yggdrasil/yggdrasil_tests.py | yggdrasil/yggdrasil_tests.py | from unittest import TestCase
from intent.igt.references import raw_tier, cleaned_tier, normalized_tier
from intent.igt.rgxigt import Igt
from yggdrasil.igt_operations import add_raw_tier, add_clean_tier, add_normal_tier
class ConstructIGTTests(TestCase):
def setUp(self):
self.lines = [{'text':'This is ... | Move testcases here from INTENT. | Move testcases here from INTENT.
| Python | mit | xigt/yggdrasil,xigt/yggdrasil,xigt/yggdrasil | from unittest import TestCase
from intent.igt.references import raw_tier, cleaned_tier, normalized_tier
from intent.igt.rgxigt import Igt
from yggdrasil.igt_operations import add_raw_tier, add_clean_tier, add_normal_tier
class ConstructIGTTests(TestCase):
def setUp(self):
self.lines = [{'text':'This is ... | Move testcases here from INTENT.
| |
899e3c9f81a43dcb94e290ce0a86f128bd94effd | opps/channel/context_processors.py | opps/channel/context_processors.py | # -*- coding: utf-8 -*-
from .models import Channel
def channel_context(request):
return {'opps_menu': Channel.objects.all()}
| # -*- coding: utf-8 -*-
from django.utils import timezone
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
opps_menu = Channel.objects.filter(date_available__lte=timezone.now(),
published=True)
return {'opps_menu': opp... | Apply filter channel published on menu list (channel context processors) | Apply filter channel published on menu list (channel context processors)
| Python | mit | YACOWS/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,opps/opps | # -*- coding: utf-8 -*-
from django.utils import timezone
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
opps_menu = Channel.objects.filter(date_available__lte=timezone.now(),
published=True)
return {'opps_menu': opp... | Apply filter channel published on menu list (channel context processors)
# -*- coding: utf-8 -*-
from .models import Channel
def channel_context(request):
return {'opps_menu': Channel.objects.all()}
|
3421db3528a655768141b3615d04d84cf7100bb0 | ckanext/requestdata/plugin.py | ckanext/requestdata/plugin.py | import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckanext.requestdata.model import setup as model_setup
class RequestdataPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.IRoutes, inherit=True)
plugins.implements(plugins.IConfigur... | import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckanext.requestdata.model import setup as model_setup
from ckanext.requestdata.logic import actions
from ckanext.requestdata.logic import auth
class RequestdataPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
p... | Define actions and auth functions | Define actions and auth functions
| Python | agpl-3.0 | ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata | import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckanext.requestdata.model import setup as model_setup
from ckanext.requestdata.logic import actions
from ckanext.requestdata.logic import auth
class RequestdataPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
p... | Define actions and auth functions
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckanext.requestdata.model import setup as model_setup
class RequestdataPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.IRoutes, inherit=True)
p... |
6b51bb8e62ca8bb43c93c2c58b65b5b4fb5c1a06 | src/ggrc/settings/app_engine.py | src/ggrc/settings/app_engine.py | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FU... | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FU... | Disable SQL logging in appengine | Disable SQL logging in appengine
| Python | apache-2.0 | uskudnik/ggrc-core,uskudnik/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,VinnieJohns/ggrc-core,vladan-m/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core,vlad... | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FU... | Disable SQL logging in appengine
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_M... |
8b7c5b7001ac005849fb31d83415db3a6517feb7 | reddit_adzerk/adzerkads.py | reddit_adzerk/adzerkads.py | from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
| from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
... | Set the frame id to what aderk expects. | Set the frame id to what aderk expects.
(See a corresponding change to ads.html in reddit)
| Python | bsd-3-clause | madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk | from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
... | Set the frame id to what aderk expects.
(See a corresponding change to ads.html in reddit)
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test... |
4027cccb929308528666e1232eeebfc1988e0ab1 | tests/iam/test_iam_valid_json.py | tests/iam/test_iam_valid_json.py | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def test_all_iam_templates():
"""Verify all IAM templates render as proper JSON."""
jinjaenv = jinja2.Environment(loader=jinja2.F... | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def iam_templates():
"""Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TE... | Use generator for IAM template names | test: Use generator for IAM template names
See also: #208
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def iam_templates():
"""Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TE... | test: Use generator for IAM template names
See also: #208
"""Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def test_all_iam_templates():
"""Verify all IAM templates render as prope... |
7d6c9ac443dd34784f00fd4d7bc0cbee904ed98f | src/python/cargo/temporal.py | src/python/cargo/temporal.py | """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
from datetime import tzinfo
class UTC(tzinfo):
"""
The one true time zone.
"""
def utcoffset(self, dt):
"""
Return the offset to UTC.
"""
from datetime import timedelta
return timedelta(0)
def tznam... | """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
from datetime import tzinfo
class UTC(tzinfo):
"""
The one true time zone.
"""
def utcoffset(self, dt):
"""
Return the offset to UTC.
"""
from datetime import timedelta
return timedelta(0)
def tznam... | Fix comment after dropping the pytz dependency. | Fix comment after dropping the pytz dependency.
| Python | mit | borg-project/cargo,borg-project/cargo | """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
from datetime import tzinfo
class UTC(tzinfo):
"""
The one true time zone.
"""
def utcoffset(self, dt):
"""
Return the offset to UTC.
"""
from datetime import timedelta
return timedelta(0)
def tznam... | Fix comment after dropping the pytz dependency.
"""
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
from datetime import tzinfo
class UTC(tzinfo):
"""
The one true time zone.
"""
def utcoffset(self, dt):
"""
Return the offset to UTC.
"""
from datetime import time... |
3fbec65f39295eb45211e33f0452b1076541cbc1 | etl/csv/__init__.py | etl/csv/__init__.py | import overview
import personnel
import match
import events
import statistics
CSV_ETL_CLASSES = {
'Overview': {
'Competitions': overview.CompetitionIngest,
'Clubs': overview.ClubIngest,
'Venues': overview.VenueIngest
},
'Personnel': {
'Players': personnel.PlayerIngest,
... | Create dictionary to map ETL data files to ingestion classes | Create dictionary to map ETL data files to ingestion classes
| Python | mit | soccermetrics/marcotti | import overview
import personnel
import match
import events
import statistics
CSV_ETL_CLASSES = {
'Overview': {
'Competitions': overview.CompetitionIngest,
'Clubs': overview.ClubIngest,
'Venues': overview.VenueIngest
},
'Personnel': {
'Players': personnel.PlayerIngest,
... | Create dictionary to map ETL data files to ingestion classes
| |
fa2e48566bf532a2c72f9863444f3c7cff23a1c4 | github/commands/open_file_on_remote.py | github/commands/open_file_on_remote.py | from sublime_plugin import TextCommand
from ...common.file_and_repo import FileAndRepo
from ..github import open_file_in_browser
class GsOpenFileOnRemoteCommand(TextCommand, FileAndRepo):
"""
Open a new browser window to the web-version of the currently opened
(or specified) file. If `preselect` is `Tru... | from sublime_plugin import TextCommand
from ...core.base_command import BaseCommand
from ..github import open_file_in_browser
class GsOpenFileOnRemoteCommand(TextCommand, BaseCommand):
"""
Open a new browser window to the web-version of the currently opened
(or specified) file. If `preselect` is `True`,... | Fix regression where unable to open file on remote. | Fix regression where unable to open file on remote.
| Python | mit | divmain/GitSavvy,ddevlin/GitSavvy,ddevlin/GitSavvy,ypersyntelykos/GitSavvy,stoivo/GitSavvy,theiviaxx/GitSavvy,ralic/GitSavvy,dreki/GitSavvy,ralic/GitSavvy,jmanuel1/GitSavvy,divmain/GitSavvy,stoivo/GitSavvy,dreki/GitSavvy,dvcrn/GitSavvy,asfaltboy/GitSavvy,stoivo/GitSavvy,theiviaxx/GitSavvy,asfaltboy/GitSavvy,ddevlin/Git... | from sublime_plugin import TextCommand
from ...core.base_command import BaseCommand
from ..github import open_file_in_browser
class GsOpenFileOnRemoteCommand(TextCommand, BaseCommand):
"""
Open a new browser window to the web-version of the currently opened
(or specified) file. If `preselect` is `True`,... | Fix regression where unable to open file on remote.
from sublime_plugin import TextCommand
from ...common.file_and_repo import FileAndRepo
from ..github import open_file_in_browser
class GsOpenFileOnRemoteCommand(TextCommand, FileAndRepo):
"""
Open a new browser window to the web-version of the currently o... |
74ac965c451f29faa344be0161ebb419395faa6e | entities/context_processors.py | entities/context_processors.py | from . import models
from django.conf import settings
def groups(request):
return {
'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
}
def statistics(request):
return {
... | from . import models
from django.conf import settings
from django.contrib.auth import hashers
def groups(request):
return {
'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
}
... | Exclude unusable users from stats | Exclude unusable users from stats
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten | from . import models
from django.conf import settings
from django.contrib.auth import hashers
def groups(request):
return {
'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
}
... | Exclude unusable users from stats
from . import models
from django.conf import settings
def groups(request):
return {
'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
}
def s... |
20562a167e24911873e83659bccfde94b0a91061 | do_the_tests.py | do_the_tests.py | from runtests import Tester
import os.path
tester = Tester(os.path.abspath(__file__), "fake_spectra")
tester.main(sys.argv[1:])
| from runtests import Tester
import os.path
import sys
tester = Tester(os.path.abspath(__file__), "fake_spectra")
tester.main(sys.argv[1:])
| Add import back to test script | Add import back to test script
| Python | mit | sbird/fake_spectra,sbird/fake_spectra,sbird/fake_spectra | from runtests import Tester
import os.path
import sys
tester = Tester(os.path.abspath(__file__), "fake_spectra")
tester.main(sys.argv[1:])
| Add import back to test script
from runtests import Tester
import os.path
tester = Tester(os.path.abspath(__file__), "fake_spectra")
tester.main(sys.argv[1:])
|
4dfb5003994b45d01d451412d12fbf30051f68a8 | project_euler/library/number_theory/test_pells_equation.py | project_euler/library/number_theory/test_pells_equation.py | import pytest
from typing import Tuple
from .pells_equation import solve_pells_equation
from ..sqrt import is_square
PELLS_SOLUTIONS = [
(
2,
[
3,
2
]
),
(
3,
[
2,
1
]
),
(
5,
[
... | Add testing for Pells equation | Add testing for Pells equation
| Python | mit | cryvate/project-euler,cryvate/project-euler | import pytest
from typing import Tuple
from .pells_equation import solve_pells_equation
from ..sqrt import is_square
PELLS_SOLUTIONS = [
(
2,
[
3,
2
]
),
(
3,
[
2,
1
]
),
(
5,
[
... | Add testing for Pells equation
| |
ade69178edac1d4d73dedee0ad933d4106e22c82 | knox/crypto.py | knox/crypto.py | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from OpenSSL.rand import bytes as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hex... | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
... | Use os.urandom instead of OpenSSL.rand.bytes | Use os.urandom instead of OpenSSL.rand.bytes
Follows suggestion in pyOpenSSL changelog https://github.com/pyca/pyopenssl/blob/1eac0e8f9b3829c5401151fabb3f78453ad772a4/CHANGELOG.rst#backward-incompatible-changes-1 | Python | mit | James1345/django-rest-knox,James1345/django-rest-knox | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
... | Use os.urandom instead of OpenSSL.rand.bytes
Follows suggestion in pyOpenSSL changelog https://github.com/pyca/pyopenssl/blob/1eac0e8f9b3829c5401151fabb3f78453ad772a4/CHANGELOG.rst#backward-incompatible-changes-1
import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primiti... |
a7e96f68ad2c222a360ad51d9826268ba2620c9b | morse_trainer/test_audio.py | morse_trainer/test_audio.py | import math
import numpy
import pyaudio
def sine(frequency, length, rate):
length = int(length * rate)
factor = float(frequency) * (math.pi * 2) / rate
return numpy.sin(numpy.arange(length) * factor)
def play_tone(stream, frequency=440, length=1, rate=44100):
chunks = []
chunks.append(sine(frequ... | Test codie to get sound duration right | Test codie to get sound duration right
| Python | mit | rzzzwilson/morse,rzzzwilson/morse | import math
import numpy
import pyaudio
def sine(frequency, length, rate):
length = int(length * rate)
factor = float(frequency) * (math.pi * 2) / rate
return numpy.sin(numpy.arange(length) * factor)
def play_tone(stream, frequency=440, length=1, rate=44100):
chunks = []
chunks.append(sine(frequ... | Test codie to get sound duration right
| |
59e454f0272725c46d06f3d5f32edafa866f578b | registration/admin.py | registration/admin.py | from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfile, RegistrationAdmin)
| from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfil... | Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users. | Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
| Python | bsd-3-clause | remarkablerocket/django-mailinglist-registration,remarkablerocket/django-mailinglist-registration | from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfil... | Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
search_fie... |
5b18131069f860b712d8e54611541a8729496867 | suorganizer/urls.py | suorganizer/urls.py | """suorganizer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | """suorganizer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | Create URL pattern for Tag Detail. | Ch05: Create URL pattern for Tag Detail.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | """suorganizer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | Ch05: Create URL pattern for Tag Detail.
"""suorganizer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: ... |
2793f9a4e245c79ece58990622ae059a70514592 | actions/aws_decrypt_password_data.py | actions/aws_decrypt_password_data.py | #!/usr/bin/env python
import base64
import rsa
import six
from st2common.runners.base_action import Action
class AwsDecryptPassworData(Action):
def run(self, keyfile, password_data):
# copied from:
# https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L12... | #!/usr/bin/env python
import base64
import rsa
import six
from st2common.runners.base_action import Action
class AwsDecryptPassworData(Action):
def run(self, keyfile, password_data):
# copied from:
# https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L12... | Add a workaround since somewhere in the Mistral "publish variable" pipeline, trealing and leading whitespace is removed. | Add a workaround since somewhere in the Mistral "publish variable"
pipeline, trealing and leading whitespace is removed.
| Python | apache-2.0 | StackStorm/st2cd,StackStorm/st2cd | #!/usr/bin/env python
import base64
import rsa
import six
from st2common.runners.base_action import Action
class AwsDecryptPassworData(Action):
def run(self, keyfile, password_data):
# copied from:
# https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L12... | Add a workaround since somewhere in the Mistral "publish variable"
pipeline, trealing and leading whitespace is removed.
#!/usr/bin/env python
import base64
import rsa
import six
from st2common.runners.base_action import Action
class AwsDecryptPassworData(Action):
def run(self, keyfile, password_data):
... |
811263573aa35361da8a8ddde03b333914e156c5 | web_utils.py | web_utils.py | """Collection of HTTP helpers."""
from functools import partial, wraps
from inspect import iscoroutine
from aiohttp.web import json_response
def async_json_out(orig_method=None, *, content_type='application/json', **kwargs):
"""Turn dict output of an HTTP handler into JSON response.
Decorates aiohttp reque... | """Collection of HTTP helpers."""
from functools import partial, wraps
from inspect import iscoroutine
from aiohttp.web import json_response
def async_json_out(orig_method=None, *, status=200, content_type='application/json', **kwargs):
"""Turn dict output of an HTTP handler into JSON response.
Decorates a... | Add default status=200 to async_json_out decorator | Add default status=200 to async_json_out decorator
| Python | mit | open-craft-guild/aio-feature-flags | """Collection of HTTP helpers."""
from functools import partial, wraps
from inspect import iscoroutine
from aiohttp.web import json_response
def async_json_out(orig_method=None, *, status=200, content_type='application/json', **kwargs):
"""Turn dict output of an HTTP handler into JSON response.
Decorates a... | Add default status=200 to async_json_out decorator
"""Collection of HTTP helpers."""
from functools import partial, wraps
from inspect import iscoroutine
from aiohttp.web import json_response
def async_json_out(orig_method=None, *, content_type='application/json', **kwargs):
"""Turn dict output of an HTTP hand... |
64636185744a9a64b1b04fcd81ee32930bb145af | scores.py | scores.py | from nameko.rpc import rpc, RpcProxy
class ScoreService(object):
name = 'score_service'
player_service = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_service.get_players()
return sorted(players, key=lambda player: player.score, reverse=True)
| from nameko.rpc import rpc, RpcProxy
class ScoreService(object):
name = 'score_service'
player_rpc = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_rpc.get_players()
sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
... | Add method to update a player's score | Add method to update a player's score
| Python | mit | radekj/poke-battle,skooda/poke-battle | from nameko.rpc import rpc, RpcProxy
class ScoreService(object):
name = 'score_service'
player_rpc = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_rpc.get_players()
sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
... | Add method to update a player's score
from nameko.rpc import rpc, RpcProxy
class ScoreService(object):
name = 'score_service'
player_service = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_service.get_players()
return sorted(players, key=lambda player... |
a5f591a71e460130055aafd16b248f7f61d0c541 | snippets/python/nested.py | snippets/python/nested.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
# To test this module:
# python -m unittest -v nested
def string_maxlen(txt,max_len=12):
n = len(txt)... | Add subroutine to print a dictionary tree | Add subroutine to print a dictionary tree
| Python | apache-2.0 | nathanielng/code-templates,nathanielng/code-templates,nathanielng/code-templates | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
# To test this module:
# python -m unittest -v nested
def string_maxlen(txt,max_len=12):
n = len(txt)... | Add subroutine to print a dictionary tree
| |
2d6fa86db28f79c7a576b56279c6a38cf3804eaf | setup.py | setup.py | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-nexmo',
version='1.0.1',
packages=['nexmo'],
in... | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-nexmo',
version='1.0.1',
packages=['nexmo'],
in... | Add libnexmo as a dependency | Add libnexmo as a dependency
| Python | mit | thibault/django-nexmo | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-nexmo',
version='1.0.1',
packages=['nexmo'],
in... | Add libnexmo as a dependency
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-nexmo',
version='1.0.1',
... |
9487887223be3a321c507e65210c2b651060fac3 | setup.py | setup.py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requires = [
'requests',
'rauth'
]
setup(
name='fatsecret',
version='0.2.1',
description='Python wrapper for FatSecret REST API',
url='github.com/walexnelson/pyfatsecret',
license='MIT',
auth... | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requires = [
'requests',
'rauth'
]
setup(
name='fatsecret',
version='0.2.1',
description='Python wrapper for FatSecret REST API',
url='github.com/walexnelson/pyfatsecret',
license='MIT',
auth... | Use packaging instead of a module | Use packaging instead of a module | Python | mit | walexnelson/pyfatsecret | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requires = [
'requests',
'rauth'
]
setup(
name='fatsecret',
version='0.2.1',
description='Python wrapper for FatSecret REST API',
url='github.com/walexnelson/pyfatsecret',
license='MIT',
auth... | Use packaging instead of a module
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requires = [
'requests',
'rauth'
]
setup(
name='fatsecret',
version='0.2.1',
description='Python wrapper for FatSecret REST API',
url='github.com/walexnelson/pyfatse... |
e8ab72d069633aca71ae60d62ece3c0146289b18 | xc7/utils/vivado_output_timing.py | xc7/utils/vivado_output_timing.py | """ Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse
def create_runme(f_out, args):
print(
"""
report_timing_summary
source {util_tcl}
write_timing_info timing_{name}.json5
""".format(name=args.name, util_tcl=args.util_tcl),
file=f_out
... | """ Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse
def create_output_timing(f_out, args):
print(
"""
source {util_tcl}
write_timing_info timing_{name}.json5
report_timing_summary
""".format(name=args.name, util_tcl=args.util_tcl),
file... | Correct function name and put report_timing_summary at end of script. | Correct function name and put report_timing_summary at end of script.
Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>
| Python | isc | SymbiFlow/symbiflow-arch-defs,SymbiFlow/symbiflow-arch-defs | """ Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse
def create_output_timing(f_out, args):
print(
"""
source {util_tcl}
write_timing_info timing_{name}.json5
report_timing_summary
""".format(name=args.name, util_tcl=args.util_tcl),
file... | Correct function name and put report_timing_summary at end of script.
Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>
""" Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse
def create_runme(f_out, args):
p... |
78d520b88e13a35ac20a0eeea1385f35b17383d2 | sieve/sieve.py | sieve/sieve.py | def sieve(n):
return list(primes(n))
def primes(n):
if n < 2:
raise StopIteration
yield 2
not_prime = set()
for i in range(3, n+1, 2):
if i not in not_prime:
yield i
not_prime.update(range(i*i, n, i))
| def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
| Switch to more optimal non-generator solution | Switch to more optimal non-generator solution
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
| Switch to more optimal non-generator solution
def sieve(n):
return list(primes(n))
def primes(n):
if n < 2:
raise StopIteration
yield 2
not_prime = set()
for i in range(3, n+1, 2):
if i not in not_prime:
yield i
not_prime.update(range(i*i, n, i))
|
6b92c4d155d066fb6f4e9180acb4ad07d7fc313d | pskb_website/utils.py | pskb_website/utils.py | import re
from unicodedata import normalize
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
"""Generates an slightly worse ASCII-only slug."""
result = []
for word in _punct_re.split(text.lower()):
word ... | import re
from unicodedata import normalize
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')
# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
"""Generates an slightly worse ASCII-only slug."""
result = []
for word in _punct_re.split(text.lower()):
word... | Change ":" in titles to "-" for better SEO | Change ":" in titles to "-" for better SEO
| Python | agpl-3.0 | paulocheque/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms | import re
from unicodedata import normalize
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')
# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
"""Generates an slightly worse ASCII-only slug."""
result = []
for word in _punct_re.split(text.lower()):
word... | Change ":" in titles to "-" for better SEO
import re
from unicodedata import normalize
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
"""Generates an slightly worse ASCII-only slug."""
result = []
for word in ... |
ea39c4ebba3d5ab42dfa202f88f7d76386e505fe | plugins/MeshView/MeshView.py | plugins/MeshView/MeshView.py | from Cura.View.View import View
class MeshView(View):
def __init__(self):
super(MeshView, self).__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
self._renderObject(scene.getRoot(), renderer)
def _renderObject(self, object,... | from Cura.View.View import View
class MeshView(View):
def __init__(self):
super(MeshView, self).__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
self._renderObject(scene.getRoot(), renderer)
def _renderObject(self, object,... | Allow SceneObjects to render themselves | Allow SceneObjects to render themselves
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | from Cura.View.View import View
class MeshView(View):
def __init__(self):
super(MeshView, self).__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
self._renderObject(scene.getRoot(), renderer)
def _renderObject(self, object,... | Allow SceneObjects to render themselves
from Cura.View.View import View
class MeshView(View):
def __init__(self):
super(MeshView, self).__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
self._renderObject(scene.getRoot(), rende... |
cb3156b5bc279295b5c932a36818d5ed460b31d5 | ynr/urls.py | ynr/urls.py | from __future__ import unicode_literals
import sys
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView
from django.contrib import admin
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
... | from __future__ import unicode_literals
import sys
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView
from django.contrib import admin
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
... | Use getattr in case setting doesn't exist | Use getattr in case setting doesn't exist
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | from __future__ import unicode_literals
import sys
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView
from django.contrib import admin
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
... | Use getattr in case setting doesn't exist
from __future__ import unicode_literals
import sys
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView
from django.contrib import admin
from django.conf.urls.static import static
from django.contrib.stati... |
b167b1c8099dc184c366416dab9a7c6e5be7423a | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... | Handle cases where there are multiple values for a field. | Handle cases where there are multiple values for a field.
| Python | apache-2.0 | Ghalko/osf.io,caneruguz/osf.io,felliott/osf.io,binoculars/osf.io,icereval/osf.io,ticklemepierce/osf.io,caneruguz/osf.io,mattclark/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,laurenrevere/osf.io,aaxelb/osf.io,MerlinZhang/osf.io,caseyrygt/osf.io,doublebits/osf.io,Nesiehr/osf.io,kch8qx/osf.io,acs... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... | Handle cases where there are multiple values for a field.
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when th... |
9bc5ec59224116e2092f0c2e02831c8276360910 | providers/output/terminal.py | providers/output/terminal.py | from __future__ import print_function
import textwrap
from providers.output.provider import OutputProvider
IDENTIFIER = "Terminal"
class Provider(OutputProvider):
def process_data(self, movie_data):
movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data)
... | from __future__ import print_function
import textwrap
from providers.output.provider import OutputProvider
IDENTIFIER = "Terminal"
class Provider(OutputProvider):
def process_data(self, movie_data):
movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data)
... | Sort on imdb rating if filmtipset ratings are the same. | Sort on imdb rating if filmtipset ratings are the same.
| Python | mit | EmilStenstrom/nephele | from __future__ import print_function
import textwrap
from providers.output.provider import OutputProvider
IDENTIFIER = "Terminal"
class Provider(OutputProvider):
def process_data(self, movie_data):
movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data)
... | Sort on imdb rating if filmtipset ratings are the same.
from __future__ import print_function
import textwrap
from providers.output.provider import OutputProvider
IDENTIFIER = "Terminal"
class Provider(OutputProvider):
def process_data(self, movie_data):
movie_data = filter(lambda data: data.get("filmtip... |
9387dfd4cc39fa6fbbf66147ced880dffa6408bd | keystone/server/flask/__init__.py | keystone/server/flask/__init__.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Make keystone.server.flask more interesting for importing | Make keystone.server.flask more interesting for importing
Importing keystone.server.flask now exposes all the relevant bits
from the sub modules to develop APIs without needing to understand
all the underlying modules. __all__ has also be setup in a meaningful
way to allow for `from keystone.server.flask import *` and... | Python | apache-2.0 | openstack/keystone,openstack/keystone,mahak/keystone,openstack/keystone,mahak/keystone,mahak/keystone | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Make keystone.server.flask more interesting for importing
Importing keystone.server.flask now exposes all the relevant bits
from the sub modules to develop APIs without needing to understand
all the underlying modules. __all__ has also be setup in a meaningful
way to allow for `from keystone.server.flask import *` and... |
bdacb16673b2435249ee7cff42a6cc4cacd07e41 | setup.py | setup.py | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.23.0',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager f... | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.23.0',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager f... | Add semver version limit due to compat changes | Add semver version limit due to compat changes
The semver library stopped working for legacy Python versions after the
2.9.1 release. This adds a less than 2.10 restriction to the abstract
dependency requirements so that folks don't need to all add a pin to
their requirements.txt.
| Python | mit | kevinconway/rpmvenv | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.23.0',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager f... | Add semver version limit due to compat changes
The semver library stopped working for legacy Python versions after the
2.9.1 release. This adds a less than 2.10 restriction to the abstract
dependency requirements so that folks don't need to all add a pin to
their requirements.txt.
"""Setuptools configuration for rpmv... |
205324a8fdc9742688952421ed5646877f66f583 | pydub/exceptions.py | pydub/exceptions.py | class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(... | class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(... | Add blank lines to comply with PEP8 | Add blank lines to comply with PEP8
| Python | mit | jiaaro/pydub | class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(... | Add blank lines to comply with PEP8
class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):... |
a9d3f47098bc7499d62d4866883fa45622f01b74 | app/main/errors.py | app/main/errors.py | # coding=utf-8
from flask import render_template, current_app, request
from . import main
from ..helpers.search_helpers import get_template_data
@main.app_errorhandler(404)
def page_not_found(e):
template_data = get_template_data(main, {})
return render_template("errors/404.html", **template_data), 404
@ma... | # coding=utf-8
from flask import render_template, current_app, request
from . import main
from ..helpers.search_helpers import get_template_data
from dmutils.apiclient import APIError
@main.app_errorhandler(APIError)
def api_error_handler(e):
return _render_error_page(e.status_code)
@main.app_errorhandler(404)... | Add API error handling similar to supplier app | Add API error handling similar to supplier app
Currently 404s returned by the API are resulting in 500s on the buyer
app for invalid supplier requests. This change takes the model used in
the supplier frontend to automatically handle uncaught APIErrors. It is
not identical to the supplier app version because the defau... | Python | mit | alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-di... | # coding=utf-8
from flask import render_template, current_app, request
from . import main
from ..helpers.search_helpers import get_template_data
from dmutils.apiclient import APIError
@main.app_errorhandler(APIError)
def api_error_handler(e):
return _render_error_page(e.status_code)
@main.app_errorhandler(404)... | Add API error handling similar to supplier app
Currently 404s returned by the API are resulting in 500s on the buyer
app for invalid supplier requests. This change takes the model used in
the supplier frontend to automatically handle uncaught APIErrors. It is
not identical to the supplier app version because the defau... |
fa609681c2732e655cde9075182af918983ccc1f | photutils/utils/_misc.py | photutils/utils/_misc.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools to return the installed astropy and photutils
versions.
"""
from datetime import datetime, timezone
def _get_version_info():
"""
Return a dictionary of the installed version numbers for photutils
and its depende... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools to return the installed astropy and photutils
versions.
"""
from datetime import datetime, timezone
import sys
def _get_version_info():
"""
Return a dictionary of the installed version numbers for photutils
and ... | Add all optional dependencies to version info dict | Add all optional dependencies to version info dict
| Python | bsd-3-clause | larrybradley/photutils,astropy/photutils | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools to return the installed astropy and photutils
versions.
"""
from datetime import datetime, timezone
import sys
def _get_version_info():
"""
Return a dictionary of the installed version numbers for photutils
and ... | Add all optional dependencies to version info dict
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools to return the installed astropy and photutils
versions.
"""
from datetime import datetime, timezone
def _get_version_info():
"""
Return a dictionary of the install... |
f96d2ceef6b15e397e82e310a3f369f61879a6d0 | ptpython/validator.py | ptpython/validator.py | from __future__ import unicode_literals
from prompt_toolkit.validation import Validator, ValidationError
__all__ = (
'PythonValidator',
)
class PythonValidator(Validator):
"""
Validation of Python input.
:param get_compiler_flags: Callable that returns the currently
active compiler flags.
... | from __future__ import unicode_literals
from prompt_toolkit.validation import Validator, ValidationError
__all__ = (
'PythonValidator',
)
class PythonValidator(Validator):
"""
Validation of Python input.
:param get_compiler_flags: Callable that returns the currently
active compiler flags.
... | Make get_compiler_flags optional for PythonValidator. (Fixes ptipython.) | Make get_compiler_flags optional for PythonValidator. (Fixes ptipython.)
| Python | bsd-3-clause | jonathanslenders/ptpython | from __future__ import unicode_literals
from prompt_toolkit.validation import Validator, ValidationError
__all__ = (
'PythonValidator',
)
class PythonValidator(Validator):
"""
Validation of Python input.
:param get_compiler_flags: Callable that returns the currently
active compiler flags.
... | Make get_compiler_flags optional for PythonValidator. (Fixes ptipython.)
from __future__ import unicode_literals
from prompt_toolkit.validation import Validator, ValidationError
__all__ = (
'PythonValidator',
)
class PythonValidator(Validator):
"""
Validation of Python input.
:param get_compiler_f... |
3c616f21b962218fafd17fcf4a7c673e49566636 | ph_unfolder/analysis/functions.py | ph_unfolder/analysis/functions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
__author__ = "Yuji Ikeda"
import numpy as np
def lorentzian(x, position, width):
return 1.0 / (np.pi * width * (1.0 + ((x - position) / width) ** 2))
def l... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
__author__ = "Yuji Ikeda"
import numpy as np
def lorentzian(x, position, width):
return 1.0 / (np.pi * width * (1.0 + ((x - position) / width) ** 2))
def l... | Fix to give x to lorentzian in lorentzian_unnormalized | Fix to give x to lorentzian in lorentzian_unnormalized
| Python | mit | yuzie007/upho,yuzie007/ph_unfolder | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
__author__ = "Yuji Ikeda"
import numpy as np
def lorentzian(x, position, width):
return 1.0 / (np.pi * width * (1.0 + ((x - position) / width) ** 2))
def l... | Fix to give x to lorentzian in lorentzian_unnormalized
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
__author__ = "Yuji Ikeda"
import numpy as np
def lorentzian(x, position, width):
return 1.0 / (np.pi ... |
5d0fa6d6f66cce56b9704601c4399ca0adcc419a | programmingtheorems/python/theorem_of_selection.py | programmingtheorems/python/theorem_of_selection.py | #! /usr/bin/env python
# Copyright Lajos Katona
#
# 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... | #! /usr/bin/env python
# Copyright Lajos Katona
#
# 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... | Fix pep8 error with new newline | Fix pep8 error with new newline
Change-Id: I47b12c62eb1653bcbbe552464aab72c486bbd1cc
| Python | apache-2.0 | elajkat/hugradexam,elajkat/hugradexam | #! /usr/bin/env python
# Copyright Lajos Katona
#
# 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... | Fix pep8 error with new newline
Change-Id: I47b12c62eb1653bcbbe552464aab72c486bbd1cc
#! /usr/bin/env python
# Copyright Lajos Katona
#
# 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 Licens... |
7784186509e41c72bcf7a4ebbd9b268b49449d35 | user_clipboard/urls.py | user_clipboard/urls.py | from django.conf.urls import patterns, url
from .views import ClipboardFileAPIView, ClipboardImageAPIView
urlpatterns = patterns(
'',
url(r'^images/(?P<pk>\d+)$', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^images/', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(... | from django.conf.urls import url
from .views import ClipboardFileAPIView, ClipboardImageAPIView
urlpatterns = [
url(r'^images/(?P<pk>\d+)$', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^images/', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^(?P<pk>\d+)$', Clipboar... | Define urlpatterns as a pure list (don't call patterns) | Define urlpatterns as a pure list (don't call patterns) | Python | mit | MagicSolutions/django-user-clipboard,IndustriaTech/django-user-clipboard,MagicSolutions/django-user-clipboard,IndustriaTech/django-user-clipboard | from django.conf.urls import url
from .views import ClipboardFileAPIView, ClipboardImageAPIView
urlpatterns = [
url(r'^images/(?P<pk>\d+)$', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^images/', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^(?P<pk>\d+)$', Clipboar... | Define urlpatterns as a pure list (don't call patterns)
from django.conf.urls import patterns, url
from .views import ClipboardFileAPIView, ClipboardImageAPIView
urlpatterns = patterns(
'',
url(r'^images/(?P<pk>\d+)$', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^images/', ClipboardIm... |
d60ce9b23bcf2f8c60b2a8ce75eeba8779345b8b | Orange/tests/__init__.py | Orange/tests/__init__.py | import os
import unittest
from Orange.widgets.tests import test_setting_provider, \
test_settings_handler, test_context_handler, \
test_class_values_context_handler, test_domain_context_handler
from Orange.widgets.data.tests import test_owselectcolumns
try:
from Orange.widgets.tests import test_widget
... | import os
import unittest
from Orange.widgets.tests import test_setting_provider, \
test_settings_handler, test_context_handler, \
test_class_values_context_handler, test_domain_context_handler
from Orange.widgets.data.tests import test_owselectcolumns
try:
from Orange.widgets.tests import test_widget
... | Disable widget test. (does not run on travis) | Disable widget test. (does not run on travis)
| Python | bsd-2-clause | marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,kwikadi/orange3,cheral/orange3,qusp/orange3,marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,qusp/orange3,qPCR4vir/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,cheral/orange3,kwikadi/orange3,qPCR4vir/orange3,qPCR4vir/orange3,q... | import os
import unittest
from Orange.widgets.tests import test_setting_provider, \
test_settings_handler, test_context_handler, \
test_class_values_context_handler, test_domain_context_handler
from Orange.widgets.data.tests import test_owselectcolumns
try:
from Orange.widgets.tests import test_widget
... | Disable widget test. (does not run on travis)
import os
import unittest
from Orange.widgets.tests import test_setting_provider, \
test_settings_handler, test_context_handler, \
test_class_values_context_handler, test_domain_context_handler
from Orange.widgets.data.tests import test_owselectcolumns
try:
f... |
e88a0a27a4960f6b41170cffa0809423987db888 | tests/test_transpiler.py | tests/test_transpiler.py | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except FileNotFoundError:
pass
transpiler.main(["--ou... | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except OSError:
pass
transpiler.main(["--output-dir",... | Fix error testing on python 2.7 | Fix error testing on python 2.7
| Python | mit | WesleyAC/lemonscript-transpiler,WesleyAC/lemonscript-transpiler,WesleyAC/lemonscript-transpiler | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except OSError:
pass
transpiler.main(["--output-dir",... | Fix error testing on python 2.7
import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except FileNotFoundError:
pas... |
9b8d18d52ef6ddd5009a448bcaf003435b387e72 | wake/views.py | wake/views.py | from been.couch import CouchStore
from flask import render_template
from wake import app
store = CouchStore().load()
@app.route('/')
def wake():
return render_template('stream.html', events=store.collapsed_events())
| from been.couch import CouchStore
from flask import render_template, abort
from wake import app
store = CouchStore().load()
@app.route('/')
def wake():
return render_template('stream.html', events=store.collapsed_events())
@app.route('/<slug>')
def by_slug(slug):
events = list(store.events_by_slug(slug))
... | Add by_slug view for single events. | Add by_slug view for single events.
| Python | bsd-3-clause | chromakode/wake | from been.couch import CouchStore
from flask import render_template, abort
from wake import app
store = CouchStore().load()
@app.route('/')
def wake():
return render_template('stream.html', events=store.collapsed_events())
@app.route('/<slug>')
def by_slug(slug):
events = list(store.events_by_slug(slug))
... | Add by_slug view for single events.
from been.couch import CouchStore
from flask import render_template
from wake import app
store = CouchStore().load()
@app.route('/')
def wake():
return render_template('stream.html', events=store.collapsed_events())
|
812fd79675590659b3dc4251ed998f84c4bf2395 | utils.py | utils.py | import os
import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exist... | import os
import sys
import hashlib
def e(s):
if type(s) == str:
return s
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists(... | Fix string encoding when the argument is already a str(). | Fix string encoding when the argument is already a str().
| Python | mit | Stryn/citationhunt,Stryn/citationhunt,Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt | import os
import sys
import hashlib
def e(s):
if type(s) == str:
return s
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists(... | Fix string encoding when the argument is already a str().
import os
import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:... |
897dd874a34ddfc164ea7dbd4bfd5eaffd02aabd | tests/QtUiTools/bug_376.py | tests/QtUiTools/bug_376.py | import unittest
import os
from helper import UsesQApplication
from PySide import QtCore, QtGui
from PySide.QtUiTools import QUiLoader
class BugTest(UsesQApplication):
def testCase(self):
w = QtGui.QWidget()
loader = QUiLoader()
filePath = os.path.join(os.path.dirname(__file__), 'test.ui')... | import unittest
import os
from helper import UsesQApplication
from PySide import QtCore, QtGui
from PySide.QtUiTools import QUiLoader
class BugTest(UsesQApplication):
def testCase(self):
w = QtGui.QWidget()
loader = QUiLoader()
filePath = os.path.join(os.path.dirname(__file__), 'test.ui')... | Replace type() comparison with isinstance. | Replace type() comparison with isinstance.
type() comparison won't work due to weakproxy.
Reviewer: Luciano Wolf <c353ae890f0e6de8473e43011f009ccd38a3c452@openbossa.org>
Reviewer: Hugo Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org>
Reviewer: Renato Filho <16af9705e5a16d85aed275f2f9e8171326ec17f6@openbo... | Python | lgpl-2.1 | gbaty/pyside2,enthought/pyside,RobinD42/pyside,pankajp/pyside,M4rtinK/pyside-android,PySide/PySide,BadSingleton/pyside2,M4rtinK/pyside-bb10,IronManMark20/pyside2,M4rtinK/pyside-android,BadSingleton/pyside2,pankajp/pyside,PySide/PySide,pankajp/pyside,IronManMark20/pyside2,gbaty/pyside2,enthought/pyside,RobinD42/pyside,B... | import unittest
import os
from helper import UsesQApplication
from PySide import QtCore, QtGui
from PySide.QtUiTools import QUiLoader
class BugTest(UsesQApplication):
def testCase(self):
w = QtGui.QWidget()
loader = QUiLoader()
filePath = os.path.join(os.path.dirname(__file__), 'test.ui')... | Replace type() comparison with isinstance.
type() comparison won't work due to weakproxy.
Reviewer: Luciano Wolf <c353ae890f0e6de8473e43011f009ccd38a3c452@openbossa.org>
Reviewer: Hugo Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org>
Reviewer: Renato Filho <16af9705e5a16d85aed275f2f9e8171326ec17f6@openbo... |
7eadc9e514b1311409356f4c6c40ef8cdb2de809 | manager/__init__.py | manager/__init__.py | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_o... | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_o... | Add new stuff to the css bundle | Add new stuff to the css bundle
| Python | mit | hreeder/ignition,hreeder/ignition,hreeder/ignition | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_o... | Add new stuff to the css bundle
import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load... |
4fe72ff427290e845c0259cd1aadf21dd29b9872 | kivy/tests/test_video.py | kivy/tests/test_video.py |
import unittest
class AnimationTestCase(unittest.TestCase):
def test_video_unload(self):
# fix issue https://github.com/kivy/kivy/issues/2275
# AttributeError: 'NoneType' object has no attribute 'texture'
from kivy.uix.video import Video
from kivy.clock import Clock
from ... |
import unittest
class AnimationTestCase(unittest.TestCase):
def test_video_unload(self):
# fix issue https://github.com/kivy/kivy/issues/2275
# AttributeError: 'NoneType' object has no attribute 'texture'
from kivy.uix.video import Video
from kivy.clock import Clock
from ... | Fix path and avi -> mpg. | Fix path and avi -> mpg.
| Python | mit | el-ethan/kivy,angryrancor/kivy,janssen/kivy,rafalo1333/kivy,cbenhagen/kivy,inclement/kivy,Farkal/kivy,jffernandez/kivy,manthansharma/kivy,youprofit/kivy,darkopevec/kivy,jegger/kivy,xiaoyanit/kivy,bob-the-hamster/kivy,Cheaterman/kivy,manthansharma/kivy,LogicalDash/kivy,aron-bordin/kivy,vipulroxx/kivy,andnovar/kivy,iamut... |
import unittest
class AnimationTestCase(unittest.TestCase):
def test_video_unload(self):
# fix issue https://github.com/kivy/kivy/issues/2275
# AttributeError: 'NoneType' object has no attribute 'texture'
from kivy.uix.video import Video
from kivy.clock import Clock
from ... | Fix path and avi -> mpg.
import unittest
class AnimationTestCase(unittest.TestCase):
def test_video_unload(self):
# fix issue https://github.com/kivy/kivy/issues/2275
# AttributeError: 'NoneType' object has no attribute 'texture'
from kivy.uix.video import Video
from kivy.clock ... |
1639a91f018e29c4572242a94c5faf7281b15a6e | netdisco/discoverables/belkin_wemo.py | netdisco/discoverables/belkin_wemo.py | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['... | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['... | Handle mac address missing in early wemo firmware. | Handle mac address missing in early wemo firmware.
| Python | mit | balloob/netdisco,sfam/netdisco,brburns/netdisco | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['... | Handle mac address missing in early wemo firmware.
""" Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a ... |
8d46e411b2e7091fc54c676665905da8ec6906f3 | controllers/dotd.py | controllers/dotd.py | def form():
db.raw_log.uuid.default = uuid_generator()
db.raw_log.date.default = dbdate()
#don't display form items that are part of table, but not facing end user
db.raw_log.uuid.readable = db.raw_log.uuid.writable = False
db.raw_log.date.readable = db.raw_log.date.writable = False
form = SQLFORM(db.raw_log, sho... | def form():
db.raw_log.uuid.default = uuid_generator()
db.raw_log.date.default = dbdate()
#don't display form items that are part of table, but not facing end user
db.raw_log.uuid.readable = db.raw_log.uuid.writable = False
db.raw_log.date.readable = db.raw_log.date.writable = False
if form.accepted:
redirect(U... | Remove selection of all raw_log rows, since it was used for debugging purposes only | Remove selection of all raw_log rows, since it was used for debugging
purposes only
| Python | mit | tsunam/dotd_parser,tsunam/dotd_parser,tsunam/dotd_parser,tsunam/dotd_parser | def form():
db.raw_log.uuid.default = uuid_generator()
db.raw_log.date.default = dbdate()
#don't display form items that are part of table, but not facing end user
db.raw_log.uuid.readable = db.raw_log.uuid.writable = False
db.raw_log.date.readable = db.raw_log.date.writable = False
if form.accepted:
redirect(U... | Remove selection of all raw_log rows, since it was used for debugging
purposes only
def form():
db.raw_log.uuid.default = uuid_generator()
db.raw_log.date.default = dbdate()
#don't display form items that are part of table, but not facing end user
db.raw_log.uuid.readable = db.raw_log.uuid.writable = False
db.raw... |
81b4cd41198edd388d68bf49dfa2a87c43f3357e | joblib/test/test_func_inspect.py | joblib/test/test_func_inspect.py | """
Test the func_inspect module.
"""
# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
# Copyright (c) 2009 Gael Varoquaux
# License: BSD Style, 3 clauses.
import nose
import tempfile
from ..func_inspect import filter_args, get_func_name
from ..memory import Memory
##############################... | Add tests checking that we get the names right. | TEST: Add tests checking that we get the names right.
| Python | bsd-3-clause | tomMoral/joblib,karandesai-96/joblib,aabadie/joblib,joblib/joblib,aabadie/joblib,karandesai-96/joblib,lesteve/joblib,joblib/joblib,tomMoral/joblib,lesteve/joblib | """
Test the func_inspect module.
"""
# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
# Copyright (c) 2009 Gael Varoquaux
# License: BSD Style, 3 clauses.
import nose
import tempfile
from ..func_inspect import filter_args, get_func_name
from ..memory import Memory
##############################... | TEST: Add tests checking that we get the names right.
| |
ad0151eee0027237c8cdd433ef2f24bfa47af5df | pyreaclib/nucdata/tests/test_binding.py | pyreaclib/nucdata/tests/test_binding.py | # unit tests for Binding Energy database taken from AME 2016.
import os
from pyreaclib.nucdata import BindingTable
class TestAME(object):
@classmethod
def setup_class(cls):
""" this is run once for each class before any tests """
pass
@classmethod
def teardown_class(cls):
"""... | # unit tests for Binding Energy database taken from AME 2016.
import os
from pyreaclib.nucdata import BindingTable
class TestAME(object):
@classmethod
def setup_class(cls):
""" this is run once for each class before any tests """
pass
@classmethod
def teardown_class(cls):
"""... | Add some more binding energy table tests. | Add some more binding energy table tests.
| Python | bsd-3-clause | pyreaclib/pyreaclib | # unit tests for Binding Energy database taken from AME 2016.
import os
from pyreaclib.nucdata import BindingTable
class TestAME(object):
@classmethod
def setup_class(cls):
""" this is run once for each class before any tests """
pass
@classmethod
def teardown_class(cls):
"""... | Add some more binding energy table tests.
# unit tests for Binding Energy database taken from AME 2016.
import os
from pyreaclib.nucdata import BindingTable
class TestAME(object):
@classmethod
def setup_class(cls):
""" this is run once for each class before any tests """
pass
@classmeth... |
c46d628449651fde613fb4f7c1829f7770d2e353 | django-server/feel/core/db/load_fixtures.py | django-server/feel/core/db/load_fixtures.py | import subprocess
from django.conf import settings
MY_APPS = settings.MY_APPS
COMMAND_FORMAT = "python manage.py loaddata core/fixtures/{app}.json"
def load_fixtures():
for app in MY_APPS:
command = COMMAND_FORMAT.format(app=app)
print(command)
subprocess.check_output(command, shell=True)... | Add script to load fixtures into tables. | Fixtures: Add script to load fixtures into tables.
| Python | mit | pixyj/feel,pixyj/feel,pixyj/feel,pixyj/feel,pixyj/feel | import subprocess
from django.conf import settings
MY_APPS = settings.MY_APPS
COMMAND_FORMAT = "python manage.py loaddata core/fixtures/{app}.json"
def load_fixtures():
for app in MY_APPS:
command = COMMAND_FORMAT.format(app=app)
print(command)
subprocess.check_output(command, shell=True)... | Fixtures: Add script to load fixtures into tables.
| |
b6deb0495f1a31801d95e2d59de7ea2731eb8970 | home/bin/h2t.py | home/bin/h2t.py | import argparse
import html2text
import pypandoc
def main():
p = argparse.ArgumentParser()
h = html2text.HTML2Text()
p.add_argument("filename")
filename = p.parse_args().filename
h.ignore_emphasis = True
h.body_width = 0
h.use_automatic_links = False
h.wrap_links = False
h.single_... | Add html to text script | Add html to text script
| Python | mit | dahlbaek/Ubuntu-dotfiles | import argparse
import html2text
import pypandoc
def main():
p = argparse.ArgumentParser()
h = html2text.HTML2Text()
p.add_argument("filename")
filename = p.parse_args().filename
h.ignore_emphasis = True
h.body_width = 0
h.use_automatic_links = False
h.wrap_links = False
h.single_... | Add html to text script
| |
7d2277685a125e4ee2b57ed7782bcae62f64464b | matrix/example.py | matrix/example.py | class Matrix(object):
def __init__(self, s):
self.rows = [[int(n) for n in row.split()]
for row in s.split('\n')]
@property
def columns(self):
return map(list, zip(*self.rows))
| class Matrix(object):
def __init__(self, s):
self.rows = [[int(n) for n in row.split()]
for row in s.split('\n')]
@property
def columns(self):
return [list(tup) for tup in zip(*self.rows)]
| Make matrix exercise compatible with Python3 | Make matrix exercise compatible with Python3
| Python | mit | exercism/python,pombredanne/xpython,outkaj/xpython,behrtam/xpython,smalley/python,orozcoadrian/xpython,orozcoadrian/xpython,exercism/xpython,ZacharyRSmith/xpython,de2Zotjes/xpython,oalbe/xpython,jmluy/xpython,N-Parsons/exercism-python,pheanex/xpython,behrtam/xpython,exercism/python,pombredanne/xpython,wobh/xpython,jmlu... | class Matrix(object):
def __init__(self, s):
self.rows = [[int(n) for n in row.split()]
for row in s.split('\n')]
@property
def columns(self):
return [list(tup) for tup in zip(*self.rows)]
| Make matrix exercise compatible with Python3
class Matrix(object):
def __init__(self, s):
self.rows = [[int(n) for n in row.split()]
for row in s.split('\n')]
@property
def columns(self):
return map(list, zip(*self.rows))
|
30459a1552b5b90ec5469bbae85510ef3224ccac | stored_messages/models.py | stored_messages/models.py | from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
from .compat import AUTH_USER_MODEL
from .settings import stored_messages_settings
INBOX_EXPIRE_DAYS = 30 # TODO move to settings
@python_2_unicode_compatible
class Message(models.Model):
... | from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from .compat import AUTH_USER_MODEL
from .settings import stored_messages_settings
INBOX_EXPIRE_DAYS = 30 # TODO move to settings
@pyt... | Add Verbose name plurar for inbox and __str__ method | Add Verbose name plurar for inbox and __str__ method
| Python | bsd-3-clause | nthall/django-stored-messages,evonove/django-stored-messages,evonove/django-stored-messages,xrmx/django-stored-messages,b0bbywan/django-stored-messages,nthall/django-stored-messages,b0bbywan/django-stored-messages,xrmx/django-stored-messages | from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from .compat import AUTH_USER_MODEL
from .settings import stored_messages_settings
INBOX_EXPIRE_DAYS = 30 # TODO move to settings
@pyt... | Add Verbose name plurar for inbox and __str__ method
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
from .compat import AUTH_USER_MODEL
from .settings import stored_messages_settings
INBOX_EXPIRE_DAYS = 30 # TODO move to settings
@pytho... |
4f1124c7526ee1d30f0de180d459f42d716ad2c8 | setup.py | setup.py | #from distutils.core import setup
from setuptools import setup
descr = """Tree representations and algorithms for Python.
Viridis is named after the green tree python, Morelia viridis.
"""
DISTNAME = 'viridis'
DESCRIPTION = 'Tree data structures and algorithms'
LONG_DESCRIPTION = descr
MAINTAIN... | #from distutils.core import setup
from setuptools import setup
descr = """Tree representations and algorithms for Python.
Viridis is named after the green tree python, Morelia viridis.
"""
DISTNAME = 'viridis'
DESCRIPTION = 'Tree data structures and algorithms'
LONG_DESCRIPTION = descr
MAINTAIN... | Update master version to 0.3-dev | Update master version to 0.3-dev
| Python | mit | jni/viridis | #from distutils.core import setup
from setuptools import setup
descr = """Tree representations and algorithms for Python.
Viridis is named after the green tree python, Morelia viridis.
"""
DISTNAME = 'viridis'
DESCRIPTION = 'Tree data structures and algorithms'
LONG_DESCRIPTION = descr
MAINTAIN... | Update master version to 0.3-dev
#from distutils.core import setup
from setuptools import setup
descr = """Tree representations and algorithms for Python.
Viridis is named after the green tree python, Morelia viridis.
"""
DISTNAME = 'viridis'
DESCRIPTION = 'Tree data structures and algorithms'
LO... |
df5594e3da75ecd7f5ab6d112d22e5da628a3ccf | onepercentclub/settings/travis.py | onepercentclub/settings/travis.py | # TODO: not sure why but we need to include the SECRET_KEY here - importing from the test_runner file doesn't work
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
from .test_runner import *
# Use firefox for running tests on Travis
SELENIUM_WEBDRIVER = 'remote'
SELENIUM_TESTS = False
ROOT_UR... | # TODO: not sure why but we need to include the SECRET_KEY here - importing from the test_runner file doesn't work
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
from .test_runner import *
# Use firefox for running tests on Travis
SELENIUM_WEBDRIVER = 'firefox'
SELENIUM_TESTS = False
ROOT_U... | Use FF as test browser in Travis | Use FF as test browser in Travis
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site | # TODO: not sure why but we need to include the SECRET_KEY here - importing from the test_runner file doesn't work
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
from .test_runner import *
# Use firefox for running tests on Travis
SELENIUM_WEBDRIVER = 'firefox'
SELENIUM_TESTS = False
ROOT_U... | Use FF as test browser in Travis
# TODO: not sure why but we need to include the SECRET_KEY here - importing from the test_runner file doesn't work
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
from .test_runner import *
# Use firefox for running tests on Travis
SELENIUM_WEBDRIVER = 'remot... |
a4a50e2043bf49b867cc80d9b7d55333d6e0cffa | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name = 'tentd',
version = "0.0.0",
author = 'James Ravenscroft',
url = 'https://github.com/ravenscroftj/pytentd',
description = 'An implementation of the http://tent.io server protocol',
long_description = open(... | from setuptools import setup, find_packages
setup(
name = 'tentd',
version = "0.0.0",
author = 'James Ravenscroft',
url = 'https://github.com/ravenscroftj/pytentd',
description = 'An implementation of the http://tent.io server protocol',
long_description = open(... | Allow tentd to be run from the command line | Allow tentd to be run from the command line
| Python | apache-2.0 | pytent/pytentd | from setuptools import setup, find_packages
setup(
name = 'tentd',
version = "0.0.0",
author = 'James Ravenscroft',
url = 'https://github.com/ravenscroftj/pytentd',
description = 'An implementation of the http://tent.io server protocol',
long_description = open(... | Allow tentd to be run from the command line
from setuptools import setup, find_packages
setup(
name = 'tentd',
version = "0.0.0",
author = 'James Ravenscroft',
url = 'https://github.com/ravenscroftj/pytentd',
description = 'An implementation of the http://tent.i... |
3ef0c6adcfa74877245f586618c4592b308976cd | openapi_core/wrappers/flask.py | openapi_core/wrappers/flask.py | """OpenAPI core wrappers module"""
from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse
class FlaskOpenAPIRequest(BaseOpenAPIRequest):
def __init__(self, request):
self.request = request
@property
def host_url(self):
return self.request.host_url
@property
... | """OpenAPI core wrappers module"""
import re
from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse
# http://flask.pocoo.org/docs/1.0/quickstart/#variable-rules
PATH_PARAMETER_PATTERN = r'<(?:(?:string|int|float|path|uuid):)?(\w+)>'
class FlaskOpenAPIRequest(BaseOpenAPIRequest):
path_re... | Convert Flask path variables to OpenAPI path parameters | Convert Flask path variables to OpenAPI path parameters
| Python | bsd-3-clause | p1c2u/openapi-core | """OpenAPI core wrappers module"""
import re
from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse
# http://flask.pocoo.org/docs/1.0/quickstart/#variable-rules
PATH_PARAMETER_PATTERN = r'<(?:(?:string|int|float|path|uuid):)?(\w+)>'
class FlaskOpenAPIRequest(BaseOpenAPIRequest):
path_re... | Convert Flask path variables to OpenAPI path parameters
"""OpenAPI core wrappers module"""
from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse
class FlaskOpenAPIRequest(BaseOpenAPIRequest):
def __init__(self, request):
self.request = request
@property
def host_url(sel... |
ab78bf2c47a8bec5c1d0c5a7951dba1c98f5c28e | check_gm.py | check_gm.py | #!/usr/bin/env python3
# vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab
import os, sys
import sqlite3
import urllib.request
err = False
for version in range (7, 14):
fname = 'tables_v1.sql' if version < 12 else 'tables.sql'
url = 'https://cdn.jsdelivr.net/gh/moneymanagerex/database@v%i/... | #!/usr/bin/env python3
# vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab
import os, sys
import sqlite3
import urllib.request
err = False
for version in range (7, 14):
fname = 'tables_v1.sql' if version < 12 else 'tables.sql'
url = 'https://cdn.jsdelivr.net/gh/moneymanagerex/database@v%i/... | Revert file to moneymanager master branch. | Revert file to moneymanager master branch.
| Python | mit | moneymanagerex/general-reports,moneymanagerex/general-reports | #!/usr/bin/env python3
# vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab
import os, sys
import sqlite3
import urllib.request
err = False
for version in range (7, 14):
fname = 'tables_v1.sql' if version < 12 else 'tables.sql'
url = 'https://cdn.jsdelivr.net/gh/moneymanagerex/database@v%i/... | Revert file to moneymanager master branch.
#!/usr/bin/env python3
# vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab
import os, sys
import sqlite3
import urllib.request
err = False
for version in range (7, 14):
fname = 'tables_v1.sql' if version < 12 else 'tables.sql'
url = 'https://cdn.... |
52f38cd00db200d0520062c27f0d305827edb7d2 | eventkit_cloud/auth/models.py | eventkit_cloud/auth/models.py | from django.contrib.auth.models import User,Group
from django.db import models
from django.contrib.postgres.fields import JSONField
from ..core.models import TimeStampedModelMixin, UIDMixin
class OAuth(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False)
identification = mod... | from django.contrib.auth.models import User,Group
from django.db import models
from django.contrib.postgres.fields import JSONField
from ..core.models import TimeStampedModelMixin, UIDMixin
class OAuth(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False)
identification = mod... | Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted." | Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted."
This reverts commit 4c77c36f447d104f492e320ca684e9a737f2b803.
| Python | bsd-3-clause | venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud | from django.contrib.auth.models import User,Group
from django.db import models
from django.contrib.postgres.fields import JSONField
from ..core.models import TimeStampedModelMixin, UIDMixin
class OAuth(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False)
identification = mod... | Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted."
This reverts commit 4c77c36f447d104f492e320ca684e9a737f2b803.
from django.contrib.auth.models import User,Group
from django.db import models
from django.contrib.postgres.fields import JSONField
from ..core.mo... |
1d729ada6c81cdf75c6f76b996337e46d7b679a0 | setup.py | setup.py | #!/usr/bin/env python
# encoding: utf8
import platform
import os
system = platform.system()
from distutils.core import setup
setup(
name='matlab2cpp',
version='0.2',
packages=['matlab2cpp', 'matlab2cpp.translations',
'matlab2cpp.testsuite', 'matlab2cpp.inlines'],
package_dir={'': 'src'... | #!/usr/bin/env python
# encoding: utf8
import platform
import os
system = platform.system()
from distutils.core import setup
setup(
name='matlab2cpp',
version='0.2',
packages=['matlab2cpp', 'matlab2cpp.translations',
'matlab2cpp.testsuite', 'matlab2cpp.inlines'],
package_dir={'': 'src'... | Change mode of mconvert to be globaly executable | Change mode of mconvert to be globaly executable
| Python | bsd-3-clause | jonathf/matlab2cpp,jonathf/matlab2cpp,jonathf/matlab2cpp | #!/usr/bin/env python
# encoding: utf8
import platform
import os
system = platform.system()
from distutils.core import setup
setup(
name='matlab2cpp',
version='0.2',
packages=['matlab2cpp', 'matlab2cpp.translations',
'matlab2cpp.testsuite', 'matlab2cpp.inlines'],
package_dir={'': 'src'... | Change mode of mconvert to be globaly executable
#!/usr/bin/env python
# encoding: utf8
import platform
import os
system = platform.system()
from distutils.core import setup
setup(
name='matlab2cpp',
version='0.2',
packages=['matlab2cpp', 'matlab2cpp.translations',
'matlab2cpp.testsuite',... |
1504710d748a86bbd4eed717b4bcc2f5d15ec1b7 | SatNOGS/base/management/commands/initialize.py | SatNOGS/base/management/commands/initialize.py | from orbit import satellite
from django.core.management.base import BaseCommand
from base.tests import ObservationFactory, StationFactory
from base.models import Satellite
class Command(BaseCommand):
help = 'Create initial fixtures'
def handle(self, *args, **options):
ObservationFactory.create_batc... | from orbit import satellite
from django.core.management.base import BaseCommand
from base.tests import ObservationFactory, StationFactory
from base.models import Satellite
class Command(BaseCommand):
help = 'Create initial fixtures'
def handle(self, *args, **options):
ObservationFactory.create_batc... | Use more sane numbers for initial data | Use more sane numbers for initial data
| Python | agpl-3.0 | cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network | from orbit import satellite
from django.core.management.base import BaseCommand
from base.tests import ObservationFactory, StationFactory
from base.models import Satellite
class Command(BaseCommand):
help = 'Create initial fixtures'
def handle(self, *args, **options):
ObservationFactory.create_batc... | Use more sane numbers for initial data
from orbit import satellite
from django.core.management.base import BaseCommand
from base.tests import ObservationFactory, StationFactory
from base.models import Satellite
class Command(BaseCommand):
help = 'Create initial fixtures'
def handle(self, *args, **options)... |
713b05e49b814a2a924f657294352bc5e7061638 | tools/chrome_proxy/integration_tests/chrome_proxy_pagesets/reenable_after_bypass.py | tools/chrome_proxy/integration_tests/chrome_proxy_pagesets/reenable_after_bypass.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry import story
class ReenableAfterBypassPage(page_module.Page):
"""A test page for the re-ena... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry import story
class ReenableAfterBypassPage(page_module.Page):
"""A test page for the re-ena... | Add trailing slash to chrome_proxy telemetry test page URL. | Add trailing slash to chrome_proxy telemetry test page URL.
BUG=507797
Review URL: https://codereview.chromium.org/1229563002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#337895}
| Python | bsd-3-clause | hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,axingi... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry import story
class ReenableAfterBypassPage(page_module.Page):
"""A test page for the re-ena... | Add trailing slash to chrome_proxy telemetry test page URL.
BUG=507797
Review URL: https://codereview.chromium.org/1229563002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#337895}
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style licens... |
e63a9430d9ad4d6bbfd6af66b1de617e71490c2c | countylimits/views.py | countylimits/views.py | from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from countylimits.models import CountyLimit
@api_view(['GET'])
def county_limits(request):
""" Return all counties with their limits per state. """
... | from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from countylimits.models import CountyLimit
@api_view(['GET'])
def county_limits(request):
""" Return all counties with their limits per state. """
... | Return 400 when state is invalid | Return 400 when state is invalid
| Python | cc0-1.0 | amymok/owning-a-home-api,cfpb/owning-a-home-api,fna/owning-a-home-api | from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from countylimits.models import CountyLimit
@api_view(['GET'])
def county_limits(request):
""" Return all counties with their limits per state. """
... | Return 400 when state is invalid
from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from countylimits.models import CountyLimit
@api_view(['GET'])
def county_limits(request):
""" Return all counties w... |
d6c493df4df06f5195c1f964224728ca4e5ace06 | django_project/realtime/management/commands/loadfloodtestdata.py | django_project/realtime/management/commands/loadfloodtestdata.py | # coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"""Script to load flood test data for de... | # coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"""Script to load flood test data for de... | Fix wrong path to flood data to push. | Fix wrong path to flood data to push.
| Python | bsd-2-clause | AIFDR/inasafe-django,AIFDR/inasafe-django,AIFDR/inasafe-django,AIFDR/inasafe-django | # coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"""Script to load flood test data for de... | Fix wrong path to flood data to push.
# coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"... |
ebf89478f7c841ee7d61a4081d4d6ba2f2cabe05 | app/main/auth.py | app/main/auth.py | from functools import wraps
from flask import abort
from flask_login import current_user
def role_required(*roles):
"""Ensure that logged in user has one of the required roles.
Return 403 if the user doesn't have a required role.
Should be applied before the `@login_required` decorator:
@login... | Add `role_required` view decorator to check current_user role | Add `role_required` view decorator to check current_user role
Returns 403 if user has none of the roles listed in the decorator
arguments.
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend | from functools import wraps
from flask import abort
from flask_login import current_user
def role_required(*roles):
"""Ensure that logged in user has one of the required roles.
Return 403 if the user doesn't have a required role.
Should be applied before the `@login_required` decorator:
@login... | Add `role_required` view decorator to check current_user role
Returns 403 if user has none of the roles listed in the decorator
arguments.
| |
31691ca909fe0b1816d89bb4ccf69974eca882a6 | allauth/app_settings.py | allauth/app_settings.py | import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS
def check_context_processors():
allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
ctx_present = False
if ... | import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django import template
SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS
def check_context_processors():
allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
... | Fix for checking the context processors on Django 1.8 | Fix for checking the context processors on Django 1.8
If the user has not migrated their settings file to use the new TEMPLATES
method in Django 1.8, settings.TEMPLATES is an empty list.
Instead, if we check django.templates.engines it will be populated with the
automatically migrated data from settings.TEMPLATE*.
| Python | mit | cudadog/django-allauth,bitcity/django-allauth,petersanchez/django-allauth,bittner/django-allauth,manran/django-allauth,jscott1989/django-allauth,petersanchez/django-allauth,JshWright/django-allauth,italomaia/django-allauth,yarbelk/django-allauth,pankeshang/django-allauth,sih4sing5hong5/django-allauth,ZachLiuGIS/django-... | import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django import template
SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS
def check_context_processors():
allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
... | Fix for checking the context processors on Django 1.8
If the user has not migrated their settings file to use the new TEMPLATES
method in Django 1.8, settings.TEMPLATES is an empty list.
Instead, if we check django.templates.engines it will be populated with the
automatically migrated data from settings.TEMPLATE*.
i... |
ef37001c97f83d39e8e9998a8f7d1d6db75b1e0b | examples/graph/degree_sequence.py | examples/graph/degree_sequence.py | #!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Sc... | #!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Sc... | Remove Python 3 incompatible print statement | Remove Python 3 incompatible print statement
| Python | bsd-3-clause | goulu/networkx,harlowja/networkx,sharifulgeo/networkx,bzero/networkx,RMKD/networkx,ionanrozenfeld/networkx,bzero/networkx,blublud/networkx,SanketDG/networkx,jakevdp/networkx,farhaanbukhsh/networkx,nathania/networkx,RMKD/networkx,cmtm/networkx,aureooms/networkx,JamesClough/networkx,chrisnatali/networkx,beni55/networkx,f... | #!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Sc... | Remove Python 3 incompatible print statement
#!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# ... |
7405c342522cf3686b5946fb30a59c74c410c655 | tests/site/pages/migrations/0002_regularpage.py | tests/site/pages/migrations/0002_regularpage.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-02 04:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0033_remov... | Add missing migration for tests.app.pages (fixes build) | Add missing migration for tests.app.pages (fixes build)
| Python | mit | LabD/wagtail-personalisation,LabD/wagtail-personalisation,LabD/wagtail-personalisation | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-02 04:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0033_remov... | Add missing migration for tests.app.pages (fixes build)
| |
58bee0ac0df709f9a5cee83e7828dce148182d10 | tests/v6/test_tee_generator.py | tests/v6/test_tee_generator.py | from .context import tohu
from tohu.v6.primitive_generators import Integer, TimestampPrimitive
from tohu.v6.derived_generators import IntegerDerived, Tee
from tohu.v6.derived_generators_v2 import TimestampDerived
from tohu.v6.custom_generator import CustomGenerator
def test_tee_generator():
class QuuxGenerator(C... | Add a few tests for Tee | Add a few tests for Tee
| Python | mit | maxalbert/tohu | from .context import tohu
from tohu.v6.primitive_generators import Integer, TimestampPrimitive
from tohu.v6.derived_generators import IntegerDerived, Tee
from tohu.v6.derived_generators_v2 import TimestampDerived
from tohu.v6.custom_generator import CustomGenerator
def test_tee_generator():
class QuuxGenerator(C... | Add a few tests for Tee
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.