commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
c88b060e216b494d893a1cf50de4e85b276740c1 | setup.py | setup.py | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
from eodatasets import __version__ as version
# Append TeamCity build number if it gives us one.
if 'BUILD_NUMBER' in os.environ and version.endswith('b'):
version += '' + os.environ['BUILD_NUMBER']
setup(
name="eodatasets",
ver... | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
from eodatasets import __version__ as version
# Append TeamCity build number if it gives us one.
if 'BUILD_NUMBER' in os.environ and version.endswith('b'):
version += '' + os.environ['BUILD_NUMBER']
setup(
name="eodatasets",
ver... | Exclude test package from builds. | Exclude test package from builds.
| Python | apache-2.0 | jeremyh/eo-datasets,GeoscienceAustralia/eo-datasets,GeoscienceAustralia/eo-datasets,jeremyh/eo-datasets | ---
+++
@@ -12,7 +12,7 @@
setup(
name="eodatasets",
version=version,
- packages=find_packages(),
+ packages=find_packages(exclude=('tests', 'tests.*')),
install_requires=[
'click',
'python-dateutil', |
ff029b3cd79ab3f68ed5fc56be069e29580d5b46 | setup.py | setup.py | #!/usr/bin/env python
import os
from numpy.distutils.core import setup, Extension
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
wrapper = Extension('fortran_routines',
sources=['src/fortran_routines.f90'],
... | #!/usr/bin/env python
import os
from numpy.distutils.core import setup, Extension
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
wrapper = Extension('fortran_routines',
sources=['src/fortran_routines.f90'],
... | Add a dependency on healpy | Add a dependency on healpy
| Python | mit | ziotom78/stripeline,ziotom78/stripeline | ---
+++
@@ -19,6 +19,6 @@
url='https://github.com/ziotom78/stripsim',
long_description=read('README.md'),
py_modules=['src/stripsim'],
- install_requires=['pyyaml'],
+ install_requires=['healpy', 'pyyaml'],
ext_modules=[wrapper]
) |
472b0a0ba90054f151a60e200902b67223fbf6d9 | setup.py | setup.py | from distutils.core import setup
from setuptools.command.install import install
try:
description = open('README.txt').read()
except:
description = open('README.md').read()
setup(
name='python-ldap-test',
version='0.2.2',
author='Adrian Gruntkowski',
author_email='adrian.gruntkowski@gmail.com... | import codecs
from distutils.core import setup
def read(fname):
'''
Read a file from the directory where setup.py resides
'''
with codecs.open(fname, encoding='utf-8') as rfh:
return rfh.read()
try:
description = read('README.txt')
except:
description = read('README.md')
setup(
... | Fix installation on systems where locales are not properly configured | Fix installation on systems where locales are not properly configured
| Python | mit | zoldar/python-ldap-test,zoldar/python-ldap-test | ---
+++
@@ -1,11 +1,18 @@
+import codecs
from distutils.core import setup
-from setuptools.command.install import install
+def read(fname):
+ '''
+ Read a file from the directory where setup.py resides
+ '''
+ with codecs.open(fname, encoding='utf-8') as rfh:
+ return rfh.read()
+
try:
- d... |
0466ed83bdf9a84f01235339aef7505d26d6df3a | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='manifold',
version='1.0.0',
packages=find_packages(include=('manifold', 'manifold.*')),
long_description=open('README.md').read(),
include_package_data=True,
install_requires=(
'numpy',
'scipy',
'matplotlib',
... | from setuptools import setup, find_packages
setup(
name='manifold',
version='1.0.0',
packages=find_packages(include=('manifold', 'manifold.*')),
long_description=open('README.md').read(),
include_package_data=True,
install_requires=(
'numpy',
'scipy',
'matplotlib',
... | Add scipy to project requirements list | Add scipy to project requirements list
| Python | mit | lucasdavid/Manifold-Learning,lucasdavid/Manifold-Learning | ---
+++
@@ -27,5 +27,5 @@
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.4',
'Topic :: Manifold Learning',
- ], requires=['networkx', 'numpy', 'sklearn', 'matplotlib']
+ ], requires=['networkx', 'numpy', 'sklearn', 'matplotlib', 'scipy']
) |
bfbe4f0a2fa231b22f6ebaae3eb1065565ab66e4 | setup.py | setup.py | # -*- coding: utf-8 -*-
"""
setup
:copyright: (c) 2012-2014 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
from setuptools import setup
setup(name='trytond_sentry',
version='3.0.1.0',
description='Sentry Client for Tryton',
long_description... | # -*- coding: utf-8 -*-
"""
setup
:copyright: (c) 2012-2014 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
from setuptools import setup
setup(name='trytond_sentry',
version='3.0.1.0',
description='Sentry Client for Tryton',
long_description... | Set homepage for package as github url | Set homepage for package as github url
| Python | bsd-3-clause | fulfilio/trytond-sentry | ---
+++
@@ -13,7 +13,7 @@
long_description=open('README.rst').read(),
author="Openlabs Technologies & Consulting (P) Limited",
author_email="info@openlabs.co.in",
- url="http://www.openlabs.co.in",
+ url="https://github.com/openlabs/trytond-sentry",
package_dir={'trytond_sentry': '.'},
... |
1ad58abffb5b9f768a916620e503b2511509fba5 | setup.py | setup.py | import codecs
from os import path
from setuptools import find_packages, setup
def read(*parts):
filename = path.join(path.dirname(__file__), *parts)
with codecs.open(filename, encoding="utf-8") as fp:
return fp.read()
setup(
author="Pinax Developers",
author_email="developers@pinaxproject.c... | import codecs
from os import path
from setuptools import find_packages, setup
def read(*parts):
filename = path.join(path.dirname(__file__), *parts)
with codecs.open(filename, encoding="utf-8") as fp:
return fp.read()
setup(
author="Pinax Developers",
author_email="developers@pinaxproject.c... | Update test requirement for PTB | Update test requirement for PTB
| Python | mit | eldarion/user_messages,pinax/pinax-messages,pinax/pinax-messages,eldarion/user_messages | ---
+++
@@ -26,7 +26,7 @@
test_suite="runtests.runtests",
tests_require=[
"django-test-plus>=1.0.11",
- "pinax-theme-bootstrap>=7.10.0",
+ "pinax-theme-bootstrap>=7.10.1",
],
install_requires=[
"django-appconf>=1.0.1", |
674dd25bebb21919c27cb78bef2cee2f59f0c922 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
import py2exe
setup(console=['CryptoUnLocker.py'])
| #!/usr/bin/env python
import sys
from cx_Freeze import setup, Executable
setup(
name="CryptoUnLocker",
version="1.0",
Description="Detection and Decryption tool for CryptoLocker files",
executables= [Executable("CryptoUnLocker.py")]
)
| Switch from py2exe to cx_Freeze | Switch from py2exe to cx_Freeze
py2exe had issues with pycrypto. cx_Freeze seems to work.
| Python | mit | kyrus/crypto-un-locker,thecocce/crypto-un-locker | ---
+++
@@ -1,6 +1,11 @@
#!/usr/bin/env python
-from distutils.core import setup
-import py2exe
+import sys
+from cx_Freeze import setup, Executable
-setup(console=['CryptoUnLocker.py'])
+setup(
+ name="CryptoUnLocker",
+ version="1.0",
+ Description="Detection and Decryption tool for CryptoLocker files",
+ exec... |
35e5643db16e2da200c9151b6d6fc53ea2096944 | setup.py | setup.py | from setuptools import setup
setup(name='polycircles',
version='0.1',
description='Polycircles: WGS84 Circle approximations using polygons',
url='http://github.com/vioozer/servers',
author='Adam Matan',
author_email='adam@matan.name',
license='MIT',
packages=['polycircles'],
... | from setuptools import setup
setup(name='polycircles',
version='0.1',
description='Polycircles: WGS84 Circle approximations using polygons',
url='http://github.com/vioozer/servers',
author='Adam Matan',
author_email='adam@matan.name',
license='MIT',
packages=['polycircles'],
... | Reduce nose version to 1.3.0 for Travis CI. | Reduce nose version to 1.3.0 for Travis CI.
| Python | mit | adamatan/polycircles | ---
+++
@@ -10,6 +10,6 @@
packages=['polycircles'],
include_package_data=True,
install_requires=['geographiclib'],
- tests_require=['geopy >= 0.99', 'nose >= 1.3.1'],
+ tests_require=['geopy >= 0.99', 'nose >= 1.3.0'],
test_suite='polycircles.test',
zip_safe=False) |
3ca6feb2d20e6f3d8051a872ccba8a747e31bc51 | setup.py | setup.py | #!/usr/bin/env python
import sys
import os
from distutils.core import setup
sys.path.insert(0, os.path.dirname(__file__))
from wutils import get_version, generate_version_py
generate_version_py(force=False)
setup(name='pybindgen',
version=get_version(),
description='Python Bindings Generator',
autho... | #!/usr/bin/env python
import sys
import os
from distutils.core import setup
sys.path.insert(0, os.path.dirname(__file__))
from wutils import get_version, generate_version_py
generate_version_py(force=False)
setup(name='PyBindGen',
version=get_version(),
description='Python Bindings Generator',
autho... | Revert back to PyBindGen as package name because it's what is already registered in PyPI. | Revert back to PyBindGen as package name because it's what is already registered in PyPI.
| Python | lgpl-2.1 | gjcarneiro/pybindgen,gjcarneiro/pybindgen,ftalbrecht/pybindgen,ftalbrecht/pybindgen,gjcarneiro/pybindgen,ftalbrecht/pybindgen,gjcarneiro/pybindgen,ftalbrecht/pybindgen | ---
+++
@@ -7,7 +7,7 @@
from wutils import get_version, generate_version_py
generate_version_py(force=False)
-setup(name='pybindgen',
+setup(name='PyBindGen',
version=get_version(),
description='Python Bindings Generator',
author='Gustavo Carneiro', |
a12bdf5b8ffa0b43fdd0b1ad9b49b47e09815c9c | pymsascoring/score/score.py | pymsascoring/score/score.py | import logging
__author__ = "Antonio J. Nebro"
__license__ = "GPL"
__version__ = "1.0-SNAPSHOT"
__status__ = "Development"
__email__ = "antonio@lcc.uma.es"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Score:
""" Class representing MSA (Multiple Sequence Alignment) scores
... | import logging
__author__ = "Antonio J. Nebro"
__license__ = "GPL"
__version__ = "1.0-SNAPSHOT"
__status__ = "Development"
__email__ = "antonio@lcc.uma.es"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Score:
""" Class representing MSA (Multiple Sequence Alignment) scores
... | Check if all sequences are of the same length | Check if all sequences are of the same length
| Python | mit | ajnebro/pyMSAScoring | ---
+++
@@ -33,7 +33,7 @@
""" Get the sequences from an msa.
:param msa: Python list containing pairs of (identifier, sequence)
- :return: List of sequences (i.e. "('AB', 'CD', 'EF' )").
+ :return: List of sequences (i.e. "('AB', 'CD', 'EF' )") if all sequences are of the same length... |
8162cf98f04125b7db1460a42a177eae516660d0 | appliance/getready.py | appliance/getready.py | # -*- coding: utf-8 -*-
import RPi.GPIO as gpio
pin_power=12
pin_light=16
# Setup
gpio.setmode(gpio.BOARD)
gpio.setup(pin_power, gpio.OUT)
gpio.setup(pin_light, gpio.OUT)
gpio.output(pin_power, gpio.HIGH)
gpio.output(pin_light, gpio.LOW)
| # -*- coding: utf-8 -*-
import RPi.GPIO as gpio
pin_power=3
pin_light=5
# Setup
gpio.setmode(gpio.BOARD)
gpio.setup(pin_power, gpio.OUT)
gpio.setup(pin_light, gpio.OUT)
gpio.output(pin_power, gpio.HIGH)
gpio.output(pin_light, gpio.LOW)
| Modify the pin number due to the hardware case | Modify the pin number due to the hardware case
| Python | apache-2.0 | kensonman/IMCSmartHome,kensonman/IMCSmartHome,kensonman/IMCSmartHome | ---
+++
@@ -2,8 +2,8 @@
import RPi.GPIO as gpio
-pin_power=12
-pin_light=16
+pin_power=3
+pin_light=5
# Setup
gpio.setmode(gpio.BOARD) |
3e689dc769bd4859b4ed73e98d8d559710aa2e14 | tools/perf/profile_creators/small_profile_creator.py | tools/perf/profile_creators/small_profile_creator.py | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from telemetry.core import util
from telemetry.page import page_set
from telemetry.page import profile_creator
class SmallProfileCreator(pro... | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from telemetry.core import util
from telemetry.page import page_set
from telemetry.page import profile_creator
class SmallProfileCreator(pro... | Make profile generator wait for pages to load completely. | [Telemetry] Make profile generator wait for pages to load completely.
The bug that causes this not to work is fixed. It is possible that this
non-determinism in the profile could lead to flakiness in the session_restore
benchmark.
BUG=375979
Review URL: https://codereview.chromium.org/318733002
git-svn-id: de016e52... | Python | bsd-3-clause | hgl888/chromium-crosswalk-efl,littlstar/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,jaruba/chromium.src,dushu1203/chromium.src,Chilledheart/chr... | ---
+++
@@ -32,6 +32,4 @@
return browser.tabs.New()
def MeasurePage(self, _, tab, results):
- # Can't use WaitForDocumentReadyStateToBeComplete() here due to
- # crbug.com/280750 .
- tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
+ tab.WaitForDocumentReadyStateToBeComplete() |
a61363b23c2fee99c7420cf2371a2711b3bc1eaa | indra/java_vm.py | indra/java_vm.py | """Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
... | """Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
... | Include current classpath when starting java VM | Include current classpath when starting java VM
| Python | bsd-2-clause | johnbachman/indra,johnbachman/belpy,sorgerlab/indra,jmuhlich/indra,sorgerlab/indra,sorgerlab/belpy,jmuhlich/indra,johnbachman/belpy,sorgerlab/indra,bgyori/indra,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,pvtodorov/indra,pvtodorov/indra,sorgerlab/belpy... | ---
+++
@@ -14,7 +14,7 @@
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
-os.environ['CLASSPATH'] = cp
+os.environ['CLASSPATH'] = cp + ':' + os.environ['CLASSPATH']
from jnius import autoclass, JavaException, cast
|
f79f5a8494930cd7f64c6471dea631a7e8f35478 | slave/skia_slave_scripts/flavor_utils/xsan_build_step_utils.py | slave/skia_slave_scripts/flavor_utils/xsan_build_step_utils.py | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Utilities for ASAN,TSAN,etc. build steps. """
from default_build_step_utils import DefaultBuildStepUtils
from py.utils import ... | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Utilities for ASAN,TSAN,etc. build steps. """
from default_build_step_utils import DefaultBuildStepUtils
from py.utils import ... | Enable leak checks on our ASAN bots. | Enable leak checks on our ASAN bots.
After updating our suppressions, I had clean LSAN runs of dm and nanobench
yesterday on my desktop. Hopefully this will hold true for the bots.
BUG=skia:
R=borenet@google.com, mtklein@google.com
Author: mtklein@chromium.org
Review URL: https://codereview.chromium.org/524623002
| Python | bsd-3-clause | google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Ti... | ---
+++
@@ -27,8 +27,10 @@
shell_utils.run(cmd)
def RunFlavoredCmd(self, app, args):
- # New versions of ASAN run LSAN by default. We're not yet clean for that.
- os.environ['ASAN_OPTIONS'] = 'detect_leaks=0'
- # Point TSAN at our suppressions file.
+ # TODO(mtklein): Enable symbolize=1 for all... |
bdde8bb3ee9a79dc0ae777bb6e226dbc2be18dfb | manuscript/urls.py | manuscript/urls.py | # Copyright (C) 2011 by Christopher Adams
# Released under MIT License. See LICENSE.txt in the root of this
# distribution for details.
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'manuscript.views.all_works', name="all-works"),
url(r'^(?P<title>[-\w]+)/$', 'manuscript.views.whole_... | # Copyright (C) 2011 by Christopher Adams
# Released under MIT License. See LICENSE.txt in the root of this
# distribution for details.
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'manuscript.views.all_works', name="all-works"),
url(r'^(?P<title>[-\w]+)/$', 'manuscript.views.whole_... | Add sample url patterns to views for management functions. | Add sample url patterns to views for management functions.
| Python | mit | adamsc64/django-manuscript,adamsc64/django-manuscript | ---
+++
@@ -12,6 +12,10 @@
url(r'^(?P<title>[-\w]+)/(?P<chapter>[-\w]+)/$', 'manuscript.views.chapter', name="show-chapter"),
# url(r'^(?P<title>.*)/(?P<model>.*)/?$', 'model_by_work'),
# url(r'^(?P<title>.*)/(?P<model>.*)/(?P<id>\d*)/?$', 'element_by_id'),
+
+# url(r'^img_to_db/run/$', 'wyclif.bin.img_to_... |
247850851367486d54c8cf3a074e85d1d283e654 | message_view.py | message_view.py | import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
OUTPUT_PANEL = "output." + PANEL_NAME
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""... | import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
OUTPUT_PANEL = "output." + PANEL_NAME
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""... | Make the message panel accessible via menu | Make the message panel accessible via menu
| Python | mit | SublimeLinter/SublimeLinter3,SublimeLinter/SublimeLinter3 | ---
+++
@@ -12,7 +12,7 @@
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""):
- panel_view = self.window.create_output_panel(PANEL_NAME, True)
+ panel_view = self.window.create_output_panel(PANEL_NAME)
panel_view.set_read_only(False)
pan... |
e5db0a11634dc442f77f5550efd5cbf687ea6526 | lionschool/core/admin.py | lionschool/core/admin.py | from django.contrib import admin
from .models import Grade, Group, Pupil, Teacher, Warden
for model in {Grade, Group, Pupil, Teacher, Warden}:
admin.site.register(model)
| from django.contrib import admin
from .models import Grade, Group, Pupil, Teacher, Warden, Course
for model in Grade, Group, Pupil, Teacher, Warden, Course:
admin.site.register(model)
| Add Course field to Admin | Add Course field to Admin
Oops! forgot..
| Python | bsd-3-clause | Leo2807/lioncore | ---
+++
@@ -1,6 +1,6 @@
from django.contrib import admin
-from .models import Grade, Group, Pupil, Teacher, Warden
+from .models import Grade, Group, Pupil, Teacher, Warden, Course
-for model in {Grade, Group, Pupil, Teacher, Warden}:
+for model in Grade, Group, Pupil, Teacher, Warden, Course:
admin.site.r... |
fda50fb75b0b0e1d571c825e0a364573b93461bc | mbuild/__init__.py | mbuild/__init__.py | from mbuild.box import Box
from mbuild.coarse_graining import coarse_grain
from mbuild.coordinate_transform import *
from mbuild.compound import *
from mbuild.pattern import *
from mbuild.packing import *
from mbuild.port import Port
from mbuild.recipes import *
from mbuild.lattice import Lattice
from mbuild.recipes im... | from mbuild.box import Box
from mbuild.coarse_graining import coarse_grain
from mbuild.coordinate_transform import *
from mbuild.compound import *
from mbuild.pattern import *
from mbuild.packing import *
from mbuild.port import Port
from mbuild.lattice import Lattice
from mbuild.recipes import recipes
from mbuild.vers... | Remove a troubling import * | Remove a troubling import *
| Python | mit | iModels/mbuild,iModels/mbuild | ---
+++
@@ -5,7 +5,6 @@
from mbuild.pattern import *
from mbuild.packing import *
from mbuild.port import Port
-from mbuild.recipes import *
from mbuild.lattice import Lattice
from mbuild.recipes import recipes
from mbuild.version import version |
bd679f26e384ab42ac9edc2e99575dc57b9450ef | singleuser/user-config.py | singleuser/user-config.py | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'r') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
# Clean up temp variables, since pwb issues a warning otherwise
# to help people c... | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'r') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
# Clean up temp variables, since pwb issues a warning otherwise
# to help people c... | Mark the usernames to work only with wikipedia | Mark the usernames to work only with wikipedia
Bug: T120334
| Python | mit | yuvipanda/paws,yuvipanda/paws | ---
+++
@@ -15,4 +15,4 @@
del custom_path
# Things that should be non-easily-overridable
-usernames['*']['*'] = os.environ['JPY_USER']
+usernames['wikipedia']['*'] = os.environ['JPY_USER'] |
64398ae731b2f89e126ae9c63fe048134cbf649c | daybed/tests/support.py | daybed/tests/support.py | import os
from unittest import TestCase
import webtest
HERE = os.path.dirname(os.path.abspath(__file__))
class BaseWebTest(TestCase):
"""Base Web Test to test your cornice service.
It setups the database before each test and delete it after.
"""
def setUp(self):
self.app = webtest.TestApp(... | import os
from uuid import uuid4
from unittest import TestCase
import webtest
HERE = os.path.dirname(os.path.abspath(__file__))
class BaseWebTest(TestCase):
"""Base Web Test to test your cornice service.
It setups the database before each test and delete it after.
"""
def setUp(self):
self... | Create a random db for the tests each time. | Create a random db for the tests each time.
| Python | bsd-3-clause | spiral-project/daybed,spiral-project/daybed | ---
+++
@@ -1,4 +1,5 @@
import os
+from uuid import uuid4
from unittest import TestCase
import webtest
@@ -13,12 +14,14 @@
"""
def setUp(self):
+ self.db_name = os.environ['DB_NAME'] = 'daybed-tests-%s' % uuid4()
+
self.app = webtest.TestApp("config:tests.ini", relative_to=HERE)
... |
6f968a4aa4048163dd55f927a32da2477cd8c1ff | tx_salaries/search_indexes.py | tx_salaries/search_indexes.py | from haystack import indexes
from tx_people.models import Organization
from tx_salaries.models import Employee
class EmployeeIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
content_auto = indexes.EdgeNgramField(model_attr='position__person__name')
... | from haystack import indexes
from tx_salaries.models import Employee
class EmployeeIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
content_auto = indexes.EdgeNgramField(model_attr='position__person__name')
compensation = indexes.FloatField(model_at... | Index slugs to reduce search page queries | Index slugs to reduce search page queries
| Python | apache-2.0 | texastribune/tx_salaries,texastribune/tx_salaries | ---
+++
@@ -1,5 +1,4 @@
from haystack import indexes
-from tx_people.models import Organization
from tx_salaries.models import Employee
@@ -8,8 +7,11 @@
content_auto = indexes.EdgeNgramField(model_attr='position__person__name')
compensation = indexes.FloatField(model_attr='compensation', null=True)
... |
42c7496beefea0e5d10cbd6e356335efae27a5ec | taiga/projects/migrations/0043_auto_20160530_1004.py | taiga/projects/migrations/0043_auto_20160530_1004.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-05-30 10:04
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projects', '0042_auto_20160... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-05-30 10:04
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projects', '0040_remove_mem... | Fix a problem with a migration between master and stable branch | Fix a problem with a migration between master and stable branch
| Python | agpl-3.0 | dayatz/taiga-back,taigaio/taiga-back,xdevelsistemas/taiga-back-community,taigaio/taiga-back,xdevelsistemas/taiga-back-community,dayatz/taiga-back,dayatz/taiga-back,xdevelsistemas/taiga-back-community,taigaio/taiga-back | ---
+++
@@ -10,7 +10,7 @@
class Migration(migrations.Migration):
dependencies = [
- ('projects', '0042_auto_20160525_0911'),
+ ('projects', '0040_remove_memberships_of_cancelled_users_acounts'),
]
operations = [ |
7352f08852d5d265e4cb79a43e056b666a1877c5 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name="go_contacts",
version="0.1.0a",
url='http://github.com/praekelt/go-contacts-api',
license='BSD',
description="A contacts and groups API for Vumi Go",
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
a... | from setuptools import setup, find_packages
setup(
name="go_contacts",
version="0.1.0a",
url='http://github.com/praekelt/go-contacts-api',
license='BSD',
description="A contacts and groups API for Vumi Go",
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
a... | Add go_api as a dependency. | Add go_api as a dependency.
| Python | bsd-3-clause | praekelt/go-contacts-api,praekelt/go-contacts-api | ---
+++
@@ -13,6 +13,7 @@
include_package_data=True,
install_requires=[
'cyclone',
+ 'go_api',
],
classifiers=[
'Development Status :: 4 - Beta', |
8565921f7bc42c30534bdc272bd3daaf1e758b1c | setup.py | setup.py | import os
from setuptools import setup, find_packages
DESCRIPTION = 'Send emails using Django template system'
LONG_DESCRIPTION = None
try:
LONG_DESCRIPTION = open('README.rst').read()
except:
pass
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
... | import os
from setuptools import setup, find_packages
DESCRIPTION = 'Send emails using Django template system'
LONG_DESCRIPTION = None
try:
LONG_DESCRIPTION = open('README.rst').read()
except:
pass
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
... | Remove Django from dependencies to avoid auto upgrade | Remove Django from dependencies to avoid auto upgrade
| Python | mit | artemrizhov/django-mail-templated,artemrizhov/django-mail-templated,artemrizhov/django-mail-templated | ---
+++
@@ -40,5 +40,4 @@
platforms=['any'],
classifiers=CLASSIFIERS,
test_suite='mail_templated.test_utils.run.run_tests',
- install_requires = ['django'],
) |
ee9a9b12248d119d561523e8ca1b692f11a56fd7 | datasets/forms.py | datasets/forms.py | from django import forms
from datasets.models import DatasetRelease, CategoryComment
class DatasetReleaseForm(forms.ModelForm):
max_number_of_sounds = forms.IntegerField(required=False)
class Meta:
model = DatasetRelease
fields = ['release_tag', 'type']
class PresentNotPresentUnsureForm(for... | from django import forms
from datasets.models import DatasetRelease, CategoryComment
class DatasetReleaseForm(forms.ModelForm):
max_number_of_sounds = forms.IntegerField(required=False)
class Meta:
model = DatasetRelease
fields = ['release_tag', 'type']
class PresentNotPresentUnsureForm(for... | Remove upper case Not Present | Remove upper case Not Present
| Python | agpl-3.0 | MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets | ---
+++
@@ -17,7 +17,7 @@
choices=(
('1', 'Present and predominant',),
('0.5', 'Present but not predominant',),
- ('-1', 'Not Present',),
+ ('-1', 'Not present',),
('0', 'Unsure',),
),
) |
e43b91412ee0899bb6b851a760dd06bce263d099 | Instanssi/ext_blog/templatetags/blog_tags.py | Instanssi/ext_blog/templatetags/blog_tags.py | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id__lte=int(event_id), publ... | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id, max_posts=10):
entries = BlogEntry.objects.filter(event_id__lte=int(e... | Allow customizing number of posts displayed | ext_blog: Allow customizing number of posts displayed
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | ---
+++
@@ -7,8 +7,8 @@
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
-def render_blog(event_id):
- entries = BlogEntry.objects.filter(event_id__lte=int(event_id), public=True).order_by('-date')[:10]
+def render_blog(event_id, max_posts=10):
+ entries = BlogEntry.objec... |
c8cc85f0d10093ae9cd42ee4cc7dabef46718645 | ood/controllers/simple.py | ood/controllers/simple.py | import socket
from ood.minecraft import Client
from ood.models import SimpleServerState
class SimpleServerController(object):
def __init__(self, ood_instance):
self.state = SimpleServerState.objects.get(ood=ood_instance)
self.mcc = Client(ood_instance)
def start(self):
self.mcc.rese... | import socket
from ood.minecraft import Client
from ood.models import SimpleServerState
class SimpleServerController(object):
def __init__(self, ood_instance):
self.state, _ = SimpleServerState.objects.get_or_create(
ood=ood_instance)
self.mcc = Client(ood_instance)
def start(se... | Create SimpleServerState object if it doesn't exist. | Create SimpleServerState object if it doesn't exist.
| Python | mit | markrcote/ood,markrcote/ood,markrcote/ood,markrcote/ood | ---
+++
@@ -7,7 +7,8 @@
class SimpleServerController(object):
def __init__(self, ood_instance):
- self.state = SimpleServerState.objects.get(ood=ood_instance)
+ self.state, _ = SimpleServerState.objects.get_or_create(
+ ood=ood_instance)
self.mcc = Client(ood_instance)
... |
a7919b78c96128cc5bcfda759da11f6b067d0041 | tests/__init__.py | tests/__init__.py | import base64
import unittest
def setup_package(self):
pass
def teardown_package(self):
pass
class BaseS3EncryptTest(unittest.TestCase):
def decode64(self, data):
return base64.b64decode(data)
def encode64(self, data):
return base64.b64encode(data)
| import base64
import codecs
import unittest
def setup_package(self):
pass
def teardown_package(self):
pass
class BaseS3EncryptTest(unittest.TestCase):
def decode64(self, data):
return base64.b64decode(codecs.decode(data, 'utf-8'))
def encode64(self, data):
return codecs.encode(ba... | Make test helpers py 3 compatable | Make test helpers py 3 compatable
| Python | bsd-3-clause | boldfield/s3-encryption | ---
+++
@@ -1,4 +1,5 @@
import base64
+import codecs
import unittest
@@ -13,7 +14,7 @@
class BaseS3EncryptTest(unittest.TestCase):
def decode64(self, data):
- return base64.b64decode(data)
+ return base64.b64decode(codecs.decode(data, 'utf-8'))
def encode64(self, data):
- ret... |
4e70bc00a7b3fb96302ac6c2a29e463e07eabbb0 | tests/__init__.py | tests/__init__.py | import logging
import unittest
from cassandra.cluster import Cluster
from cassandra.connection import _loop
from cassandra.policies import HostDistance
log = logging.getLogger()
log.setLevel('DEBUG')
log.addHandler(logging.StreamHandler())
existing_keyspaces = None
def setup_package():
try:
cluster = Cl... | Test package setup and teardown | Test package setup and teardown
| Python | apache-2.0 | HackerEarth/cassandra-python-driver,jfelectron/python-driver,tempbottle/python-driver,stef1927/python-driver,kishkaru/python-driver,coldeasy/python-driver,jfelectron/python-driver,HackerEarth/cassandra-python-driver,stef1927/python-driver,aholmberg/python-driver,yi719/python-driver,mike-tr-adamson/python-driver,datasta... | ---
+++
@@ -0,0 +1,62 @@
+import logging
+import unittest
+
+from cassandra.cluster import Cluster
+from cassandra.connection import _loop
+from cassandra.policies import HostDistance
+
+log = logging.getLogger()
+log.setLevel('DEBUG')
+log.addHandler(logging.StreamHandler())
+
+existing_keyspaces = None
+
+def setup... | |
24ed97f09707a404bf81062a99a485c547d92d11 | accio/webhooks/views.py | accio/webhooks/views.py | from django.http.response import HttpResponse
def webhook(request):
return HttpResponse('Webhooks not implemented yet', status=501)
| from django.http.response import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def webhook(request):
return HttpResponse('Webhooks not implemented yet', status=501)
| Add csrf_exempt to webhook view | fix: Add csrf_exempt to webhook view
| Python | mit | relekang/accio,relekang/accio,relekang/accio | ---
+++
@@ -1,5 +1,7 @@
from django.http.response import HttpResponse
+from django.views.decorators.csrf import csrf_exempt
+@csrf_exempt
def webhook(request):
return HttpResponse('Webhooks not implemented yet', status=501) |
936cb7ad48a2ab509127fa2eb4cc84af9b3dbe2a | spicedham/nonsensefilter.py | spicedham/nonsensefilter.py | import operator
from itertools import imap, repeat
from spicedham.config import load_config
from spicedham.baseplugin import BasePlugin
class NonsenseFilter(BasePlugin):
"""
Filter messages with no words in the database.
"""
def __init__(self, config, backend):
"""
Get values from the... | import operator
from itertools import imap, repeat
from spicedham.baseplugin import BasePlugin
class NonsenseFilter(BasePlugin):
"""
Filter messages with no words in the database.
"""
def __init__(self, config, backend):
"""
Get values from the config.
"""
self.backend... | Remove extraneous and problematic import | Remove extraneous and problematic import
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham | ---
+++
@@ -1,7 +1,6 @@
import operator
from itertools import imap, repeat
-from spicedham.config import load_config
from spicedham.baseplugin import BasePlugin
class NonsenseFilter(BasePlugin): |
75345f55679437b418d9645371efc647b0d7db6c | filestore/api.py | filestore/api.py | from __future__ import absolute_import, division, print_function
from .commands import insert_resource, insert_datum, retrieve
| from __future__ import absolute_import, division, print_function
from .commands import insert_resource, insert_datum, retrieve
from .retrieve import register_handler
| Add register_handler with the API. | API: Add register_handler with the API.
| Python | bsd-3-clause | ericdill/fileStore,ericdill/databroker,ericdill/databroker,danielballan/filestore,ericdill/fileStore,stuwilkins/filestore,danielballan/filestore,NSLS-II/filestore,stuwilkins/filestore,tacaswell/filestore | ---
+++
@@ -1,3 +1,4 @@
from __future__ import absolute_import, division, print_function
from .commands import insert_resource, insert_datum, retrieve
+from .retrieve import register_handler |
86fdcd6575a944a378a9c3f5b292fb33a6c42853 | digestive/hash.py | digestive/hash.py | import hashlib
from digestive.io import Sink
class HashDigest(Sink):
def __init__(self, name, digest):
super().__init__(name)
self._digest = digest
def update(self, data):
self._digest.update(data)
def digest(self):
return self._digest.hexdigest()
class MD5(HashDigest)... | import hashlib
from digestive.io import Sink
class HashDigest(Sink):
def __init__(self, name, digest):
super().__init__(name)
self._digest = digest
def update(self, data):
self._digest.update(data)
def digest(self):
return self._digest.hexdigest()
class MD5(HashDigest)... | Make sha256 and sha512 sink names correspond to their commandline arguments | Make sha256 and sha512 sink names correspond to their commandline arguments
| Python | isc | akaIDIOT/Digestive | ---
+++
@@ -27,9 +27,9 @@
class SHA256(HashDigest):
def __init__(self):
- super().__init__('sha2-256', hashlib.sha256())
+ super().__init__('sha256', hashlib.sha256())
class SHA512(HashDigest):
def __init__(self):
- super().__init__('sha2-512', hashlib.sha512())
+ super()... |
dcd6d830033914a0ccf26822d6f305c084b90987 | f8a_jobs/defaults.py | f8a_jobs/defaults.py | #!/usr/bin/env python3
import os
from datetime import timedelta
_BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__))
DEFAULT_SERVICE_PORT = 34000
SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml')
DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs')
TOKEN_VALID_TIME = timed... | #!/usr/bin/env python3
import os
from datetime import timedelta
_BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__))
DEFAULT_SERVICE_PORT = 34000
SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml')
DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs')
TOKEN_VALID_TIME = timed... | Fix wrong variable reference in configuration | Fix wrong variable reference in configuration
| Python | apache-2.0 | fabric8-analytics/fabric8-analytics-jobs,fabric8-analytics/fabric8-analytics-jobs | ---
+++
@@ -16,7 +16,7 @@
AWS_ACCESS_KEY_ID = os.getenv('AWS_SQS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SQS_SECRET_ACCESS_KEY')
AWS_SQS_REGION = os.getenv('AWS_SQS_REGION', 'us-east-1')
-DEPLOYMENT_PREFIX = os.getenv('AWS_SQS_REGION', 'us-east-1')
+DEPLOYMENT_PREFIX = os.getenv('DEPLOYMENT_PREFIX',... |
25e5b39113994769c01bf6a79a9ca65764861ab3 | spicedham/__init__.py | spicedham/__init__.py | from pkg_resources import iter_entry_points
from spicedham.config import config
# TODO: Wrap all of this in an object with this in an __init__ function
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(... | from pkg_resources import iter_entry_points
from spicedham.config import load_config
_plugins = None
def load_plugins():
"""
If not already loaded, load plugins.
"""
if _plugins == None
load_config()
_plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', ... | Fix code which executes on module load. | Fix code which executes on module load.
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham | ---
+++
@@ -1,19 +1,26 @@
from pkg_resources import iter_entry_points
-from spicedham.config import config
+from spicedham.config import load_config
-# TODO: Wrap all of this in an object with this in an __init__ function
-plugins = []
-for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
-... |
6d23a879a40b9e94f1c568dc6f97e42001b4203c | vcspull/__about__.py | vcspull/__about__.py | __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.0.3'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013-2016 Tony Narlock'
| __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.0.3'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013-2016 Tony Narlock'
| Update LICENSE in package metadata | Update LICENSE in package metadata
| Python | mit | tony/vcspull,tony/vcspull | ---
+++
@@ -4,5 +4,5 @@
__version__ = '1.0.3'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
-__license__ = 'BSD'
+__license__ = 'MIT'
__copyright__ = 'Copyright 2013-2016 Tony Narlock' |
8e76b64fa3eafa9d22fc37b68ddb1daff6633119 | thinglang/parser/tokens/functions.py | thinglang/parser/tokens/functions.py | from thinglang.lexer.symbols.base import LexicalIdentifier
from thinglang.parser.tokens import BaseToken, DefinitionPairToken
from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization
from thinglang.utils.type_descriptors import ValueType
class Access(BaseToken):
def __init__(s... | from thinglang.lexer.symbols.base import LexicalIdentifier, LexicalAccess
from thinglang.parser.tokens import BaseToken, DefinitionPairToken
from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization
from thinglang.utils.type_descriptors import ValueType
class Access(BaseToken):
... | Use original LexicalIDs in Access | Use original LexicalIDs in Access
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -1,4 +1,4 @@
-from thinglang.lexer.symbols.base import LexicalIdentifier
+from thinglang.lexer.symbols.base import LexicalIdentifier, LexicalAccess
from thinglang.parser.tokens import BaseToken, DefinitionPairToken
from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitializat... |
22e90cf883fa0b6d4c8acb282ebe28929f6d9487 | nhs/patents/models.py | nhs/patents/models.py | from django.db import models
from nhs.prescriptions.models import Product
class Patent(models.Model):
drug = models.ForeignKey(Product)
expiry_date = models.DateField()
start_date = models.DateField(null=True, blank=True)
# Stupid. But you know, they're called patent number... | from django.db import models
from nhs.prescriptions.models import Product
class Patent(models.Model):
drug = models.ForeignKey(Product)
expiry_date = models.DateField()
start_date = models.DateField(null=True, blank=True)
# Stupid. But you know, they're called patent number... | Add that field in the model | Add that field in the model
| Python | agpl-3.0 | openhealthcare/open-prescribing,openhealthcare/open-prescribing,openhealthcare/open-prescribing | ---
+++
@@ -9,3 +9,4 @@
# Stupid. But you know, they're called patent numbers.
# Except they have letters in them.
number = models.CharField(max_length=200, null=True, blank=True)
+ source = models.CharField(max_length=200, null=True, blank=True) |
c74b444f75441a6ccf9d9305f956ec4443f6ec01 | dockci/session.py | dockci/session.py | """ Session interface switcher """
from flask.sessions import SecureCookieSessionInterface, SessionMixin
from dockci.util import is_api_request
class FakeSession(dict, SessionMixin):
""" Transient session-like object """
pass
class SessionSwitchInterface(SecureCookieSessionInterface):
"""
Session ... | """ Session interface switcher """
from flask.sessions import SecureCookieSessionInterface, SessionMixin
from dockci.util import is_api_request
class FakeSession(dict, SessionMixin):
""" Transient session-like object """
pass
class SessionSwitchInterface(SecureCookieSessionInterface):
"""
Session ... | Use global request context, because None url_rule sometimes | Use global request context, because None url_rule sometimes
| Python | isc | sprucedev/DockCI-Agent,sprucedev/DockCI,sprucedev/DockCI,sprucedev/DockCI,RickyCook/DockCI,sprucedev/DockCI,RickyCook/DockCI,sprucedev/DockCI-Agent,RickyCook/DockCI,RickyCook/DockCI | ---
+++
@@ -22,7 +22,7 @@
def open_session(self, app, request):
session_id = request.cookies.get(self.app.session_cookie_name)
- if not session_id and is_api_request(request):
+ if not session_id and is_api_request():
return FakeSession()
return super(SessionSwitc... |
5597c9db9067ce466697f75949d47d7f94077fae | tests/test_forms.py | tests/test_forms.py | from django.forms import ModelForm, RadioSelect
from .models import Product, Option
class ProductForm(ModelForm):
class Meta:
model = Product
class OptionForm(ModelForm):
class Meta:
model = Option
def test_post(rf):
req = rf.post('/', {'price': '2.12'})
form = ProductForm(req.POST... | from django.forms import ModelForm, RadioSelect
from .models import Product, Option
class ProductForm(ModelForm):
class Meta:
model = Product
class OptionForm(ModelForm):
class Meta:
model = Option
def test_post(rf):
req = rf.post('/', {'price': '2.12'})
form = ProductForm(req.POST... | Add tests for proper values in select/radios | Add tests for proper values in select/radios
| Python | bsd-2-clause | Suor/django-easymoney | ---
+++
@@ -35,6 +35,7 @@
html = form['price'].as_widget()
assert html.startswith('<select')
+ assert 'value="0.50"' in html
assert 'selected' in html
@@ -50,6 +51,7 @@
html = form['price'].as_widget()
assert 'radio' in html
+ assert 'value="0.50"' in html
assert 'checked' ... |
b4f17dfd004cf0033e1aeccbb9e75a07bbe35cfa | competition_scripts/interop/tra.py | competition_scripts/interop/tra.py | import argparse
from time import time
try:
# Python 3
from xmlrpc.client import ServerProxy
except ImportError:
# Python 2
from SimpleXMLRPCServer import ServerProxy
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='AUVSI SUAS TRA')
parser.add_argument(
'... | import argparse
from time import time
try:
# Python 3
from xmlrpc.client import ServerProxy
except ImportError:
# Python 2
from SimpleXMLRPCServer import ServerProxy
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='AUVSI SUAS TRA')
parser.add_argument(
'... | Add initialization for ServerProxy object | Add initialization for ServerProxy object
| Python | mit | FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition | ---
+++
@@ -20,6 +20,9 @@
print("[*] Starting Target Recognition Application...")
+ server = ServerProxy(cmd_args.url)
+ print('Server Info: {}'.format(server.server_info()))
+
try:
print('[*] Use Control-C to exit')
except KeyboardInterrupt: |
d6da05f79d62f90d8d03908197a0389b67535aa5 | halfedge_mesh.py | halfedge_mesh.py | class HalfedgeMesh:
def __init__(self, filename=None):
"""Make an empty halfedge mesh."""
self.vertices = []
self.halfedges = []
self.facets = []
def read_off(self, filename):
class Vertex:
def __init__(self, x, y, z, index):
"""Create a vertex with give... | class HalfedgeMesh:
def __init__(self, filename=None):
"""Make an empty halfedge mesh."""
self.vertices = []
self.halfedges = []
self.facets = []
def parse_off(self, filename):
"""Parses OFF files and returns a set of vertices, halfedges, and
facets.
"""
... | Add parse_off stub and change docstring | Add parse_off stub and change docstring
I follow the TomDoc format for docstrings.
| Python | mit | carlosrojas/halfedge_mesh | ---
+++
@@ -5,17 +5,30 @@
self.halfedges = []
self.facets = []
- def read_off(self, filename):
+ def parse_off(self, filename):
+ """Parses OFF files and returns a set of vertices, halfedges, and
+ facets.
+ """
+ pass
+
+ def get_halfedge(self, u, v):
+ ... |
65c55a6a4920d67b10d705909864124776d3a2dc | plugins/generic/syntax.py | plugins/generic/syntax.py | #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __in... | #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __in... | Fix for escaping single quote character(s) | Fix for escaping single quote character(s)
| Python | mit | dtrip/.ubuntu,RexGene/monsu-server,dtrip/.ubuntu,RexGene/monsu-server | ---
+++
@@ -22,7 +22,7 @@
retVal = expression
if quote:
- for item in re.findall(r"'[^']+'", expression, re.S):
+ for item in re.findall(r"'[^']*'+", expression, re.S):
retVal = retVal.replace(item, escaper(item[1:-1]))
else:
retVal = es... |
a1a9852f478258b2c2f6f28a0ee28f223adaa299 | src/myarchive/db/tables/ljtables.py | src/myarchive/db/tables/ljtables.py | from sqlalchemy import (
LargeBinary, Boolean, Column, Integer, String, PickleType, ForeignKey)
from sqlalchemy.orm import backref, relationship
from sqlalchemy.orm.exc import NoResultFound
from myarchive.db.tables.base import Base
from myarchive.db.tables.file import TrackedFile
from myarchive.db.tables.associati... | from sqlalchemy import (
Column, Integer, String, TIMESTAMP, ForeignKey)
from sqlalchemy.orm import backref, relationship
from sqlalchemy.orm.exc import NoResultFound
from myarchive.db.tables.base import Base
from myarchive.db.tables.file import TrackedFile
class LJHost(Base):
"""Class representing a user re... | Add a bunch of LJ tables | Add a bunch of LJ tables
| Python | mit | zetasyanthis/myarchive | ---
+++
@@ -1,14 +1,69 @@
from sqlalchemy import (
- LargeBinary, Boolean, Column, Integer, String, PickleType, ForeignKey)
+ Column, Integer, String, TIMESTAMP, ForeignKey)
from sqlalchemy.orm import backref, relationship
from sqlalchemy.orm.exc import NoResultFound
from myarchive.db.tables.base import B... |
13350cdf5598ac0ed55e5404cf6d407300b4c1ac | apps/home/forms.py | apps/home/forms.py | # -*- coding: utf-8 -*-
import re
from django import forms
from apps.chat.models import Chats
from django.utils.translation import ugettext as _
class CreateChatForm(forms.Form):
pass
class JoinChatForm(forms.Form):
chat_token = forms.CharField(required=True, max_length=24, label='')
chat_token.widget =... | # -*- coding: utf-8 -*-
import re
from django import forms
from apps.chat.models import Chats
from django.utils.translation import ugettext as _
class CreateChatForm(forms.Form):
pass
class JoinChatForm(forms.Form):
chat_token = forms.CharField(required=True, max_length=24, label='')
chat_token.widget =... | Set autocomplete off for chat token form field | Set autocomplete off for chat token form field
| Python | bsd-3-clause | MySmile/sfchat,MySmile/sfchat,MySmile/sfchat,MySmile/sfchat | ---
+++
@@ -13,6 +13,7 @@
chat_token = forms.CharField(required=True, max_length=24, label='')
chat_token.widget = forms.TextInput({"maxlength": 24,
"pattern": "[a-z0-9]{24}",
+ "autocomplete": "off",
... |
e8da237a6c1542b997b061db43cc993942983b10 | django_local_apps/management/commands/local_app_utils/db_clean_utils.py | django_local_apps/management/commands/local_app_utils/db_clean_utils.py | from django.db.models import Q
from django.utils import timezone
def remove_expired_record(expire_days, query_set, time_attr_name="timestamp"):
expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)}
q = Q(**expired_record_filter)
final_q = query_set.filt... | from django.db.models import Q
from django.utils import timezone
def remove_expired_record(expire_days, query_set, time_attr_name="timestamp"):
expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)}
q = Q(**expired_record_filter)
final_q = query_set.filt... | Delete item with limited size. | Delete item with limited size.
| Python | bsd-3-clause | weijia/django-local-apps,weijia/django-local-apps | ---
+++
@@ -6,6 +6,8 @@
expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)}
q = Q(**expired_record_filter)
final_q = query_set.filter(q)
+ if final_q.count() > 1000:
+ final_q = final_q[:999]
# cnt = 0
# for i in final_q:
#... |
ce3948b2aacddfb9debd4834d9aa446e99987a0d | app/views.py | app/views.py | from app import mulungwishi_app as url
from flask import render_template
@url.route('/')
def index():
return render_template('index.html')
@url.route('/<query>')
def print_user_input(query):
if '=' in query:
query_container, query_value = query.split('=')
return 'Your query is {} which is eq... | from app import mulungwishi_app as url
from flask import render_template
@url.route('/')
def index():
return render_template('index.html')
@url.route('/<query>')
def print_user_input(query):
if '=' in query:
query_container, query_value = query.split('=')
return 'Your query is {} which is eq... | Replace string concatenation with .format function | Replace string concatenation with .format function
| Python | mit | admiral96/mulungwishi-webhook,engagespark/public-webhooks,admiral96/public-webhooks,admiral96/mulungwishi-webhook,admiral96/public-webhooks,engagespark/mulungwishi-webhook,engagespark/mulungwishi-webhook,engagespark/public-webhooks | ---
+++
@@ -12,7 +12,7 @@
if '=' in query:
query_container, query_value = query.split('=')
return 'Your query is {} which is equal to {}'.format(query_container, query_value)
- return "You've entered an incorrect query. Please check and try again. Input : "+query
+ return "You've entered ... |
98aea2115cb6c5101379be2320a6fb0735a32490 | helenae/web/views.py | helenae/web/views.py | from flask import render_template
from flask_app import app
@app.route('/')
def index():
return render_template('index.html')
| # -*- coding: utf-8 -*-
import datetime
from hashlib import sha256
from time import gmtime, strftime
import sqlalchemy
from flask import render_template, redirect, url_for
from flask_app import app, db_connection, dbTables
from forms import RegisterForm
@app.route('/', methods=('GET', 'POST'))
def index():
retur... | Add routes for other pages | Add routes for other pages
| Python | mit | Relrin/Helenae,Relrin/Helenae,Relrin/Helenae | ---
+++
@@ -1,7 +1,54 @@
-from flask import render_template
-from flask_app import app
+# -*- coding: utf-8 -*-
+import datetime
+from hashlib import sha256
+from time import gmtime, strftime
-@app.route('/')
+import sqlalchemy
+from flask import render_template, redirect, url_for
+from flask_app import app, db_con... |
2aed0c4089eced430dabf8d63c732e6b0013f540 | project_fish/whats_fresh/models.py | project_fish/whats_fresh/models.py | from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Django when the object is created or modified,... | from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Django when the object is created or modified,... | Change upload path for images | Change upload path for images
| Python | apache-2.0 | osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api | ---
+++
@@ -14,7 +14,7 @@
timestamps.
"""
- image = models.ImageField(upload_to='%Y/%m/%d')
+ image = models.ImageField(upload_to='/')
caption = models.TextField()
created = models.DateTimeField(auto_now_add=True) |
0ee0d94e6a167ab8994a5e61f3db45799eba7a12 | dragonflow/common/common_params.py | dragonflow/common/common_params.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... | Use oslo_config new type PortOpt for port options | Use oslo_config new type PortOpt for port options
The oslo_config library provides new type PortOpt to validate the
range of port now.
Change-Id: Ifbfee642309fec668e363555c2abd103c1f8c4af
ref: https://github.com/openstack/oslo.config/blob/2.6.0/oslo_config/cfg.py#L1114
Depends-On: Ida294b05a85f5bef587b761fcd03c28c7a3... | Python | apache-2.0 | FrankDuan/df_code,openstack/dragonflow,FrankDuan/df_code,openstack/dragonflow,FrankDuan/df_code,openstack/dragonflow | ---
+++
@@ -18,9 +18,9 @@
cfg.StrOpt('remote_db_ip',
default='127.0.0.1',
help=_('The remote db server ip address')),
- cfg.IntOpt('remote_db_port',
- default=4001,
- help=_('The remote db server port')),
+ cfg.PortOpt('remote_db_port',
+ ... |
590f80bc382cdbec97e2cb3e7b92c79bb7fa89cc | dyndns/models.py | dyndns/models.py | from django.db import models
class Record(models.Model):
domain_id = models.IntegerField()
name = models.CharField(max_length=30)
type=models.CharField(max_length=6)
content=models.CharField(max_length=30)
ttl=models.IntegerField()
prio=models.IntegerField()
change_date= models.IntegerField()
def __unicode__(s... | from django.db import models
class Domain(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(unique=True, max_length=255)
master = models.CharField(max_length=128)
last_check = models.IntegerField()
type = models.CharField(max_length=6)
notified_serial = models.In... | Update model to match latest PDNS and add other two tables | Update model to match latest PDNS and add other two tables
| Python | bsd-2-clause | zefciu/django-powerdns-dnssec,allegro/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,allegro/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,allegro/djan... | ---
+++
@@ -1,18 +1,36 @@
from django.db import models
-class Record(models.Model):
- domain_id = models.IntegerField()
- name = models.CharField(max_length=30)
- type=models.CharField(max_length=6)
- content=models.CharField(max_length=30)
- ttl=models.IntegerField()
- prio=models.IntegerField()
- change_date= mo... |
454e107abfdc9e3038a18500568e9a1357364bd0 | pygraphc/similarity/JaroWinkler.py | pygraphc/similarity/JaroWinkler.py | import jellyfish
import multiprocessing
from itertools import combinations
class JaroWinkler(object):
def __init__(self, event_attributes, event_length):
self.event_attributes = event_attributes
self.event_length = event_length
def __jarowinkler(self, unique_event_id):
string1 = unico... | import jellyfish
import multiprocessing
from itertools import combinations
class JaroWinkler(object):
def __init__(self, event_attributes, event_length):
self.event_attributes = event_attributes
self.event_length = event_length
def __jarowinkler(self, unique_event_id):
string1 = unico... | Add checking for zero distance | Add checking for zero distance
| Python | mit | studiawan/pygraphc | ---
+++
@@ -11,13 +11,14 @@
def __jarowinkler(self, unique_event_id):
string1 = unicode(self.event_attributes[unique_event_id[0]]['preprocessed_event'], 'utf-8')
string2 = unicode(self.event_attributes[unique_event_id[1]]['preprocessed_event'], 'utf-8')
- return jellyfish.jaro_winkler(st... |
39d7ec0fe9fdbdd152dfcc2d4280b784f6315886 | stardate/urls/index_urls.py | stardate/urls/index_urls.py | from django.conf.urls import include, url
from django.views import generic
from stardate.models import Blog
from stardate.views import (
BlogCreate,
select_backend,
process_webhook,
)
urlpatterns = [
url(r'^new/$', select_backend, name='blog-new'),
url(r'^create/(?P<provider>[-\w]+)/$', BlogCreat... | from django.conf.urls import include, url
from django.views import generic
from stardate.models import Blog
from stardate.views import (
BlogCreate,
select_backend,
process_webhook,
)
urlpatterns = [
url(r'^new/$', select_backend, name='blog-new'),
url(r'^create/(?P<provider>[-\w]+)/$', BlogCreat... | Revert "remove blog urls from index urls" | Revert "remove blog urls from index urls"
This reverts commit f8d5541a8e5de124dcec62a32bd19a8226869622.
| Python | bsd-3-clause | blturner/django-stardate,blturner/django-stardate | ---
+++
@@ -14,5 +14,6 @@
url(r'^create/(?P<provider>[-\w]+)/$', BlogCreate.as_view(), name='blog-create'),
url(r'^providers/$', select_backend, name='provider-select'),
url(r'^webhook/$', process_webhook, name='webhook'),
+ url(r'^(?P<blog_slug>[-\w]+)/', include('stardate.urls.blog_urls')),
u... |
93d0f11658c7417371ec2e040397c7a572559585 | django_remote_submission/consumers.py | django_remote_submission/consumers.py | """Manage websocket connections."""
# -*- coding: utf-8 -*-
import json
from channels import Group
from channels.auth import channel_session_user_from_http, channel_session_user
from .models import Job
@channel_session_user_from_http
def ws_connect(message):
message.reply_channel.send({
'accept': True,
... | """Manage websocket connections."""
# -*- coding: utf-8 -*-
import json
from channels import Group
from channels.auth import channel_session_user_from_http, channel_session_user
from .models import Job
import json
@channel_session_user_from_http
def ws_connect(message):
last_jobs = message.user.jobs.order_by('... | Send last jobs on initial connection | Send last jobs on initial connection
| Python | isc | ornl-ndav/django-remote-submission,ornl-ndav/django-remote-submission,ornl-ndav/django-remote-submission | ---
+++
@@ -7,12 +7,21 @@
from .models import Job
+import json
+
@channel_session_user_from_http
def ws_connect(message):
- message.reply_channel.send({
- 'accept': True,
- })
+ last_jobs = message.user.jobs.order_by('-modified')[:10]
+
+ for job in last_jobs:
+ message.reply_channe... |
099c41acc83fdd6589f5a53ec8d1615d96e4d188 | website/articles.py | website/articles.py | import sys
from tinydb import TinyDB, where
import markdown2
articles_db = TinyDB("data/articles.json")
def get_all_articles():
return articles_db.all()
def get_article_data_by_url(url: str):
results = articles_db.search(where("url") == url)
if len(results) == 0:
raise FileNotFoundError("Error: no article wit... | import sys
from tinydb import TinyDB, where
import markdown2
articles_db = TinyDB("data/articles.json")
def get_all_articles():
return articles_db.all()
def get_article_data_by_url(url: str):
results = articles_db.search(where("url") == url)
if len(results) == 0:
raise FileNotFoundError("Error: no article wit... | Set file open to enforce utf8 | Set file open to enforce utf8
| Python | apache-2.0 | timlyo/personalWebsite,timlyo/timlyo.github.io,timlyo/timlyo.github.io,timlyo/personalWebsite,timlyo/personalWebsite,timlyo/timlyo.github.io | ---
+++
@@ -33,6 +33,6 @@
def get_contents(filename: str):
contents = None
- with open("data/articles/" + filename) as file:
+ with open("data/articles/" + filename, "r", encoding="utf8") as file:
contents = file.read()
return contents |
22472d7947c16388dc849b2c317ee4d509322754 | docs/examples/01_make_resourcelist.py | docs/examples/01_make_resourcelist.py | from resync.resource_list import ResourceList
from resync.resource import Resource
from resync.sitemap import Sitemap
rl = ResourceList()
rl.add( Resource('http://example.com/res1', lastmod='2013-01-01') )
rl.add( Resource('http://example.com/res2', lastmod='2013-01-02') )
sm = Sitemap(pretty_xml=True)
print sm.resour... | from resync.resource_list import ResourceList
from resync.resource import Resource
from resync.sitemap import Sitemap
rl = ResourceList()
rl.add( Resource('http://example.com/res1', lastmod='2013-01-01') )
rl.add( Resource('http://example.com/res2', lastmod='2013-01-02') )
print rl.as_xml(pretty_xml=True)
| Update to use ResourceList methods | Update to use ResourceList methods
| Python | apache-2.0 | dans-er/resync,lindareijnhoudt/resync,lindareijnhoudt/resync,dans-er/resync,resync/resync | ---
+++
@@ -5,5 +5,4 @@
rl = ResourceList()
rl.add( Resource('http://example.com/res1', lastmod='2013-01-01') )
rl.add( Resource('http://example.com/res2', lastmod='2013-01-02') )
-sm = Sitemap(pretty_xml=True)
-print sm.resources_as_xml(rl)
+print rl.as_xml(pretty_xml=True) |
e82225201772794bf347c6e768d25f24a61b9b54 | migrations/schematic_settings.py | migrations/schematic_settings.py | import sys
import os
# This only works if you're running schematic from the zamboni root.
sys.path.insert(0, os.path.realpath('.'))
# Set up zamboni.
import manage
from django.conf import settings
config = settings.DATABASES['default']
config['HOST'] = config.get('HOST', 'localhost')
config['PORT'] = config.get('POR... | import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Set up zamboni.
import manage
from django.conf import settings
config = settings.DATABASES['default']
config['HOST'] = config.get('HOST', 'localhost')
config['PORT'] = config.get('PORT', '3306')
if not config['HOS... | Make the settings work when there's no port, and fix up the path manipulation | Make the settings work when there's no port, and fix up the path manipulation
| Python | bsd-3-clause | kumar303/zamboni,kmaglione/olympia,Prashant-Surya/addons-server,jamesthechamp/zamboni,yfdyh000/olympia,aviarypl/mozilla-l10n-addons-server,Joergen/zamboni,muffinresearch/addons-server,Jobava/zamboni,koehlermichael/olympia,clouserw/zamboni,kmaglione/olympia,mstriemer/addons-server,Hitechverma/zamboni,mstriemer/olympia,p... | ---
+++
@@ -1,8 +1,7 @@
import sys
import os
-# This only works if you're running schematic from the zamboni root.
-sys.path.insert(0, os.path.realpath('.'))
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Set up zamboni.
import manage
@@ -12,16 +11,20 @@
config['HOST'] = c... |
e53e489da4e9f53e371997449bc813def2600008 | opps/contrib/notifications/models.py | opps/contrib/notifications/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable
from opps.db import Db
NOTIFICATION_TYPE = (
(u'json', _(u'JSON')),
(u'text', _(u'Text')),
(u'html', _(u'HTML')),
)
cla... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable
from opps.db import Db
NOTIFICATION_TYPE = (
(u'json', _(u'JSON')),
(u'text', _(u'Text')),
(u'html', _(u'HTML')),
)
cla... | Add get_absolute_url on notification model | Add get_absolute_url on notification model
| Python | mit | YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps | ---
+++
@@ -37,3 +37,7 @@
"published": self.published,
"date": self.date_available.strftime("%D %T"),
"message": message}))
+
+ def get_absolute_url(self):
+ return u"/{}/{}.server".format(self.container.channel_long_slug,
+ self.c... |
eccda634d3233cd4f8aaeea372735731fd674c29 | pysis/labels/__init__.py | pysis/labels/__init__.py | import io
import functools
import warnings
import six
from .decoder import LabelDecoder
from .encoder import LabelEncoder
def load(stream):
"""Parse an isis label from a stream.
:param stream: a ``.read()``-supporting file-like object containing a label.
if ``stream`` is a string it will be treated ... | import io
import warnings
import six
from .decoder import LabelDecoder
from .encoder import LabelEncoder
def load(stream):
"""Parse an isis label from a stream.
:param stream: a ``.read()``-supporting file-like object containing a label.
if ``stream`` is a string it will be treated as a filename
... | Add depreciation messages to old parse_label methods. | Add depreciation messages to old parse_label methods.
| Python | bsd-3-clause | michaelaye/Pysis,wtolson/pysis,wtolson/pysis,michaelaye/Pysis | ---
+++
@@ -1,5 +1,4 @@
import io
-import functools
import warnings
import six
@@ -41,13 +40,19 @@
return stream.getvalue()
-@functools.wraps(load)
def parse_file_label(stream):
+ load.__doc__ + """
+ deprecated:: 0.4.0
+ Use load instead.
+ """
warnings.warn('parse_file_label is depre... |
14c7f4295701ffbb5c7cd14062a43cb8c86d57de | qtpy/tests/test_qtsql.py | qtpy/tests/test_qtsql.py | from __future__ import absolute_import
import pytest
from qtpy import QtSql
def test_qtsvg():
"""Test the qtpy.QtSql namespace"""
assert QtSql.QSqlDatabase is not None
# assert QtSql.QSqlDriverCreator is not None
assert QtSql.QSqlDriverCreatorBase is not None
assert QtSql.QSqlDriver is not None
... | from __future__ import absolute_import
import pytest
from qtpy import QtSql
def test_qtsvg():
"""Test the qtpy.QtSql namespace"""
assert QtSql.QSqlDatabase is not None
# assert QtSql.QSqlDriverCreator is not None
assert QtSql.QSqlDriverCreatorBase is not None
assert QtSql.QSqlDriver is not None
... | Remove another class (QSqlDriverPlugin) from test | Remove another class (QSqlDriverPlugin) from test
| Python | mit | davvid/qtpy,davvid/qtpy,spyder-ide/qtpy,goanpeca/qtpy,goanpeca/qtpy | ---
+++
@@ -9,7 +9,7 @@
# assert QtSql.QSqlDriverCreator is not None
assert QtSql.QSqlDriverCreatorBase is not None
assert QtSql.QSqlDriver is not None
- assert QtSql.QSqlDriverPlugin is not None
+ #assert QtSql.QSqlDriverPlugin is not None
assert QtSql.QSqlError is not None
assert QtSq... |
0fae7ce68a531b2c27e03a854fba3319d041ee45 | mezzanine/twitter/managers.py | mezzanine/twitter/managers.py |
from django.db.models import Manager
from mezzanine.utils.cache import cache_installed
class TweetManager(Manager):
"""
Manager that handles generating the initial ``Query`` instance
for a user, list or search term.
"""
def get_for(self, user_name=None, list_name=None, search_term=None):
... |
from django.db.models import Manager
class TweetManager(Manager):
"""
Manager that handles generating the initial ``Query`` instance
for a user, list or search term.
"""
def get_for(self, user_name=None, list_name=None, search_term=None):
"""
Create a query and run it for the giv... | Revert cache changes to Twitter queries - since authenticated users bypass the cache, and the Twitter call will generate a lot of queries. | Revert cache changes to Twitter queries - since authenticated users bypass the cache, and the Twitter call will generate a lot of queries.
| Python | bsd-2-clause | viaregio/mezzanine,promil23/mezzanine,biomassives/mezzanine,dekomote/mezzanine-modeltranslation-backport,sjuxax/mezzanine,AlexHill/mezzanine,dustinrb/mezzanine,ZeroXn/mezzanine,theclanks/mezzanine,theclanks/mezzanine,SoLoHiC/mezzanine,guibernardino/mezzanine,dekomote/mezzanine-modeltranslation-backport,emile2016/mezzan... | ---
+++
@@ -1,7 +1,5 @@
from django.db.models import Manager
-
-from mezzanine.utils.cache import cache_installed
class TweetManager(Manager):
@@ -25,7 +23,7 @@
return
from mezzanine.twitter.models import Query
query, created = Query.objects.get_or_create(type=type, value=value)... |
2875a8e6c123d3d4f6039e7864ff66373c51daea | examples/signal_handlers/signal_handlers.py | examples/signal_handlers/signal_handlers.py | # -*- coding: utf-8 -*-
from riot.app import quit_app, run_tag
from riot.tags.style import parse_style
from riot.tags.tags import parse_tag_from_node
from riot.tags.utils import convert_string_to_node
from riot.virtual_dom import define_tag, mount
sig = define_tag('sig', '''
<sig>
<filler valign="top">
<pile>
... | # -*- coding: utf-8 -*-
from riot.app import quit_app, run_tag
from riot.tags.style import parse_style
from riot.tags.tags import parse_tag_from_node
from riot.tags.utils import convert_string_to_node
from riot.virtual_dom import define_tag, mount
sig = define_tag('sig', '''
<sig>
<filler valign="top">
<pile>
... | Remove useless code in signal handler example. | Remove useless code in signal handler example.
| Python | mit | soasme/riotpy | ---
+++
@@ -25,14 +25,7 @@
self.name = opts['name']
def answer(self, edit, text):
- self.update({'name': text})
-
- def exit(self, button):
- import urwid
- raise urwid.ExitMainLoop()
-
-
-
+ self.name = text
</script>
</sig>
''') |
79c0071b7aad2992011684428611701bc58a9bff | tests/__init__.py | tests/__init__.py | try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
import tornado.testing
import tornado.options
import celery
from flower.app import Flower
from flower.urls import handlers
from flower.events import Events
from flower.urls import settings
from flower import command # s... | try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
import tornado.testing
from tornado.options import options
import celery
import mock
from flower.app import Flower
from flower.urls import handlers
from flower.events import Events
from flower.urls import settings
from f... | Add an util funcion for mocking options | Add an util funcion for mocking options
| Python | bsd-3-clause | jzhou77/flower,asmodehn/flower,jzhou77/flower,asmodehn/flower,asmodehn/flower,jzhou77/flower | ---
+++
@@ -4,9 +4,10 @@
from urllib import urlencode
import tornado.testing
-import tornado.options
+from tornado.options import options
import celery
+import mock
from flower.app import Flower
from flower.urls import handlers
@@ -20,8 +21,7 @@
capp = celery.Celery()
events = Events(... |
4aad37d8186fab025ba29050620a929c167ca497 | pulsar/locks.py | pulsar/locks.py | try:
import lockfile
except ImportError:
lockfile = None
import threading
import logging
log = logging.getLogger(__name__)
NO_PYLOCKFILE_MESSAGE = "pylockfile module not found, expect suboptimal Pulsar lock handling."
class LockManager():
def __init__(self, lockfile=lockfile):
if not lockfile:... | try:
import lockfile
except ImportError:
lockfile = None
import threading
import logging
log = logging.getLogger(__name__)
NO_PYLOCKFILE_MESSAGE = "pylockfile module not found, skipping experimental lockfile handling."
class LockManager():
def __init__(self, lockfile=lockfile):
if not lockfile... | Fix misleading message about pylockfile. | Fix misleading message about pylockfile.
| Python | apache-2.0 | ssorgatem/pulsar,natefoo/pulsar,natefoo/pulsar,ssorgatem/pulsar,galaxyproject/pulsar,galaxyproject/pulsar | ---
+++
@@ -8,7 +8,7 @@
import logging
log = logging.getLogger(__name__)
-NO_PYLOCKFILE_MESSAGE = "pylockfile module not found, expect suboptimal Pulsar lock handling."
+NO_PYLOCKFILE_MESSAGE = "pylockfile module not found, skipping experimental lockfile handling."
class LockManager(): |
3f848be239d5fc4ae18d598250e90217b86e8fcf | pywikibot/_wbtypes.py | pywikibot/_wbtypes.py | # -*- coding: utf-8 -*-
"""Wikibase data type classes."""
#
# (C) Pywikibot team, 2013-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import json
from pywikibot.tools import StringTypes
class WbRepresentation(object):
... | # -*- coding: utf-8 -*-
"""Wikibase data type classes."""
#
# (C) Pywikibot team, 2013-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import json
from pywikibot.tools import StringTypes
class WbRepresentation(object):
... | Add missing not-equal comparison for wbtypes | Add missing not-equal comparison for wbtypes
Bug: T158848
Change-Id: Ib6e992b7ed1c5b4b8feac205758bdbaebda2b09c
| Python | mit | hasteur/g13bot_tools_new,magul/pywikibot-core,jayvdb/pywikibot-core,Darkdadaah/pywikibot-core,happy5214/pywikibot-core,hasteur/g13bot_tools_new,magul/pywikibot-core,happy5214/pywikibot-core,wikimedia/pywikibot-core,npdoty/pywikibot,wikimedia/pywikibot-core,jayvdb/pywikibot-core,npdoty/pywikibot,Darkdadaah/pywikibot-cor... | ---
+++
@@ -47,3 +47,6 @@
def __eq__(self, other):
return self.__dict__ == other.__dict__
+
+ def __ne__(self, other):
+ return not self.__eq__(other) |
aa5bc77e78e82fbe63acf2fd8f6764a420f2e4e8 | simuvex/procedures/stubs/caller.py | simuvex/procedures/stubs/caller.py |
import simuvex
######################################
# Caller
######################################
class Caller(simuvex.SimProcedure):
"""
Caller stub. Creates a Ijk_Call exit to the specified function
"""
def run(self, target_addr=None):
self.call(target_addr, [ ], self.after_call)
... |
import simuvex
######################################
# Caller
######################################
class Caller(simuvex.SimProcedure):
"""
Caller stub. Creates a Ijk_Call exit to the specified function
"""
NO_RET = True
def run(self, target_addr=None):
self.call(target_addr, [ ], se... | Make sure Caller does not return | Make sure Caller does not return
| Python | bsd-2-clause | axt/angr,chubbymaggie/angr,iamahuman/angr,tyb0807/angr,tyb0807/angr,chubbymaggie/angr,schieb/angr,iamahuman/angr,schieb/angr,angr/angr,angr/simuvex,iamahuman/angr,chubbymaggie/angr,axt/angr,angr/angr,chubbymaggie/simuvex,tyb0807/angr,angr/angr,f-prettyland/angr,f-prettyland/angr,axt/angr,schieb/angr,chubbymaggie/simuve... | ---
+++
@@ -11,6 +11,8 @@
Caller stub. Creates a Ijk_Call exit to the specified function
"""
+ NO_RET = True
+
def run(self, target_addr=None):
self.call(target_addr, [ ], self.after_call)
|
2da9a6d5f1668bc78995034ba3bb9ed22172e799 | tests/test_cli.py | tests/test_cli.py | import unittest
import os
from EasyEuler.cli import commands
from click.testing import CliRunner
class CommandLineInterfaceTestCase(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
class TestGenerateCommand(CommandLineInterfaceTestCase):
def test_file_creation(self):
with sel... | import unittest
import os
from EasyEuler.cli import commands
from click.testing import CliRunner
class CommandLineInterfaceTestCase(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
class TestGenerateCommand(CommandLineInterfaceTestCase):
def test_file_creation(self):
with sel... | Fix invalid problem ID test | Fix invalid problem ID test
| Python | mit | Encrylize/EasyEuler | ---
+++
@@ -22,7 +22,7 @@
def test_invalid_problem_id(self):
result = self.runner.invoke(commands, ['generate', '9999'])
- self.assertEqual(result.exit_code, 1)
+ self.assertEqual(result.exit_code, 2)
if __name__ == '__main__': |
5b156e3927f2168d9df36f5771c91807704c6dc9 | tests/adjust_unittesting_config_for_ci.py | tests/adjust_unittesting_config_for_ci.py | from os.path import abspath, dirname, join
import json
if __name__ == '__main__':
file = abspath(join(dirname(__file__), '..', 'unittesting.json'))
with open(file, 'w') as fp:
config = {
"deferred": True,
"verbosity": 0,
"capture_console": True,
"failfas... | from os.path import abspath, dirname, join
import json
if __name__ == '__main__':
file = abspath(join(dirname(__file__), '..', 'unittesting.json'))
with open(file, 'w') as fp:
config = {
"deferred": True,
"verbosity": 2,
"capture_console": True,
"failfas... | Put verbosity to 2 for the tests because otherwise the ci script things we're hanging | Put verbosity to 2 for the tests because otherwise the ci script things we're hanging
| Python | mit | tomv564/LSP | ---
+++
@@ -7,7 +7,7 @@
with open(file, 'w') as fp:
config = {
"deferred": True,
- "verbosity": 0,
+ "verbosity": 2,
"capture_console": True,
"failfast": True,
"reload_package_on_testing": False, |
18a8a9e90ab0dd31ca1ee147f85d16d0cc7e6bc1 | api/__init__.py | api/__init__.py | from api.models import BaseTag
TAGS = {
'fairness': {
'color': '#bcf0ff',
'description': 'Fairness is ideas of justice, rights, and autonomy.',
},
'cheating': {
'color': '#feffbc',
'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.',
},
'loyalty': {
... | Add script to populate Base Tags on app startup | Add script to populate Base Tags on app startup
| Python | mit | haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server | ---
+++
@@ -0,0 +1,60 @@
+from api.models import BaseTag
+
+TAGS = {
+ 'fairness': {
+ 'color': '#bcf0ff',
+ 'description': 'Fairness is ideas of justice, rights, and autonomy.',
+ },
+ 'cheating': {
+ 'color': '#feffbc',
+ 'description': 'Cheating is acting dishonestly or unfairly in order to gain an ... | |
47348a032bf86aac563dca41703f1e39d03b2360 | aplpy/header.py | aplpy/header.py | from __future__ import absolute_import
def check(header, convention=None, dimensions=[0, 1]):
ix = dimensions[0] + 1
iy = dimensions[1] + 1
ctypex = header['CTYPE%i' % ix]
crvaly = header['CRVAL%i' % iy]
crpixy = header['CRPIX%i' % iy]
cdelty = header['CDELT%i' % iy]
# Check for CRVAL2!... | from __future__ import absolute_import
def check(header, convention=None, dimensions=[0, 1]):
ix = dimensions[0] + 1
iy = dimensions[1] + 1
ctypex = header['CTYPE%i' % ix]
crvaly = header['CRVAL%i' % iy]
# Check for CRVAL2!=0 for CAR projection
if ctypex[4:] == '-CAR' and crvaly != 0:
... | Fix check for Wells/Calabretta convention | Fix check for Wells/Calabretta convention | Python | mit | mwcraig/aplpy,allisony/aplpy | ---
+++
@@ -8,14 +8,17 @@
ctypex = header['CTYPE%i' % ix]
crvaly = header['CRVAL%i' % iy]
- crpixy = header['CRPIX%i' % iy]
- cdelty = header['CDELT%i' % iy]
# Check for CRVAL2!=0 for CAR projection
if ctypex[4:] == '-CAR' and crvaly != 0:
if convention in ['wells', 'calabrett... |
11abf077a8c429825c2ba55e42ffa590448da502 | examples/django_app/tests/test_settings.py | examples/django_app/tests/test_settings.py | from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
... | from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
... | Fix unit tests for Django 1.8 | Fix unit tests for Django 1.8
| Python | bsd-3-clause | vkosuri/ChatterBot,davizucon/ChatterBot,Reinaesaya/OUIRL-ChatBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot,maclogan/VirtualPenPal,Reinaesaya/OUIRL-ChatBot | ---
+++
@@ -16,6 +16,6 @@
response = self.client.get(api_url)
self.assertEqual(response.status_code, 405)
- self.assertIn('detail', response.json())
- self.assertIn('name', response.json())
- self.assertEqual('Django ChatterBot Example', response.json()['name'])
+ self.... |
9e08eaea0259c702fea2055c4f72d66f8efe204d | fedmsg/schema.py | fedmsg/schema.py | AGENT = 'agent' # Generic use. "Who is responsible for this event?"
FIELDS = 'fields' # A list of fields that may be of interest. For instance,
# fas uses this to specify which fields were updated in
# a user.update event.
USER = 'user' # FAS
GROUP = 'group' # ... | __schema = dict(
AGENT = 'agent', # Generic use. "Who is responsible for this event?"
FIELDS = 'fields', # A list of fields that may be of interest. For instance,
# fas uses this to specify which fields were updated in
# a user.update event.
USER = ... | Fix a bug on python-2.6 and use a frozenset() | Fix a bug on python-2.6 and use a frozenset()
Signed-off-by: Ralph Bean <bcd66b84ebceb8404db9191d837c83f1b20bab8e@redhat.com>
| Python | lgpl-2.1 | chaiku/fedmsg,pombredanne/fedmsg,chaiku/fedmsg,chaiku/fedmsg,pombredanne/fedmsg,maxamillion/fedmsg,cicku/fedmsg,maxamillion/fedmsg,maxamillion/fedmsg,cicku/fedmsg,pombredanne/fedmsg,cicku/fedmsg,mathstuf/fedmsg,fedora-infra/fedmsg,vivekanand1101/fedmsg,fedora-infra/fedmsg,vivekanand1101/fedmsg,mathstuf/fedmsg,vivekanan... | ---
+++
@@ -1,18 +1,24 @@
-AGENT = 'agent' # Generic use. "Who is responsible for this event?"
-FIELDS = 'fields' # A list of fields that may be of interest. For instance,
- # fas uses this to specify which fields were updated in
- # a user.update event.
+__schema = dict(... |
f9b3fd3d5e14c7ecfc59848e9edf6d99d5c6b98d | ffmpy/ffprobe.py | ffmpy/ffprobe.py | import json
from ffmpy import FF
class FFprobe(FF):
"""
Wrapper for `ffprobe <https://www.ffmpeg.org/ffprobe.html>`_.
Utilizes ffmpeg `pipe protocol <https://www.ffmpeg.org/ffmpeg-protocols.html#pipe>`_. Input data
(as a byte string) is passed to ffprobe on standard input. Result is presented in JSO... | import json
from ffmpy import FF
class FFprobe(FF):
"""
Wrapper for `ffprobe <https://www.ffmpeg.org/ffprobe.html>`_.
Utilizes ffmpeg `pipe protocol <https://www.ffmpeg.org/ffmpeg-protocols.html#pipe>`_. Input data
(as a byte string) is passed to ffprobe on standard input. Result is presented in JSO... | Fix json parsing for Python 3 | Fix json parsing for Python 3 | Python | mit | Ch00k/ffmpy,wchill/ffmpy3,astroza/ffmpy,astroza/ffmpy,Ch00k/ffmpy,wchill/ffmpy3 | ---
+++
@@ -35,7 +35,7 @@
"""
output = super(FFprobe, self).run(input_data)
if '-print_format json' in self.cmd_str:
- output = json.loads(output)
+ output = json.loads(output.decode())
# TODO: Convert all "numeric" strings to int/float
return outpu... |
9836c275d79851010654aacda379ccb78cea1b27 | chartflo/engine.py | chartflo/engine.py | import pandas as pd
from goerr import err
from dataswim import DataSwim
from django.db.models.query import QuerySet
from django_pandas.io import read_frame
class ChartFlo(DataSwim):
def __repr__(self):
"""
String representation of the object
"""
rows = str(len(self.df.columns))
... | from dataswim import DataSwim
class ChartFlo(DataSwim):
def __repr__(self):
"""
String representation of the object
"""
rows = str(len(self.df.columns))
return '<Chartflo object - ' + rows + " >"
cf = ChartFlo()
| Move the load_data method to the Dataswim lib | Move the load_data method to the Dataswim lib
| Python | mit | synw/django-chartflo,synw/django-chartflo,synw/django-chartflo | ---
+++
@@ -1,8 +1,4 @@
-import pandas as pd
-from goerr import err
from dataswim import DataSwim
-from django.db.models.query import QuerySet
-from django_pandas.io import read_frame
class ChartFlo(DataSwim):
@@ -14,63 +10,5 @@
rows = str(len(self.df.columns))
return '<Chartflo object - ' + r... |
b28dd26792be9125d2fd3d5657431bc6ee7a5470 | lobster/cmssw/actions.py | lobster/cmssw/actions.py | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... | Add message in log with plotting process id. | Add message in log with plotting process id.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster | ---
+++
@@ -26,6 +26,7 @@
self.plotq = multiprocessing.Queue()
self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,))
self.plotp.start()
+ logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid))
self.__last = datetime.date... |
6e76b51f5aa1c5ae54130f52e176195a992284aa | src/core/monkeypatch.py | src/core/monkeypatch.py | from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse
from django.utils.encoding import iri_to_uri
from core.middleware import GlobalRequestMiddleware
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""
This monkey patch will add the jo... | from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse
from django.utils.encoding import iri_to_uri
from core.middleware import GlobalRequestMiddleware
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""
This monkey patch will add the jo... | Update for janeway's monkey patch. | Update for janeway's monkey patch.
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway | ---
+++
@@ -27,7 +27,10 @@
# Drop kwargs if we have args (most likely from the template
if args:
kwargs = None
- args = [code] + args
+ if settings.URL_CONFIG == 'path' and not local_request.path.startswith('/admin/'):
+ args ... |
986b15b5f33ebf25b26f40645378174bb66f1898 | gerberlicious.py | gerberlicious.py |
"""
gerberlicious, a python library for programmatically generating Gerber files
Example script.
"""
from gerberlicious.point import Point
from gerberlicious.layer import Layer
from gerberlicious.aperture import CircleAperture
from gerberlicious.drawable import PointList, ApertureFlash
from gerberlicious.ren... |
"""
gerberlicious, a python library for programmatically generating Gerber files
Example script.
"""
from gerberlicious.point import Point
from gerberlicious.layer import Layer
from gerberlicious.aperture import CircleAperture
from gerberlicious.drawable import PointList, ApertureFlash
from gerberlicious.ren... | Rename 'square' to 'path' in example script | Rename 'square' to 'path' in example script
| Python | mit | deveah/gerberlicious | ---
+++
@@ -20,14 +20,14 @@
aperture2 = CircleAperture("11", 0.2, 0.1)
layer.add_aperture(aperture2)
- square = PointList(aperture1)
- square.add_point(Point(2.5, 0))
- square.add_point(Point(5, 0))
- square.add_point(Point(5, 5))
- square.add_point(Point(0, 5))
- square.add_point(Point(... |
ed667175f4961bbc7cc823657a5dd80f35ed9593 | organizer/migrations/0002_tag_data.py | organizer/migrations/0002_tag_data.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
TAGS = (
# ( tag name, tag slug ),
("augmented reality", "augmented-reality"),
("big data", "big-data"),
("django", "django"),
("education", "education"),
("ipython", "ipython"),
("java... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
TAGS = (
# ( tag name, tag slug ),
("augmented reality", "augmented-reality"),
("big data", "big-data"),
("django", "django"),
("education", "education"),
("ipython", "ipython"),
("java... | Optimize addition of Tag data in migration. | Ch26: Optimize addition of Tag data in migration.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | ---
+++
@@ -26,10 +26,11 @@
def add_tag_data(apps, schema_editor):
Tag = apps.get_model('organizer', 'Tag')
+ tag_list = []
for tag_name, tag_slug in TAGS:
- Tag.objects.create(
- name=tag_name,
- slug=tag_slug)
+ tag_list.append(
+ Tag(name=tag_name, slu... |
cb17da3fbd819a386446bc2af42e38f8c95bc392 | blango/forms.py | blango/forms.py | from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
try:
from django import newforms as forms
except ImportError:
from django import forms
from blango.models import Comment
# This violates the DRY principe, but it's the ... | from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
try:
from django import newforms as forms
except ImportError:
from django import forms
from blango.models import Comment
# This violates the DRY principe, but it's the ... | Fix UserCommentForm(), which got broken in the previous commit. | Fix UserCommentForm(), which got broken in the previous commit.
| Python | bsd-3-clause | fiam/blangoblog,fiam/blangoblog,fiam/blangoblog | ---
+++
@@ -41,5 +41,6 @@
def save(self, entry, request):
self.instance.user = request.user
+ self.instance.entry = entry
super(UserCommentForm, self).save(entry)
|
b0311af3895b359ce3a1ea1fad953c0b41585ce8 | app/cache_handler.py | app/cache_handler.py | """This module contains a cache handler."""
__author__ = 'Aaron Steele'
# MOL imports
import cache
# Standard Python imports
import json
import logging
import urllib
import webapp2
# Google App Engine imports
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
class ... | """This module contains a cache handler."""
__author__ = 'Aaron Steele'
# MOL imports
import cache
# Standard Python imports
import json
import logging
import urllib
import webapp2
# Google App Engine imports
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
class ... | Add logging of search key to cache handler. | Add logging of search key to cache handler.
| Python | bsd-3-clause | MapofLife/MOL,MapofLife/MOL,MapofLife/MOL,MapofLife/MOL,MapofLife/MOL,MapofLife/MOL,MapofLife/MOL,MapofLife/MOL | ---
+++
@@ -21,6 +21,7 @@
def post(self):
"""Returns a cached value by key or None if it doesn't exist."""
key = self.request.get('key', 'empty')
+ logging.info('SEARCH_KEY=%s' % key)
sql = self.request.get('sql', None)
cache_buster = self.request.get('cache_buster', No... |
c78d9c63238b5535b1881f4eee54700f5a138b04 | lupa/__init__.py | lupa/__init__.py |
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
# do it temporarily.
def _try_import_with_global_library_symbols():
try:
import DLFCN
dlopen_flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL
except ImportError:
... | from __future__ import absolute_import
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
# do it temporarily.
def _try_import_with_global_library_symbols():
try:
from os import RTLD_NOW, RTLD_GLOBAL
except ImportErr... | Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2. | Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2.
| Python | mit | pombredanne/lupa,pombredanne/lupa | ---
+++
@@ -1,3 +1,5 @@
+from __future__ import absolute_import
+
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
@@ -5,11 +7,10 @@
def _try_import_with_global_library_symbols():
try:
- import DLFCN
- dlo... |
fc2c3ec6680e8c1102a336ec0f6bde7db32d2070 | tests/tools/assigner/test_arguments.py | tests/tools/assigner/test_arguments.py | import inspect
import sys
import unittest
from contextlib import contextmanager
import kafka.tools.assigner.actions
from kafka.tools.assigner.arguments import set_up_arguments
from kafka.tools.assigner.modules import get_modules
from kafka.tools.assigner.plugins import PluginModule
@contextmanager
def redirect_err... | import inspect
import sys
import unittest
from contextlib import contextmanager
import kafka.tools.assigner.actions
from kafka.tools.assigner.arguments import set_up_arguments
from kafka.tools.assigner.modules import get_modules
from kafka.tools.assigner.plugins import PluginModule
@contextmanager
def redirect_err... | Call the CM to mask stderr output properly | Call the CM to mask stderr output properly
| Python | apache-2.0 | toddpalino/kafka-tools | ---
+++
@@ -30,7 +30,7 @@
def test_get_arguments_none(self):
sys.argv = ['kafka-assigner']
- with capture_sys_output() as (stdout, stderr):
+ with redirect_err_output():
self.assertRaises(SystemExit, set_up_arguments, {}, {}, [self.null_plugin])
def test_get_modules(s... |
1cc044e601dc6b6d2a5f62c7557a6cd2d5b50986 | homepage/views.py | homepage/views.py | from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api
def index(request):
uid = request.COOKIES.get("uid")
if not uid:
uid, data = api.create_new_user()
else:
data = api.get_saved_cities(uid)
resp... | from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api
def index(request):
uid = request.COOKIES.get("uid")
data = None
if not uid:
uid, _ = api.create_new_user()
else:
data = api.get_saved_cities(u... | Fix create user in homepage view. | Fix create user in homepage view.
api.create_new_user is returning the newly created user record, so we can't pass that as data to the template.
| Python | mit | c17r/tsace,c17r/tsace,c17r/tsace | ---
+++
@@ -6,8 +6,9 @@
def index(request):
uid = request.COOKIES.get("uid")
+ data = None
if not uid:
- uid, data = api.create_new_user()
+ uid, _ = api.create_new_user()
else:
data = api.get_saved_cities(uid)
|
c755934a9bc9f15f1e7dcf6d337c3dd3acf4e824 | checks/check_solarize.py | checks/check_solarize.py | import imgaug as ia
import imgaug.augmenters as iaa
def main():
image = ia.quokka_square((128, 128))
images_aug = iaa.Solarize(1.0)(images=[image] * (5*5))
ia.imshow(ia.draw_grid(images_aug))
if __name__ == "__main__":
main()
| from __future__ import print_function, division, absolute_import
import imgaug as ia
import imgaug.augmenters as iaa
import timeit
def main():
for size in [64, 128, 256, 512, 1024]:
for threshold in [64, 128, 192]:
time_iaa = timeit.timeit(
"iaa.solarize(image, %d)" % (threshol... | Add performance comparison with PIL | Add performance comparison with PIL
| Python | mit | aleju/ImageAugmenter,aleju/imgaug,aleju/imgaug | ---
+++
@@ -1,8 +1,35 @@
+from __future__ import print_function, division, absolute_import
import imgaug as ia
import imgaug.augmenters as iaa
+import timeit
def main():
+ for size in [64, 128, 256, 512, 1024]:
+ for threshold in [64, 128, 192]:
+ time_iaa = timeit.timeit(
+ ... |
3068b3d55082947fcd0594945a705c3cc34659ca | tests/test_python_solutions.py | tests/test_python_solutions.py | import glob
import json
import os
import pytest
from helpers import solutions_dir
# NOTE: If we make solution_files a fixture instead of a normal attr/function,
# then we can't use it in pytest's parametrize
solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py"))
@pytest.mark.python
def test_sol... | import glob
import json
import os
import pytest
from helpers import solutions_dir
# NOTE: If we make solution_files a fixture instead of a normal attr/function,
# then we can't use it in pytest's parametrize
solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py"))
@pytest.mark.python
def test_pyt... | Rename functions in python test | Rename functions in python test
| Python | mit | project-lovelace/lovelace-engine,project-lovelace/lovelace-engine,project-lovelace/lovelace-engine | ---
+++
@@ -13,7 +13,7 @@
@pytest.mark.python
-def test_solutions_exist():
+def test_python_solutions_exist():
assert solution_files
|
418be2bfa0f902183b607fa402da75c09bf7e6db | hug/decorators.py | hug/decorators.py | from functools import wraps
from collections import OrderedDict
import sys
def call(url, methods=('ALL', )):
def decorator(api_function):
module = sys.modules[api_function.__name__]
api_definition = sys.modules['hug.hug'].__dict__.setdefault('API_CALLS', OrderedDict())
for method in method... | from functools import wraps
from collections import OrderedDict
import sys
from falcon import HTTP_METHODS
def call(url, methods=HTTP_METHODS):
def decorator(api_function):
module = sys.modules[api_function.__name__]
api_definition = sys.modules['hug.hug'].__dict__.setdefault('HUG_API_CALLS', Ord... | Use falcon methods as HTTP methods | Use falcon methods as HTTP methods
| Python | mit | STANAPO/hug,shaunstanislaus/hug,shaunstanislaus/hug,timothycrosley/hug,philiptzou/hug,janusnic/hug,timothycrosley/hug,MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,jean/hug,giserh/hug,origingod/hug,janusnic/hug,yasoob/hug,gbn972/hug,MuhammadAlkarouri/hug,jean/hug,giserh/hug,timothycrosley/hug,gbn972/hug,alisaifee/hug,yas... | ---
+++
@@ -2,13 +2,15 @@
from collections import OrderedDict
import sys
+from falcon import HTTP_METHODS
-def call(url, methods=('ALL', )):
+
+def call(url, methods=HTTP_METHODS):
def decorator(api_function):
module = sys.modules[api_function.__name__]
- api_definition = sys.modules['hug.h... |
edcf561564a8fe30c80bda750ec0770c5e854ce8 | Code/Python/Kamaelia/Examples/Backplane/Forwarding.py | Code/Python/Kamaelia/Examples/Backplane/Forwarding.py | #!/usr/bin/python
import time
import Axon
from Kamaelia.Util.Backplane import *
from Kamaelia.Util.Console import *
from Kamaelia.Chassis.Pipeline import Pipeline
class Source(Axon.ThreadedComponent.threadedcomponent):
value = 1
sleep = 1
def main(self):
while 1:
self.send(str(self.val... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ver... | Change license to Apache 2 | Change license to Apache 2 | Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia | ---
+++
@@ -1,4 +1,23 @@
#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
+#
+# (1) Kamaelia Contributors are listed in the AUTHORS file and at
+# http://www.kamaelia.org/AUTHORS - please extend this file,
+# not this notice.
+#
+# L... |
6610648c75dc90800655a3502d4cd24fb47ac406 | timpani/webserver/webserver.py | timpani/webserver/webserver.py | import flask
import os.path
import datetime
import urllib.parse
from .. import database
from .. import configmanager
from . import controllers
FILE_LOCATION = os.path.abspath(os.path.dirname(__file__))
STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static"))
CONFIG_PATH = os.path.abspath(os.path.join... | import flask
import os.path
import datetime
import urllib.parse
from .. import database
from .. import configmanager
from . import controllers
FILE_LOCATION = os.path.abspath(os.path.dirname(__file__))
STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static"))
CONFIG_PATH = os.path.abspath(os.path.join... | Remove session cookie print in teardown | Remove session cookie print in teardown
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani | ---
+++
@@ -20,6 +20,5 @@
@app.teardown_request
def teardown_request(exception = None):
- print(flask.session)
databaseConnection = database.ConnectionManager.getMainConnection()
databaseConnection.session.close() |
9793107fb218bdff796d8df55404156e299e33ea | website/apps/ts_om/check.py | website/apps/ts_om/check.py | import os
from django.conf import settings
__author__ = 'nreed'
url_dict = {
'validate': 'http://127.0.0.1:8000/om_validate/validate/',
'scenarios': '/home/nreed/scenarios/',
'openmalaria': getattr(settings, "PROJECT_ROOT", '') + '/om_validate/bin/'
}
def check_dir(local_dir, typ):
if local_dir is ... | import os
from django.conf import settings
__author__ = 'nreed'
url_dict = {
'validate': 'http://127.0.0.1:8000/om_validate/validate/',
'scenarios': getattr(settings, "PROJECT_ROOT", '') + '/scenarios/',
'openmalaria': getattr(settings, "PROJECT_ROOT", '') + '/om_validate/bin/'
}
def check_dir(local_di... | Set default scenarios directory to within root of project. | Set default scenarios directory to within root of project.
| Python | mpl-2.0 | vecnet/om,vecnet/om,vecnet/om,vecnet/om,vecnet/om | ---
+++
@@ -6,7 +6,7 @@
url_dict = {
'validate': 'http://127.0.0.1:8000/om_validate/validate/',
- 'scenarios': '/home/nreed/scenarios/',
+ 'scenarios': getattr(settings, "PROJECT_ROOT", '') + '/scenarios/',
'openmalaria': getattr(settings, "PROJECT_ROOT", '') + '/om_validate/bin/'
}
|
b04a01f451b2fe0348af217e9eed905b552cf1cf | lc0201_bitwise_and_of_numbers_range.py | lc0201_bitwise_and_of_numbers_range.py | """Leetcode 201. Bitwise AND of Numbers Range
Medium
URL: https://leetcode.com/problems/bitwise-and-of-numbers-range/
Given a range [m, n] where 0 <= m <= n <= 2147483647,
return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
"""
class ... | """Leetcode 201. Bitwise AND of Numbers Range
Medium
URL: https://leetcode.com/problems/bitwise-and-of-numbers-range/
Given a range [m, n] where 0 <= m <= n <= 2147483647,
return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
"""
class ... | Revise class name and add time/space complexity | Revise class name and add time/space complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -16,12 +16,17 @@
"""
-class Solution(object):
+class SolutionBruteForce(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
+
+ Time limit exceeded.
+
+ Time complexity: O(n-m).
+ Space complexity: O(1).
... |
d10344dce7d012de2d434cd205fb0f179e34113c | packages/syft/src/syft/core/tensor/types.py | packages/syft/src/syft/core/tensor/types.py | # relative
from .passthrough import AcceptableSimpleType # type: ignore
from .passthrough import PassthroughTensor # type: ignore
from .passthrough import SupportedChainType # type: ignore
| from .passthrough import AcceptableSimpleType # type: ignore # NOQA
from .passthrough import PassthroughTensor # type: ignore # NOQA
from .passthrough import SupportedChainType # type: ignore # NOQA
| Fix flake8 warning by adding flake annotation | Fix flake8 warning by adding flake annotation
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | ---
+++
@@ -1,4 +1,3 @@
-# relative
-from .passthrough import AcceptableSimpleType # type: ignore
-from .passthrough import PassthroughTensor # type: ignore
-from .passthrough import SupportedChainType # type: ignore
+from .passthrough import AcceptableSimpleType # type: ignore # NOQA
+from .passthrough import Pa... |
c576acc020e60e704dad55f8cd281c4ebb26ad28 | plenario/apiary/views.py | plenario/apiary/views.py | from flask import Blueprint, request
from json import dumps, loads
from redis import Redis
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis(REDIS_HOST_SAFE)
@blueprint.route("/apiary/send_message", methods=["POST"])
def send_message():
try:
data = lo... | from collections import defaultdict
from json import dumps, loads
from traceback import format_exc
from flask import Blueprint, make_response, request
from redis import Redis
from plenario.auth import login_required
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis... | Add a rudimentary view for tracking mapper errors | Add a rudimentary view for tracking mapper errors
| Python | mit | UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario | ---
+++
@@ -1,18 +1,32 @@
-from flask import Blueprint, request
+from collections import defaultdict
from json import dumps, loads
+from traceback import format_exc
+
+from flask import Blueprint, make_response, request
from redis import Redis
+from plenario.auth import login_required
from plenario.settings impo... |
32522114db3c9afc5331a898df3b956b6a3d229a | imagekit/conf.py | imagekit/conf.py | from appconf import AppConf
from django.conf import settings
class ImageKitConf(AppConf):
CACHEFILE_NAMER = 'imagekit.cachefiles.namers.hash'
SPEC_CACHEFILE_NAMER = 'imagekit.cachefiles.namers.source_name_as_path'
CACHEFILE_DIR = 'CACHE/images'
DEFAULT_CACHEFILE_BACKEND = 'imagekit.cachefiles.backends... | from appconf import AppConf
from django.conf import settings
class ImageKitConf(AppConf):
CACHEFILE_NAMER = 'imagekit.cachefiles.namers.hash'
SPEC_CACHEFILE_NAMER = 'imagekit.cachefiles.namers.source_name_as_path'
CACHEFILE_DIR = 'CACHE/images'
DEFAULT_CACHEFILE_BACKEND = 'imagekit.cachefiles.backends... | Improve default cache backend handling | Improve default cache backend handling
| Python | bsd-3-clause | FundedByMe/django-imagekit,tawanda/django-imagekit,tawanda/django-imagekit,FundedByMe/django-imagekit | ---
+++
@@ -17,10 +17,21 @@
def configure_cache_backend(self, value):
if value is None:
- if getattr(settings, 'CACHES', None):
- value = 'django.core.cache.backends.dummy.DummyCache' if settings.DEBUG else 'default'
+ try:
+ from django.core.cache.b... |
ef17e9368cd7776f5777f095ab7dbc0c0f38a326 | common/lib/capa/setup.py | common/lib/capa/setup.py | from setuptools import setup, find_packages
setup(
name="capa",
version="0.1",
packages=find_packages(exclude=["tests"]),
install_requires=['distribute==0.6.30', 'pyparsing==1.5.6'],
)
| from setuptools import setup, find_packages
setup(
name="capa",
version="0.1",
packages=find_packages(exclude=["tests"]),
install_requires=['distribute==0.6.28', 'pyparsing==1.5.6'],
)
| Make capa specify distribute 0.6.28 like the rest of the project | Make capa specify distribute 0.6.28 like the rest of the project
| Python | agpl-3.0 | shubhdev/edx-platform,mcgachey/edx-platform,philanthropy-u/edx-platform,zofuthan/edx-platform,polimediaupv/edx-platform,SravanthiSinha/edx-platform,rue89-tech/edx-platform,louyihua/edx-platform,adoosii/edx-platform,4eek/edx-platform,BehavioralInsightsTeam/edx-platform,LICEF/edx-platform,mbareta/edx-platform-ft,shubhdev... | ---
+++
@@ -4,5 +4,5 @@
name="capa",
version="0.1",
packages=find_packages(exclude=["tests"]),
- install_requires=['distribute==0.6.30', 'pyparsing==1.5.6'],
+ install_requires=['distribute==0.6.28', 'pyparsing==1.5.6'],
) |
6b6181f1c2f902f20da440eb3bedb5d02ecfbf16 | angr/engines/soot/expressions/cast.py | angr/engines/soot/expressions/cast.py |
from .base import SimSootExpr
from archinfo import ArchSoot
import logging
l = logging.getLogger("angr.engines.soot.expressions.cast")
class SimSootExpr_Cast(SimSootExpr):
def __init__(self, expr, state):
super(SimSootExpr_Cast, self).__init__(expr, state)
def _execute(self):
if self.expr.... |
from .base import SimSootExpr
from archinfo import ArchSoot
import logging
l = logging.getLogger("angr.engines.soot.expressions.cast")
class SimSootExpr_Cast(SimSootExpr):
def __init__(self, expr, state):
super(SimSootExpr_Cast, self).__init__(expr, state)
def _execute(self):
if self.expr.... | Use correct dict for the type sizes | Use correct dict for the type sizes
| Python | bsd-2-clause | iamahuman/angr,iamahuman/angr,iamahuman/angr,angr/angr,schieb/angr,schieb/angr,angr/angr,schieb/angr,angr/angr | ---
+++
@@ -21,7 +21,7 @@
value_uncasted = self.state.memory.load(local)
# lookup the type size and extract value
- value_size = ArchSoot.primitive_types[self.expr.cast_type]
+ value_size = ArchSoot.sizeof[self.expr.cast_type]
value_extracted = value_uncasted.reversed.get_... |
bb0fae91cc0ce067a0e331bc953c7130be4e41c8 | neuroimaging/externals/pynifti/nifti/__init__.py | neuroimaging/externals/pynifti/nifti/__init__.py |
from niftiimage import NiftiImage
| """
Nifti
=====
Python bindings for the nifticlibs. Access through the NiftiImage class.
See help for pyniftiio.nifti.NiftiImage
"""
from niftiimage import NiftiImage
| Add doc for pynifti package. | DOC: Add doc for pynifti package. | Python | bsd-3-clause | yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD | ---
+++
@@ -1,2 +1,11 @@
+"""
+Nifti
+=====
+
+ Python bindings for the nifticlibs. Access through the NiftiImage class.
+
+ See help for pyniftiio.nifti.NiftiImage
+
+"""
from niftiimage import NiftiImage |
2864441be365beb40e0396b444f8d96af8d7d92e | aleph/logic/documents.py | aleph/logic/documents.py | import os
import logging
from aleph.core import db, archive
from aleph.model import Document
from aleph.queues import ingest_entity
log = logging.getLogger(__name__)
def crawl_directory(collection, path, parent=None):
"""Crawl the contents of the given path."""
content_hash = None
if not path.is_dir():
... | import os
import logging
from servicelayer.jobs import Job
from aleph.core import db, archive
from aleph.model import Document
from aleph.queues import ingest_entity
log = logging.getLogger(__name__)
def crawl_directory(collection, path, parent=None, job_id=None):
"""Crawl the contents of the given path."""
... | Make stable job IDs in ingest runs | Make stable job IDs in ingest runs
| Python | mit | alephdata/aleph,pudo/aleph,pudo/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,pudo/aleph | ---
+++
@@ -1,5 +1,6 @@
import os
import logging
+from servicelayer.jobs import Job
from aleph.core import db, archive
from aleph.model import Document
@@ -8,7 +9,7 @@
log = logging.getLogger(__name__)
-def crawl_directory(collection, path, parent=None):
+def crawl_directory(collection, path, parent=None, ... |
ae2f1014bbe83d64f17fee6a9ebd2c12cdc9a1bf | app/main/errors.py | app/main/errors.py | from flask import render_template
from app.main import main
@main.app_errorhandler(400)
def bad_request(e):
return render_template("errors/500.html",
**main.config['BASE_TEMPLATE_DATA']), 400
@main.app_errorhandler(404)
def page_not_found(e):
return render_template("errors/404.htm... | from flask import render_template
from app.main import main
from dmutils.apiclient import APIError
@main.app_errorhandler(APIError)
def api_error(e):
return _render_error_template(e.status_code)
@main.app_errorhandler(400)
def bad_request(e):
return _render_error_template(400)
@main.app_errorhandler(404)
... | Add APIError flask error handler | Add APIError flask error handler
This is modelled after the similar change in the supplier frontend
https://github.com/alphagov/digitalmarketplace-supplier-frontend/commit/233f8840d55cadb9fb7fe60ff12c53b0f59f23a5
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend | ---
+++
@@ -1,26 +1,42 @@
from flask import render_template
from app.main import main
+from dmutils.apiclient import APIError
+
+
+@main.app_errorhandler(APIError)
+def api_error(e):
+ return _render_error_template(e.status_code)
@main.app_errorhandler(400)
def bad_request(e):
- return render_template("... |
3cf44a081f6dc824e1ff0639f424c0502fa6fe39 | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store',
dest='foo',
help='Set the value for the fixture "bar".'
)
@pytest.fixture
def bar(request):
return re... | # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store',
dest='foo',
default={{cookiecutter.year}},
help='Set the value for the fixture "bar".'
)
@pytest.... | Add a default to the foo option | Add a default to the foo option
| Python | mit | s0undt3ch/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin,luzfcb/cookiecutter-pytest-plugin | ---
+++
@@ -9,6 +9,7 @@
'--foo',
action='store',
dest='foo',
+ default={{cookiecutter.year}},
help='Set the value for the fixture "bar".'
)
|
095d8d0136ff3942a9fcc76564a61e17dae56b71 | goldprice.py | goldprice.py | #!/usr/bin/python
# Maybank Gold Investment Account price scraper
# Using BeautifulSoup package
# Developed and tested on Debian Testing (Jessie)
# Initial development 25 July 2012
# Copyright (C) 2012,2013 Sharuzzaman Ahmat Raslan (sharuzzaman@gmail.com)
#
# This program is free software: you can redistribute it an... | #!/usr/bin/python
# Maybank Gold Investment Account price scraper
# Using BeautifulSoup package
# Developed and tested on Debian Testing (Jessie)
# Initial development 25 July 2012
# Copyright (C) 2012,2013 Sharuzzaman Ahmat Raslan (sharuzzaman@gmail.com)
#
# This program is free software: you can redistribute it an... | Fix breakage. The website is looking for user-agent header | Fix breakage. The website is looking for user-agent header
| Python | agpl-3.0 | sharuzzaman/sharuzzaman-code-repo.maybank-gia-rate | ---
+++
@@ -24,7 +24,10 @@
from BeautifulSoup import BeautifulSoup
import datetime
-website=urllib2.urlopen('http://www.maybank2u.com.my/mbbfrx/gold_rate.htm')
+#maybank website looking for user-agent header
+req = urllib2.Request('http://www.maybank2u.com.my/mbbfrx/gold_rate.htm')
+req.add_header('User-Agent', '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.