commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
|---|---|---|---|---|---|---|---|
9afb9954f5d58fe051f60bd336a39d794699d405
|
add a demo that plots a comparison of threshold types
|
demo/plot_thresholds.py
|
demo/plot_thresholds.py
|
Python
| 0
|
@@ -0,0 +1,994 @@
+import numpy as np%0Aimport matplotlib.pyplot as plt%0Aimport pywt%0A%0As = np.linspace(-4, 4, 1000)%0A%0As_soft = pywt.threshold(s, value=0.5, mode='soft')%0As_hard = pywt.threshold(s, value=0.5, mode='hard')%0As_garotte = pywt.threshold(s, value=0.5, mode='garotte')%0As_firm1 = pywt.threshold_firm(s, value_low=0.5, value_high=1)%0As_firm2 = pywt.threshold_firm(s, value_low=0.5, value_high=2)%0As_firm3 = pywt.threshold_firm(s, value_low=0.5, value_high=4)%0A%0Afig, ax = plt.subplots(1, 2, figsize=(10, 4))%0Aax%5B0%5D.plot(s, s_soft)%0Aax%5B0%5D.plot(s, s_hard)%0Aax%5B0%5D.plot(s, s_garotte)%0Aax%5B0%5D.legend(%5B'soft (0.5)', 'hard (0.5)', 'non-neg. garotte (0.5)'%5D)%0Aax%5B0%5D.set_xlabel('input value')%0Aax%5B0%5D.set_ylabel('thresholded value')%0A%0Aax%5B1%5D.plot(s, s_soft)%0Aax%5B1%5D.plot(s, s_hard)%0Aax%5B1%5D.plot(s, s_firm1)%0Aax%5B1%5D.plot(s, s_firm2)%0Aax%5B1%5D.plot(s, s_firm3)%0Aax%5B1%5D.legend(%5B'soft (0.5)', 'hard (0.5)', 'firm(0.5, 1)', 'firm(0.5, 2)',%0A 'firm(0.5, 4)'%5D)%0Aax%5B1%5D.set_xlabel('input value')%0Aax%5B1%5D.set_ylabel('thresholded value')%0Aplt.show()%0A
|
|
e1b32cdd95c8a11cb492d27d9ac11a46c4037f2e
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,1028 @@
+# -*- coding: utf-8 -*-%0A%0Afrom setuptools import setup, find_packages%0Aimport rdd%0A%0Asetup(name='rdd',%0A version=rdd.__version__,%0A author='Mathias Lafeldt',%0A author_email='mathias.lafeldt@gmail.com',%0A url='https://github.com/mlafeldt/rdd.py',%0A license='MIT',%0A description='Python implementation of the Readability Shortener API',%0A long_description=open('README.md').read() + '%5Cn%5Cn' +%0A open('HISTORY.rst').read(),%0A classifiers=%5B'Development Status :: 4 - Beta',%0A 'Intended Audience :: Developers',%0A 'Natural Language :: English',%0A 'License :: OSI Approved :: MIT License',%0A 'Operating System :: OS Independent',%0A 'Programming Language :: Python'%5D,%0A packages=find_packages(),%0A zip_safe=False,%0A setup_requires=%5B%5D,%0A install_requires=%5B'requests%3E=0.7.0'%5D,%0A entry_points=%22%22%22%0A # -*- Entry points: -*-%0A %5Bconsole_scripts%5D%0A rdd=rdd.cli:main%0A %22%22%22)%0A
|
|
d78e3ba37cb2c88300d1e96010e79c6e4329f720
|
bump version to 0.3
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(name='hubstorage',
version='0.2',
license='BSD',
description='Client interface for Scrapinghub HubStorage',
author='Scrapinghub',
author_email='info@scrapinghub.com',
url='http://scrapinghub.com',
platforms = ['Any'],
packages = find_packages(),
install_requires = ['requests'],
classifiers = [ 'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python']
)
|
Python
| 0
|
@@ -84,9 +84,9 @@
='0.
-2
+3
',%0A
|
9238e229c63b32e35b46508959450e97901b46ab
|
Add package setup.
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,854 @@
+import glob%0Afrom distutils.core import setup%0A%0A%0Arequires = %5B'pydicom'%5D%0A%0Asetup(%0A name = 'qipipe',%0A version = '1.1.1',%0A author = 'Fred Loney',%0A author_email = 'loneyf@ohsu.edu',%0A packages = find_packages('lib'),%0A package_dir = %7B'':'lib'%7D%0A scripts = glob.glob('bin/*'),%0A url = 'http://quip1.ohsu.edu/git/qipipe',%0A license = 'Proprietary',%0A description = '.',%0A long_description = __doc__,%0A classifiers = %5B%0A %22Development Status :: 3 - Alpha%22,%0A %22Topic :: Scientific/Engineering :: Bio-Informatics%22,%0A %22Environment :: Console%22,%0A %22Intended Audience :: Science/Research%22,%0A %22License :: Other/Proprietary License%22,%0A %22Programming Language :: Python%22,%0A %22Programming Language :: Python :: 2.6%22,%0A %22Programming Language :: Python :: 2.7%22,%0A %5D,%0A install_requires = requires%0A)%0A
|
|
cd596bd419352d95fb31aab7116a1dddb061828c
|
add a setup.py for the trait_documenter package
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,927 @@
+#----------------------------------------------------------------------------%0A#%0A# Copyright (c) 2014, Enthought, Inc.%0A# All rights reserved.%0A#%0A# This software is provided without warranty under the terms of the BSD%0A# license included in /LICENSE.txt and may be redistributed only%0A# under the conditions described in the aforementioned license. The license%0A# is also available online at http://www.enthought.com/licenses/BSD.txt%0A#%0A# Thanks for using Enthought open source!%0A#%0A#----------------------------------------------------------------------------%0A%0Afrom setuptools import setup, find_packages%0A%0A%0Asetup(%0A name='trait_documenter',%0A version='1.0.0',%0A author='Enthought, Inc',%0A author_email='info@enthought.com',%0A url='https://github.com/enthought/trait-documenter',%0A description='Autodoc extention for documenting traits',%0A long_description=open('README.rst').read(),%0A packages=find_packages())%0A
|
|
d611af5a613e444c0c31c269aa382f0996c375d9
|
Add setup.py from h3's fork
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,538 @@
+%22%22%22%0Adjango-jquery-file-upload%0A%22%22%22%0A%0Afrom setuptools import setup, find_packages%0A%0Asetup(%0A name = %22django-jquery-file-upload%22,%0A version = %220.0.1%22,%0A url = %22%22,%0A license = %22The MIT License (MIT)%22,%0A description = %22A minimal django project containing a minimal app with a working jquery file upload form based on the work by Sebastian Tschan: http://aquantum-demo.appspot.com/file-upload%22,%0A author = 'Sebastian Tschan / Sigurd Gartmann',%0A packages = find_packages(),%0A package_dir = %7B'': '.'%7D,%0A install_requires = %5B%5D,%0A)%0A
|
|
5ce21100b42dad13815d21cd3fae9a2710756314
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,589 @@
+#!/usr/bin/env python%0A%0A%22%22%22%0ACreated by: Lee Bergstrand (2018)%0A%0ADescription: Setup for installing pygenprop.%0A%22%22%22%0A%0Afrom setuptools import setup%0A%0Asetup(name='pygenprop',%0A version='0.1',%0A description='A python library for programmatic usage of EBI InterPro Genome Properties.',%0A url='https://github.com/Micromeda/pygenprop',%0A author='Lee Bergstrand',%0A author_email='flyingcircus@example.com',%0A license='Apache License 2.0',%0A packages=%5B'pygenprop'%5D,%0A install_requires=%5B%0A 'Cython==0.29',%0A 'pandas==0.23.4',%0A %5D,%0A zip_safe=False)%0A
|
|
b9a23638d4cf6cc692a2dce3d42268ca73343493
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,692 @@
+#!/usr/bin/env python%0A# coding=utf-8%0A%0Afrom setuptools import setup%0A%0Asetup(%0A name='alfred-workflow-packager',%0A version='0.8b',%0A description='A CLI utility for packaging and exporting Alfred workflows',%0A url='https://github.com/caleb531/alfred-workflow-packager',%0A author='Caleb Evans',%0A author_email='caleb@calebevans.me',%0A license='MIT',%0A keywords='alfred workflow package export',%0A packages=%5B'awp'%5D,%0A install_requires=%5B%0A 'biplist %3E= 1, %3C 2',%0A 'jsonschema %3E= 2, %3C 3'%0A %5D,%0A entry_points=%7B%0A 'console_scripts': %5B%0A 'alfred-workflow-packager=awp.packager:main',%0A 'workflow-packager=awp.packager:main'%0A %5D%0A %7D%0A)%0A
|
|
8124ad701f11aad4e127e26fb34e850b80e03bdf
|
Add compare_to_sim
|
compare_to_sim.py
|
compare_to_sim.py
|
Python
| 0.000007
|
@@ -0,0 +1,732 @@
+# -*- coding: utf-8 -*-%0A%22%22%22%0ACreated on Thu May 21 17:55:00 2015%0A%0A@author: weber%0A%22%22%22%0Aimport numpy as np%0Aimport matplotlib.pyplot as plt%0Afrom glob import glob%0Afrom pressure_traces import copy%0A%0Asimdata = np.genfromtxt('export.csv', delimiter=',', skip_header=1)%0Asimtime = simdata%5B:, 0%5D%0Asimvolume = simdata%5B:, 1%5D%0Asimtemperature = simdata%5B:, 2%5D%0Asimpressure = simdata%5B:, 3%5D%0A%0Aflist = glob('*pressure.txt')%0Aexpdata = np.genfromtxt(flist%5B0%5D)%0Aexptime = expdata%5B:, 0%5D%0Aexppressure = expdata%5B:, 1%5D%0A%0Afig = plt.figure(2)%0Aax = fig.add_subplot(1, 1, 1)%0Aax.plot(exptime, exppressure)%0Aax.plot(simtime, simpressure)%0Am = plt.get_current_fig_manager()%0Am.window.showMaximized()%0A%0AmaxT = np.amax(simtemperature)%0Aprint('%7B:.0f%7D'.format(maxT))%0Acopy(str(maxT))%0A
|
|
d952b1b42ad82d40b0eb741f189d2525b73e2d19
|
add basic configuration
|
setup.py
|
setup.py
|
Python
| 0.000006
|
@@ -0,0 +1,283 @@
+from distutils.core import setup%0Asetup(name='distance_matrix',%0A author='Harrison Shoebridge',%0A author_email='harrison@theshoebridges.com',%0A description='A small wrapper around the google distance matrix api',%0A version='0.1',%0A py_modules=%5B'distance_matrix'%5D)%0A
|
|
39b27532e79f27612bbae0b748ef91d89a429b84
|
Exclude buggy setuptools-scm version
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
'''
Vdirsyncer synchronizes calendars and contacts.
Please refer to https://vdirsyncer.pimutils.org/en/stable/packaging.html for
how to package vdirsyncer.
'''
from setuptools import Command, find_packages, setup
requirements = [
# https://github.com/mitsuhiko/click/issues/200
'click>=5.0',
'click-log>=0.1.3',
# https://github.com/pimutils/vdirsyncer/issues/478
'click-threading>=0.2',
# !=2.9.0: https://github.com/kennethreitz/requests/issues/2930
#
# >=2.4.1: https://github.com/shazow/urllib3/pull/444
# Without the above pull request, `verify=False` also disables fingerprint
# validation. This is *not* what we want, and it's not possible to
# replicate vdirsyncer's current behavior (verifying fingerprints without
# verifying against CAs) with older versions of urllib3.
'requests >=2.4.1, !=2.9.0',
# https://github.com/sigmavirus24/requests-toolbelt/pull/28
# And https://github.com/sigmavirus24/requests-toolbelt/issues/54
'requests_toolbelt >=0.4.0',
# https://github.com/untitaker/python-atomicwrites/commit/4d12f23227b6a944ab1d99c507a69fdbc7c9ed6d # noqa
'atomicwrites>=0.1.7'
]
class PrintRequirements(Command):
description = 'Prints minimal requirements'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
for requirement in requirements:
print(requirement.replace(">", "=").replace(" ", ""))
setup(
# General metadata
name='vdirsyncer',
author='Markus Unterwaditzer',
author_email='markus@unterwaditzer.net',
url='https://github.com/pimutils/vdirsyncer',
description='Synchronize calendars and contacts',
license='MIT',
long_description=open('README.rst').read(),
# Runtime dependencies
install_requires=requirements,
# Optional dependencies
extras_require={
'remotestorage': ['requests-oauthlib'],
'google': ['requests-oauthlib'],
},
# Build dependencies
setup_requires=['setuptools_scm'],
# Other
packages=find_packages(exclude=['tests.*', 'tests']),
include_package_data=True,
cmdclass={
'minimal_requirements': PrintRequirements
},
use_scm_version={
'write_to': 'vdirsyncer/version.py'
},
entry_points={
'console_scripts': ['vdirsyncer = vdirsyncer.cli:main']
},
)
|
Python
| 0.000157
|
@@ -2098,16 +2098,26 @@
ools_scm
+ != 1.12.0
'%5D,%0A%0A
|
1805e9cc2e2aeb3770b03ebcb05ac189566fa165
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,456 @@
+from setuptools import setup, find_packages%0A%0Asetup(%0A name='memozo',%0A version=%220.1.0%22,%0A description='Memotize objects to desk easily',%0A author='sotetsuk',%0A url='https://github.com/sotetsuk/memozo',%0A author_email='sotetsu.koyamada@gmail.com',%0A license='MIT',%0A install_requires=%5B%5D,%0A packages=find_packages(),%0A classifiers=%5B%0A %22Programming Language :: Python :: 3.5%22,%0A %22License :: OSI Approved :: MIT License%22%0A %5D%0A)
|
|
37dcd46678ca8f22640aa314b174fda78be5392d
|
Bump version number
|
setup.py
|
setup.py
|
"""
Flask-MongoEngine
--------------
Flask support for MongoDB using MongoEngine.
Includes `WTForms`_ support.
Links
`````
* `development version
<https://github.com/sbook/flask-mongoengine/raw/master#egg=Flask-MongoEngine-dev>`_
"""
from setuptools import setup
setup(
name='Flask-MongoEngine',
version='0.1.2-dev',
url='https://github.com/sbook/flask-mongoengine',
license='BSD',
author='Ross Lawley',
author_email='ross.lawley@streetlife.com',
description='Flask support for MongoDB and with WTF model forms',
long_description=__doc__,
packages=['flaskext',
'flaskext.mongoengine',
'flaskext.mongoengine.wtf'],
namespace_packages=['flaskext'],
test_suite='nose.collector',
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'mongoengine',
'flask-wtf'
],
include_package_data=True,
tests_require=[
'nose',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Python
| 0.000002
|
@@ -322,9 +322,9 @@
0.1.
-2
+3
-dev
|
dbe16470f596ee53ec18975afca4aa0605b9b1bc
|
Add setup.py.
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,1424 @@
+#!/usr/bin/env python3%0A%0Atry:%0A from setuptools.core import setup%0Aexcept ImportError:%0A from distutils.core import setup%0Afrom pip.req import parse_requirements%0Afrom pip.download import PipSession%0Aimport os%0A%0Adef get_file_path(name):%0A return os.path.abspath(os.path.join(%0A os.path.dirname(__file__),%0A name))%0A%0Awith open(get_file_path('version.py')) as f:%0A exec(f.read())%0A%0A# read requirements from requirements.txt%0Arequirements = parse_requirements(get_file_path('requirements.txt'),%0A session=PipSession())%0Arequirements = %5Bstr(r.req) for r in requirements%5D%0A%0Asetup(%0A name = 'pybtracker',%0A py_modules = %5B'version'%5D,%0A packages = %5B'pybtracker'%5D,%0A install_requires = requirements,%0A version = __version__,%0A description = 'Simple asyncio-based UDP BitTorrent tracker, '%0A 'with a simple client.',%0A author = 'Mostafa Razavi',%0A license = 'MIT',%0A author_email = 'mostafa@sepent.com',%0A url = 'https://github.com/elektito/pybtracker',%0A download_url = 'https://github.com/elektito/pybtracker/tarball/' + __version__,%0A keywords = %5B'bittorrent', 'torrent', 'tracker', 'asyncio', 'udp'%5D,%0A classifiers = %5B%0A 'Programming Language :: Python :: 3'%0A %5D,%0A entry_points = %7B%0A 'console_scripts': %5B%0A 'pybtracker=pybtracker.server:main',%0A 'pybtracker-client=pybtracker.client:main',%0A %5D,%0A %7D,%0A)%0A
|
|
d8dd594c2ce0defa430f5a7e873c87491c7aab47
|
Allow hyperframe 5
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# Get the version
version_regex = r'__version__ = ["\']([^"\']*)["\']'
with open('h2/__init__.py', 'r') as f:
text = f.read()
match = re.search(version_regex, text)
if match:
version = match.group(1)
else:
raise RuntimeError("No version number found!")
# Stealing this from Kenneth Reitz
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
packages = [
'h2',
]
readme = codecs.open('README.rst', encoding='utf-8').read()
history = codecs.open('HISTORY.rst', encoding='utf-8').read()
setup(
name='h2',
version=version,
description='HTTP/2 State-Machine based protocol implementation',
long_description=u'\n\n'.join([readme, history]),
author='Cory Benfield',
author_email='cory@lukasa.co.uk',
url='http://hyper.rtfd.org',
packages=packages,
package_data={'': ['LICENSE', 'README.rst', 'CONTRIBUTORS.rst', 'HISTORY.rst', 'NOTICES']},
package_dir={'h2': 'h2'},
include_package_data=True,
license='MIT License',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
install_requires=[
'hyperframe>=3.1, <5, !=4.0.0',
'hpack>=2.2, <3',
],
extras_require={
':python_version == "2.7" or python_version == "3.3"': ['enum34>=1.0.4, <2'],
}
)
|
Python
| 0.000022
|
@@ -1960,17 +1960,17 @@
%3E=3.1, %3C
-5
+6
, !=4.0.
|
5e98fe8b6ac368e29d739a2dfa690fdea01382ca
|
Bring back setup.py
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,1414 @@
+from codecs import open%0Aimport os%0Aimport os.path%0A%0Afrom setuptools import find_packages, setup%0A%0Ahere = os.path.relpath(os.path.abspath(os.path.dirname(__file__)))%0A%0Awith open(os.path.join(here, 'README.rst'), encoding='utf-8') as fd:%0A long_description = fd.read()%0A%0A__version__ = '2.2.1'%0A%0Asetup(%0A name='ichnaea',%0A version=__version__,%0A description='Mozilla Location Service - Ichnaea',%0A long_description=long_description,%0A url='https://github.com/mozilla/ichnaea',%0A author='Mozilla',%0A license=%22Apache 2.0%22,%0A classifiers=%5B%0A %22License :: OSI Approved :: Apache Software License%22,%0A %22Programming Language :: Python%22,%0A %22Programming Language :: Python :: 3%22,%0A %22Programming Language :: Python :: 3.6%22,%0A %22Programming Language :: Python :: 3 :: Only%22,%0A %22Programming Language :: Python :: Implementation :: CPython%22,%0A %22Framework :: Pyramid%22,%0A %22Topic :: Internet :: WWW/HTTP%22,%0A %22Topic :: Internet :: WWW/HTTP :: WSGI :: Application%22%0A %5D,%0A keywords=%22web services geo location%22,%0A packages=find_packages(),%0A include_package_data=True,%0A zip_safe=False,%0A entry_points=%7B%0A 'console_scripts': %5B%0A 'location_dump=ichnaea.scripts.dump:console_entry',%0A 'location_map=ichnaea.scripts.datamap:console_entry',%0A 'location_region_json=ichnaea.scripts.region_json:console_entry',%0A %5D,%0A %7D,%0A)%0A
|
|
95c8e291fe1f89e1d880deff34c6e0aa98f6fdf2
|
Package description for setuptools.
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,1549 @@
+# Copyright (c) 2009 Shrubbery Software%0A# %0A# Permission is hereby granted, free of charge, to any person obtaining a copy%0A# of this software and associated documentation files (the %22Software%22), to deal%0A# in the Software without restriction, including without limitation the rights%0A# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A# copies of the Software, and to permit persons to whom the Software is%0A# furnished to do so, subject to the following conditions:%0A# %0A# The above copyright notice and this permission notice shall be included in%0A# all copies or substantial portions of the Software.%0A# %0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0A# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0A# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0A# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0A# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN%0A# THE SOFTWARE.%0A%0Afrom setuptools import setup, find_packages%0A%0Asetup(name='homophony',%0A version='0.1',%0A description='Django and zc.testbrowser integration',%0A long_description=open('README').read(),%0A author='Shrubbery Software',%0A author_email='team@shrubberysoft.com',%0A url='http://github.com/shrubberysoft/homophony',%0A packages=find_packages('src'),%0A package_dir=%7B'' : 'src'%7D,%0A install_requires=%5B'wsgi_intercept==0.4', 'zc.testbrowser'%5D%0A)%0A
|
|
62439e5c8f174752cd5774c3f240b7cc8fa158ad
|
add packaging boilerplate
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,320 @@
+from setuptools import setup, find_packages%0A%0AINFO = %7B'name': 'mecode',%0A 'version': '0.0.1',%0A %7D%0A%0Asetup(%0A name=INFO%5B'name'%5D,%0A version=INFO%5B'version'%5D,%0A author='Jack Minardi',%0A packages=find_packages(),%0A zip_safe=False,%0A maintainer='Jack Minardi',%0A maintainer_email='jack@minardi.org',%0A)%0A
|
|
f6b9a0c75a3b5b37b74856226c8210717def606f
|
Implement astroid trajectory
|
src/trajectory/astroid_trajectory.py
|
src/trajectory/astroid_trajectory.py
|
Python
| 0.000037
|
@@ -0,0 +1,540 @@
+#!/usr/bin/env python%0Afrom math import cos, pi, sin%0A%0Afrom .trajectory import Trajectory%0A%0A%0Aclass AstroidTrajectory(object, Trajectory):%0A def __init__(self, radius, period):%0A Trajectory.__init__(self)%0A self.radius = radius%0A self.period = period%0A%0A def get_position_at(self, t):%0A super(AstroidTrajectory, self).get_position_at(t)%0A self.position.x = self.radius * cos(2 * pi * t / self.period) ** 3%0A self.position.y = self.radius * sin(2 * pi * t / self.period) ** 3%0A%0A return self.position%0A
|
|
a9091a140ff158b79b05da5c20e18a0f1368d3d9
|
add missing package init file
|
backend/src/gosa/backend/plugins/two_factor/filter/__init__.py
|
backend/src/gosa/backend/plugins/two_factor/filter/__init__.py
|
Python
| 0.000001
|
@@ -0,0 +1,274 @@
+# This file is part of the GOsa project.%0A#%0A# http://gosa-project.org%0A#%0A# Copyright:%0A# (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de%0A#%0A# See the LICENSE file in the project's top-level directory for details.%0A%0A__import__('pkg_resources').declare_namespace(__name__)%0A
|
|
9758ca18557b686825d6afe8714c2f4816411878
|
lowercase the locale in LANGUAGES (#10440)
|
src/olympia/conf/prod/settings.py
|
src/olympia/conf/prod/settings.py
|
import logging
from olympia.lib.settings_base import * # noqa
ENGAGE_ROBOTS = True
EMAIL_URL = env.email_url('EMAIL_URL')
EMAIL_HOST = EMAIL_URL['EMAIL_HOST']
EMAIL_PORT = EMAIL_URL['EMAIL_PORT']
EMAIL_BACKEND = EMAIL_URL['EMAIL_BACKEND']
EMAIL_HOST_USER = EMAIL_URL['EMAIL_HOST_USER']
EMAIL_HOST_PASSWORD = EMAIL_URL['EMAIL_HOST_PASSWORD']
SEND_REAL_EMAIL = True
ENV = env('ENV')
API_THROTTLING = True
CDN_HOST = 'https://addons.cdn.mozilla.net'
DOMAIN = env('DOMAIN', default='addons.mozilla.org')
SERVER_EMAIL = 'zprod@addons.mozilla.org'
SITE_URL = 'https://' + DOMAIN
SERVICES_URL = env('SERVICES_URL',
default='https://services.addons.mozilla.org')
STATIC_URL = '%s/static/' % CDN_HOST
MEDIA_URL = '%s/user-media/' % CDN_HOST
SESSION_COOKIE_DOMAIN = ".%s" % DOMAIN
# Domain emails should be sent to.
INBOUND_EMAIL_DOMAIN = env('INBOUND_EMAIL_DOMAIN',
default='addons.mozilla.org')
DATABASES = {
'default': get_db_config('DATABASES_DEFAULT_URL'),
'slave': get_db_config('DATABASES_SLAVE_URL', atomic_requests=False),
}
SERVICES_DATABASE = get_db_config('SERVICES_DATABASE_URL')
SLAVE_DATABASES = ['slave']
CACHES = {}
CACHES['default'] = env.cache('CACHES_DEFAULT')
CACHES['default']['TIMEOUT'] = 500
CACHES['default']['BACKEND'] = 'django.core.cache.backends.memcached.MemcachedCache' # noqa
CACHES['default']['KEY_PREFIX'] = CACHE_KEY_PREFIX
# Celery
CELERY_BROKER_CONNECTION_TIMEOUT = 0.5
LOGGING['loggers'].update({
'adi.updatecounts': {'level': logging.INFO},
'amqp': {'level': logging.WARNING},
'raven': {'level': logging.WARNING},
'requests': {'level': logging.WARNING},
'z.addons': {'level': logging.INFO},
'z.task': {'level': logging.DEBUG},
'z.pool': {'level': logging.ERROR},
})
ES_TIMEOUT = 60
ES_HOSTS = env('ES_HOSTS')
ES_URLS = ['http://%s' % h for h in ES_HOSTS]
ES_INDEXES = dict((k, '%s_%s' % (v, ENV)) for k, v in ES_INDEXES.items())
LANGUAGES = {
locale: value['native']
for locale, value in LANGUAGE_MAPPING.items()
if locale not in DEBUG_LANGUAGES}
LANGUAGE_URL_MAP = {
locale.lower(): locale
for locale in AMO_LANGUAGES
if locale not in DEBUG_LANGUAGES}
CEF_PRODUCT = STATSD_PREFIX
NEW_FEATURES = True
ADDONS_LINTER_BIN = 'node_modules/.bin/addons-linter'
XSENDFILE_HEADER = 'X-Accel-Redirect'
NEWRELIC_ENABLE = env.bool('NEWRELIC_ENABLE', default=False)
if NEWRELIC_ENABLE:
NEWRELIC_INI = '/etc/newrelic.d/%s.ini' % DOMAIN
FXA_CONFIG = {
'default': {
'client_id': env('FXA_CLIENT_ID'),
'client_secret': env('FXA_CLIENT_SECRET'),
'content_host': 'https://accounts.firefox.com',
'oauth_host': 'https://oauth.accounts.firefox.com/v1',
'profile_host': 'https://profile.accounts.firefox.com/v1',
'redirect_url':
'https://%s/api/v3/accounts/authenticate/' % DOMAIN,
'scope': 'profile',
},
'amo': {
'client_id': env('AMO_FXA_CLIENT_ID'),
'client_secret': env('AMO_FXA_CLIENT_SECRET'),
'content_host': 'https://accounts.firefox.com',
'oauth_host': 'https://oauth.accounts.firefox.com/v1',
'profile_host': 'https://profile.accounts.firefox.com/v1',
'redirect_url':
'https://addons.mozilla.org/api/v3/accounts/authenticate/',
'scope': 'profile',
'skip_register_redirect': True,
},
}
DEFAULT_FXA_CONFIG_NAME = 'default'
ALLOWED_FXA_CONFIGS = ['default', 'amo']
VALIDATOR_TIMEOUT = 360
ES_DEFAULT_NUM_SHARDS = 10
RECOMMENDATION_ENGINE_URL = env(
'RECOMMENDATION_ENGINE_URL',
default='https://taar.prod.mozaws.net/v1/api/recommendations/')
TAAR_LITE_RECOMMENDATION_ENGINE_URL = env(
'TAAR_LITE_RECOMMENDATION_ENGINE_URL',
default=('https://taarlite.prod.mozaws.net/taarlite/api/v1/'
'addon_recommendations/'))
FXA_SQS_AWS_QUEUE_URL = (
'https://sqs.us-west-2.amazonaws.com/361527076523/'
'amo-account-change-prod')
DRF_API_VERSIONS = ['v3', 'v4']
DRF_API_REGEX = r'^/?api/(?:v3|v4)/'
|
Python
| 0.999901
|
@@ -1977,16 +1977,24 @@
locale
+.lower()
: value%5B
|
846ec085ff7bc1f5be250ac1ac2df87534bbc5c9
|
add gunicorn.conf.py
|
deploy/gunicorn.conf.py
|
deploy/gunicorn.conf.py
|
Python
| 0.000003
|
@@ -0,0 +1,360 @@
+import os%0A%0Adef numCPUs():%0A if not hasattr(os, %22sysconf%22):%0A raise RuntimeError(%22No sysconf detected.%22)%0A return os.sysconf(%22SC_NPROCESSORS_ONLN%22)%0A%0Aworkers = numCPUs() * 2 + 1%0Abind = %22127.0.0.1:8000%22%0Apidfile = %22/tmp/gunicorn-demo.pid%22%0Abacklog = 2048%0Alogfile = %22/home/linventifatelier/earthbuilding/log/gunicorn_demo.log%22%0Aloglevel = %22info%22%0Atimeout=60%0A
|
|
5574ddd6aaf6ab041bdb186b1455792bff803731
|
Add range to ConditionFactory
|
src/oscar/test/factories/offer.py
|
src/oscar/test/factories/offer.py
|
import factory
from oscar.core.loading import get_model
__all__ = [
'RangeFactory', 'ConditionFactory', 'BenefitFactory',
'ConditionalOfferFactory',
]
class RangeFactory(factory.DjangoModelFactory):
name = factory.Sequence(lambda n: 'Range %d' % n)
slug = factory.Sequence(lambda n: 'range-%d' % n)
class Meta:
model = get_model('offer', 'Range')
@factory.post_generation
def products(self, create, extracted, **kwargs):
if not create or not extracted:
return
RangeProduct = get_model('offer', 'RangeProduct')
for product in extracted:
RangeProduct.objects.create(product=product, range=self)
class BenefitFactory(factory.DjangoModelFactory):
type = get_model('offer', 'Benefit').PERCENTAGE
value = 10
max_affected_items = None
range = factory.SubFactory(RangeFactory)
class Meta:
model = get_model('offer', 'Benefit')
class ConditionFactory(factory.DjangoModelFactory):
type = get_model('offer', 'Condition').COUNT
value = 10
class Meta:
model = get_model('offer', 'Condition')
class ConditionalOfferFactory(factory.DjangoModelFactory):
name = 'Test offer'
benefit = factory.SubFactory(BenefitFactory)
condition = factory.SubFactory(ConditionFactory)
class Meta:
model = get_model('offer', 'ConditionalOffer')
|
Python
| 0
|
@@ -1052,16 +1052,61 @@
lue = 10
+%0A range = factory.SubFactory(RangeFactory)
%0A%0A cl
|
710150538efcb56f2b8e968c58707ce2bbe8431b
|
add script to fill in ltr termini
|
bin/fillTermini.py
|
bin/fillTermini.py
|
Python
| 0
|
@@ -0,0 +1,2055 @@
+#!/usr/bin/env python%0A%0A#Copyright (C) 2014 by Glenn Hickey%0A#%0A#Released under the MIT license, see LICENSE.txt%0Aimport sys%0Aimport os%0Aimport argparse%0Aimport copy%0A%0Afrom pybedtools import BedTool, Interval%0A%0A%22%22%22%0AStick a bed interval between pairs of lastz termini. Script written to be used%0Ain conjunction with tsdFinder.py:%0Alastz termini -%3E fill termini -%3E bed input (which gets merged up automatically)%0Afor tsdFinder.py. Example:%0A%0Ascaffold_1%09141%09225%091+%0943%09+%0Ascaffold_1%094479%094563%091+%0943%09+%0A%0Abecomes%0A%0Ascaffold_1%09141%09225%091+%0943%09+%0Ascaffold_1%09225%094479%091+%0943%09+%0Ascaffold_1%094479%094563%091+%0943%09+%0A%22%22%22%0A%0Adef main(argv=None):%0A if argv is None:%0A argv = sys.argv%0A%0A parser = argparse.ArgumentParser(%0A formatter_class=argparse.ArgumentDefaultsHelpFormatter,%0A description=%22Add interval between pairs of candidate termini. Input %22%0A %22bed must have pairs of termini (left first) in contiguous rows.%22)%0A parser.add_argument(%22inBed%22, help=%22bed with ltr results to process%22)%0A parser.add_argument(%22outBed%22, help=%22bed to write output to.%22)%0A %0A args = parser.parse_args()%0A assert os.path.exists(args.inBed)%0A outFile = open(args.outBed, %22w%22)%0A%0A prevInterval = None%0A for interval in BedTool(args.inBed):%0A %0A # Right termini%0A if prevInterval is not None:%0A if interval.name != prevInterval.name:%0A raise RuntimeError(%22Consecutive intervals dont have same id%22%0A %22%5Cn%25s%25s%22 %25 (prevInterval, interval))%0A%0A # make the new interval, dont bother giving a new name for now%0A fillInterval = copy.deepcopy(prevInterval)%0A fillInterval.start = prevInterval.end%0A fillInterval.end = interval.start%0A outFile.write(str(prevInterval))%0A outFile.write(str(fillInterval))%0A outFile.write(str(interval))%0A prevInterval = None%0A %0A # Left termini%0A else:%0A prevInterval = interval%0A %0A outFile.close()%0A %0Aif __name__ == %22__main__%22:%0A sys.exit(main())%0A
|
|
418a2104ec20a0b8f651320c1cbea10a533dc44d
|
Add tools/sys-tools/gdb/cmd_example.py
|
tools/sys-tools/gdb/cmd_example.py
|
tools/sys-tools/gdb/cmd_example.py
|
Python
| 0.000001
|
@@ -0,0 +1,1422 @@
+import gdb%0A%0Aclass SavePrefixCommand (gdb.Command):%0A '''%0A Save the current breakpoints to a file.%0A This command takes a single argument, a file name.%0A The breakpoints can be restored using the 'source' command.%0A '''%0A%0A def __init__(self):%0A super(SavePrefixCommand, self).__init__ (%22save breakpoints%22,%0A gdb.COMMAND_SUPPORT,%0A gdb.COMPLETE_FILENAME)%0A %0A%0A def invoke (self, arg, from_tty):%0A with open (arg, 'w') as f:%0A for bp in gdb.get_breakpoints ():%0A print %3E%3E f, %22break%22, bp.get_location (),%0A if bp.get_thread () is not None:%0A print %3E%3E f, %22 thread%22, bp.get_thread (),%0A if bp.get_condition () is not None:%0A print %3E%3E f, %22 if%22, bp.get_condition (),%0A print %3E%3E f%0A if not bp.is_enabled ():%0A print %3E%3E f, %22disable $bpnum%22%0A # Note: we don't save the ignore count; there doesn't%0A # seem to be much point.%0A commands = bp.get_commands ()%0A if commands is not None:%0A print %3E%3E f, %22commands%22%0A # Note that COMMANDS has a trailing newline.%0A print %3E%3E f, commands,%0A print %3E%3E f, %22end%22%0A print %3E%3E f%0A%0A%0ASavePrefixCommand()%0A
|
|
61677566ce685379456e7853c69a78ea32353422
|
Add auto fixture to make sure that output dir does not exists when tests are run
|
static_precompiler/tests/conftest.py
|
static_precompiler/tests/conftest.py
|
Python
| 0
|
@@ -0,0 +1,424 @@
+from static_precompiler.settings import ROOT, OUTPUT_DIR%0Aimport shutil%0Aimport os%0Aimport pytest%0A%0A%0A@pytest.fixture(autouse=True)%0Adef _no_output_dir(request):%0A %22%22%22 Make sure that output dir does not exists. %22%22%22%0A%0A path = os.path.join(ROOT, OUTPUT_DIR)%0A%0A if os.path.exists(path):%0A shutil.rmtree(path)%0A%0A def fin():%0A if os.path.exists(path):%0A shutil.rmtree(path)%0A%0A request.addfinalizer(fin)%0A
|
|
6a6a76ff5274b01ae8570ae7b1a4153b8705100f
|
move worker func
|
streammorphology/freqmap/mpi_util.py
|
streammorphology/freqmap/mpi_util.py
|
Python
| 0.00002
|
@@ -0,0 +1,330 @@
+# coding: utf-8%0A%0A%22%22%22 Utilities for running frequency mapping with MPI (map) %22%22%22%0A%0Afrom __future__ import division, print_function%0A%0A__author__ = %22adrn %3Cadrn@astro.columbia.edu%3E%22%0A%0A# Standard library%0Aimport os%0Afrom collections import OrderedDict%0A%0A# Third-party%0Aimport numpy as np%0Afrom astropy.utils import isiterable%0A%0A# Project%0A# ...%0A
|
|
cb06e45100607e3375a25e2d19bcc94088f0c061
|
Fix an error in how 'gridrank' keys are set.
|
distarray/local/base.py
|
distarray/local/base.py
|
# encoding: utf-8
__docformat__ = "restructuredtext en"
#----------------------------------------------------------------------------
# Copyright (C) 2008 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
# Imports
#----------------------------------------------------------------------------
import numpy as np
import operator
from functools import reduce
from six import next
from distarray.local import construct, maps
def distribute_block_indices(dd):
"""Fill in `start` and `stop` in dimdict `dd`."""
if ('start' in dd) and ('stop' in dd):
return
nelements = dd['datasize'] // dd['gridsize']
if dd['datasize'] % dd['gridsize'] != 0:
nelements += 1
dd['start'] = dd['gridrank'] * nelements
if dd['start'] > dd['datasize']:
dd['start'] = dd['datasize']
dd['stop'] = dd['datasize']
dd['stop'] = dd['start'] + nelements
if dd['stop'] > dd['datasize']:
dd['stop'] = dd['datasize']
def distribute_cyclic_indices(dd):
"""Fill in `start` given dimdict `dd`."""
if 'start' in dd:
return
else:
dd['start'] = dd['gridrank']
def distribute_indices(dimdata):
"""Fill in missing index related keys...
for supported disttypes.
"""
distribute_fn = {
'b': distribute_block_indices,
'c': distribute_cyclic_indices,
}
for dim in dimdata:
if dim['disttype']:
distribute_fn[dim['disttype']](dim)
class BaseLocalArray(object):
"""Distributed memory Python arrays."""
__array_priority__ = 20.0
def __init__(self, dimdata, dtype=None, buf=None, comm=None):
"""Make a BaseLocalArray from a `dimdata` tuple.
Parameters
----------
dimdata : tuple of dictionaries
A dict for each dimension, with the data described here:
https://github.com/enthought/distributed-array-protocol
dtype : numpy dtype, optional
If both `dtype` and `buf` are provided, `buf` will be
encapsulated and interpreted with the given dtype. If neither
are, an empty array will be created with a dtype of 'float'. If
only `dtype` is given, an empty array of that dtype will be
created.
buf : buffer object, optional
If both `dtype` and `buf` are provided, `buf` will be
encapsulated and interpreted with the given dtype. If neither
are, an empty array will be created with a dtype of 'float'. If
only `buf` is given, `self.dtype` will be set to its dtype.
comm : MPI communicator object, optional
Returns
-------
BaseLocalArray
A BaseLocalArray encapsulating `buf`, or else an empty
(uninitialized) BaseLocalArray.
"""
self.dimdata = dimdata
self.base_comm = construct.init_base_comm(comm)
self.grid_shape = construct.init_grid_shape(self.shape,
self.distdims,
self.comm_size,
self.grid_shape)
self.comm = construct.init_comm(self.base_comm, self.grid_shape,
self.ndistdim)
self._cache_gridrank()
distribute_indices(self.dimdata)
self.maps = tuple(maps.IndexMap.from_dimdict(dimdict) for dimdict in
dimdata if dimdict['disttype'])
self.local_array = self._make_local_array(buf=buf, dtype=dtype)
self.base = None
self.ctypes = None
@property
def local_shape(self):
lshape = []
maps = iter(self.maps)
for dim in self.dimdata:
if dim['disttype']:
m = maps.next()
size = len(m.global_index)
else:
size = dim['datasize']
lshape.append(size)
return tuple(lshape)
@property
def grid_shape(self):
return tuple(dd.get('gridsize') for dd in self.dimdata
if dd.get('gridsize'))
@grid_shape.setter
def grid_shape(self, grid_shape):
grid_size = iter(grid_shape)
for dist, dd in zip(self.dist, self.dimdata):
if dist:
dd['gridsize'] = next(grid_size)
@property
def shape(self):
return tuple(dd['datasize'] for dd in self.dimdata)
@property
def ndim(self):
return len(self.dimdata)
@property
def size(self):
return reduce(operator.mul, self.shape)
@property
def comm_size(self):
return self.base_comm.Get_size()
@property
def comm_rank(self):
return self.base_comm.Get_rank()
@property
def dist(self):
return tuple(dd['disttype'] for dd in self.dimdata)
@property
def distdims(self):
return tuple(i for (i, v) in enumerate(self.dist) if v)
@property
def ndistdim(self):
return len(self.distdims)
@property
def cart_coords(self):
rval = tuple(dd.get('gridrank') for dd in self.dimdata
if dd.get('gridrank'))
assert rval == self.comm.Get_coords(self.comm_rank)
return rval
@property
def local_size(self):
return self.local_array.size
@property
def data(self):
return self.local_array.data
@property
def dtype(self):
return self.local_array.dtype
@property
def itemsize(self):
return self.dtype.itemsize
@property
def nbytes(self):
return self.size * self.itemsize
def _cache_gridrank(self):
for dim in self.dimdata:
dim['gridrank'] = self.base_comm.Get_rank()
def _make_local_array(self, buf=None, dtype=None):
"""Encapsulate `buf` or create an empty local array.
Returns
-------
local_array : numpy array
"""
if buf is None:
return np.empty(self.local_shape, dtype=dtype)
else:
mv = memoryview(buf)
return np.asarray(mv, dtype=dtype)
def __del__(self):
# If the __init__ method fails, we may not have a valid comm
# attribute and this needs to be protected against.
if hasattr(self, 'comm'):
if self.comm is not None:
try:
self.comm.Free()
except:
pass
def compatibility_hash(self):
return hash((self.shape, self.dist, self.grid_shape, True))
def arecompatible(a, b):
"""Do these arrays have the same compatibility hash?"""
return a.compatibility_hash() == b.compatibility_hash()
|
Python
| 0.999998
|
@@ -5941,39 +5941,185 @@
-for dim in self.dimdata
+cart_coords = self.comm.Get_coords(self.comm_rank)%0A dist_data = (self.dimdata%5Bi%5D for i in self.distdims)%0A for dim, cart_rank in zip(dist_data, cart_coords)
:%0A
@@ -6146,33 +6146,17 @@
%5D =
-self.base_comm.Ge
+car
t_rank
-()
%0A%0A
|
422b9458d26866b9f6692ddb0ccf2305c3ac6ea7
|
Add an extra file to the surrogates experiments.
|
dev/surrogates/plots.py
|
dev/surrogates/plots.py
|
Python
| 0
|
@@ -0,0 +1,705 @@
+import darch.search_logging as sl%0Aimport darch.visualization as vi%0Aimport numpy as np%0Aimport seaborn as sns; sns.set()%0A%0A# checking these across time.%0Alog_lst = sl.read_search_folder('./logs/cifar10_medium/run-0')%0Axkey = 'epoch_number'%0Aykey = 'validation_accuracy'%0Anum_lines = 8%0Atime_plotter = vi.LinePlot(xlabel='time_in_minutes', ylabel=ykey)%0Aepoch_plotter = vi.LinePlot(xlabel=xkey, ylabel=ykey)%0Afor lg in sorted(log_lst, key=lambda x: x%5B'results'%5D%5B'sequences'%5D%5Bykey%5D%5B-1%5D, reverse=True)%5B:num_lines%5D:%0A r = lg%5B'results'%5D%5B'sequences'%5D%0A time_plotter.add_line(np.linspace(0.0, 120.0, len(r%5Bxkey%5D) + 1)%5B1:%5D, r%5Bykey%5D)%0A epoch_plotter.add_line(r%5Bxkey%5D, r%5Bykey%5D)%0Atime_plotter.plot()%0Aepoch_plotter.plot()%0A
|
|
0e2c7c255043d7ccc5042a8e4905557f2d43e2ca
|
Add Mandrill backend
|
templated_email/backends/mandrill.py
|
templated_email/backends/mandrill.py
|
Python
| 0
|
@@ -0,0 +1,1110 @@
+import vanilla_django%0Afrom django.core.mail import EmailMessage%0Afrom django.conf import settings%0Afrom django.utils.translation import ugettext as _%0A%0A# Make sure you have Mandrill as your email backend%0A%0Aclass TemplateBackend(vanilla_django.TemplateBackend):%0A def __init__(self, *args, **kwargs):%0A vanilla_django.TemplateBackend.__init__(self, *args, **kwargs)%0A%0A def send(self, template_name, from_email, recipient_list, context, cc=None,%0A bcc=None, fail_silently=False, headers=None, template_prefix=None,%0A template_suffix=None, template_dir=None, file_extension=None,%0A **kwargs):%0A%0A msg = EmailMessage(from_email=from_email, to=recipient_list)%0A msg.template_name = template_name%0A msg.global_merge_vars = context%0A%0A if cc:%0A msg.cc = cc%0A if bcc:%0A msg.bcc = bcc%0A%0A msg.use_template_subject = kwargs.get('use_template_subject', True)%0A msg.use_template_from = kwargs.get('use_template_from', True)%0A msg.async = kwargs.get('async', True)%0A%0A msg.send()%0A return msg.mandrill_response%0A
|
|
8da12f8f269746b086f5d208afb390e304f12e9b
|
Add stub for submit_glue.py
|
metal/mmtl/submit_glue.py
|
metal/mmtl/submit_glue.py
|
Python
| 0
|
@@ -0,0 +1,253 @@
+import argparse%0A%0Aif __name__ == %22__main__%22:%0A parser = argparse.ArgumentParser(%0A description=%22Evaluate a model and make glue submission bundle%22, add_help=False%0A )%0A parser.add_argument(%22-mf%22, %22--model-file%22)%0A args = parser.parse_args()%0A
|
|
e1f8358e09cd3299effc112544206361d5a6c7dd
|
Add migration for latest-ing
|
refugee_manager/migrations/0003_auto_20141108_1609.py
|
refugee_manager/migrations/0003_auto_20141108_1609.py
|
Python
| 0
|
@@ -0,0 +1,391 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('refugee_manager', '0002_volunteer_mailing_address'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterModelOptions(%0A name='assessment',%0A options=%7B'get_latest_by': 'date'%7D,%0A ),%0A %5D%0A
|
|
7bcc6b343d53830e52b466558e27137dc55b0472
|
Allow field types in mezzanine.forms to be used in mezzanine.core without the forms app actually being installed. Closes #791.
|
mezzanine/forms/fields.py
|
mezzanine/forms/fields.py
|
from django.core.exceptions import ImproperlyConfigured
from django import forms
from django.forms.extras import SelectDateWidget
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import settings
from mezzanine.core.forms import SplitSelectDateTimeWidget
from mezzanine.utils.importing import import_dotted_path
# Constants for all available field types.
TEXT = 1
TEXTAREA = 2
EMAIL = 3
CHECKBOX = 4
CHECKBOX_MULTIPLE = 5
SELECT = 6
SELECT_MULTIPLE = 7
RADIO_MULTIPLE = 8
FILE = 9
DATE = 10
DATE_TIME = 11
HIDDEN = 12
NUMBER = 13
URL = 14
DOB = 15
# Names for all available field types.
NAMES = (
(TEXT, _("Single line text")),
(TEXTAREA, _("Multi line text")),
(EMAIL, _("Email")),
(NUMBER, _("Number")),
(URL, _("URL")),
(CHECKBOX, _("Check box")),
(CHECKBOX_MULTIPLE, _("Check boxes")),
(SELECT, _("Drop down")),
(SELECT_MULTIPLE, _("Multi select")),
(RADIO_MULTIPLE, _("Radio buttons")),
(FILE, _("File upload")),
(DATE, _("Date")),
(DATE_TIME, _("Date/time")),
(DOB, _("Date of birth")),
(HIDDEN, _("Hidden")),
)
# Field classes for all available field types.
CLASSES = {
TEXT: forms.CharField,
TEXTAREA: forms.CharField,
EMAIL: forms.EmailField,
CHECKBOX: forms.BooleanField,
CHECKBOX_MULTIPLE: forms.MultipleChoiceField,
SELECT: forms.ChoiceField,
SELECT_MULTIPLE: forms.MultipleChoiceField,
RADIO_MULTIPLE: forms.ChoiceField,
FILE: forms.FileField,
DATE: forms.DateField,
DATE_TIME: forms.DateTimeField,
DOB: forms.DateField,
HIDDEN: forms.CharField,
NUMBER: forms.FloatField,
URL: forms.URLField,
}
# Widgets for field types where a specialised widget is required.
WIDGETS = {
TEXTAREA: forms.Textarea,
CHECKBOX_MULTIPLE: forms.CheckboxSelectMultiple,
RADIO_MULTIPLE: forms.RadioSelect,
DATE: SelectDateWidget,
DATE_TIME: SplitSelectDateTimeWidget,
DOB: SelectDateWidget,
HIDDEN: forms.HiddenInput,
}
# Some helper groupings of field types.
CHOICES = (CHECKBOX, SELECT, RADIO_MULTIPLE)
DATES = (DATE, DATE_TIME, DOB)
MULTIPLE = (CHECKBOX_MULTIPLE, SELECT_MULTIPLE)
# HTML5 Widgets
if settings.FORMS_USE_HTML5:
html5_field = lambda name, base: type("", (base,), {"input_type": name})
WIDGETS.update({
DATE: html5_field("date", forms.DateInput),
DATE_TIME: html5_field("datetime", forms.DateTimeInput),
DOB: html5_field("date", forms.DateInput),
EMAIL: html5_field("email", forms.TextInput),
NUMBER: html5_field("number", forms.TextInput),
URL: html5_field("url", forms.TextInput),
})
# Allow extra fields types to be defined via the FORMS_EXTRA_FIELDS
# setting, which should contain a sequence of three-item sequences,
# each containing the ID, dotted import path for the field class,
# and field name, for each custom field type.
for field_id, field_path, field_name in settings.FORMS_EXTRA_FIELDS:
if field_id in CLASSES:
err = "ID %s for field %s in FORMS_EXTRA_FIELDS already exists"
raise ImproperlyConfigured(err % (field_id, field_name))
CLASSES[field_id] = import_dotted_path(field_path)
NAMES += ((field_id, _(field_name)),)
|
Python
| 0
|
@@ -2169,24 +2169,32 @@
gets%0Aif
+getattr(
settings
.FORMS_U
@@ -2181,25 +2181,27 @@
ttr(settings
-.
+, %22
FORMS_USE_HT
@@ -2203,16 +2203,25 @@
SE_HTML5
+%22, False)
:%0A ht
@@ -2896,16 +2896,75 @@
d type.%0A
+extra_fields = getattr(settings, %22FORMS_EXTRA_FIELDS%22, %5B%5D)%0A
for fiel
@@ -2999,35 +2999,20 @@
in
-settings.FORMS_EXTRA_FIELDS
+extra_fields
:%0A
|
660e0955979b7d11b7442a00747673700413bf1d
|
Add a test of spline filtering vs. matrix solving.
|
scipy/ndimage/tests/test_splines.py
|
scipy/ndimage/tests/test_splines.py
|
Python
| 0
|
@@ -0,0 +1,2058 @@
+%22%22%22Tests for spline filtering.%22%22%22%0Afrom __future__ import division, print_function, absolute_import%0A%0Aimport numpy as np%0Aimport pytest%0A%0Afrom numpy.testing import assert_almost_equal%0A%0Afrom scipy import ndimage%0A%0A%0Adef get_spline_knot_values(order):%0A %22%22%22Knot values to the right of a B-spline's center.%22%22%22%0A knot_values = %7B0: %5B1%5D,%0A 1: %5B1%5D,%0A 2: %5B6, 1%5D,%0A 3: %5B4, 1%5D,%0A 4: %5B230, 76, 1%5D,%0A 5: %5B66, 26, 1%5D%7D%0A%0A return knot_values%5Border%5D%0A%0A%0Adef make_spline_knot_matrix(n, order, mode='mirror'):%0A %22%22%22Matrix to invert to find the spline coefficients.%22%22%22%0A knot_values = get_spline_knot_values(order)%0A%0A matrix = np.zeros((n, n))%0A for diag, knot_value in enumerate(knot_values):%0A indices = np.arange(diag, n)%0A if diag == 0:%0A matrix%5Bindices, indices%5D = knot_value%0A else:%0A matrix%5Bindices, indices - diag%5D = knot_value%0A matrix%5Bindices - diag, indices%5D = knot_value%0A%0A knot_values_sum = knot_values%5B0%5D + 2 * sum(knot_values%5B1:%5D)%0A%0A if mode == 'mirror':%0A start, step = 1, 1%0A elif mode == 'reflect':%0A start, step = 0, 1%0A elif mode == 'wrap':%0A start, step = -1, -1%0A else:%0A raise ValueError('unsupported mode %7B%7D'.format(mode))%0A%0A for row in range(len(knot_values) - 1):%0A for idx, knot_value in enumerate(knot_values%5Brow + 1:%5D):%0A matrix%5Brow, start + step*idx%5D += knot_value%0A matrix%5B-row - 1, -start - 1 - step*idx%5D += knot_value%0A%0A return matrix / knot_values_sum%0A%0A%0A@pytest.mark.parametrize('order', %5B0, 1, 2, 3, 4, 5%5D)%0Adef test_spline_filter_vs_matrix_solution(order):%0A n = 100%0A eye = np.eye(n, dtype=float)%0A spline_filter_axis_0 = ndimage.spline_filter1d(eye, axis=0, order=order)%0A spline_filter_axis_1 = ndimage.spline_filter1d(eye, axis=1, order=order)%0A matrix = make_spline_knot_matrix(n, order)%0A assert_almost_equal(eye, np.dot(spline_filter_axis_0, matrix))%0A assert_almost_equal(eye, np.dot(spline_filter_axis_1, matrix.T))%0A
|
|
b00338413e954e91c79c625dbaf5140d0a57f6e6
|
before_perform() & after_perform() should be called on class, not pass it in
|
pyres/job.py
|
pyres/job.py
|
import time
from datetime import timedelta
from pyres import ResQ, safe_str_to_class
from pyres import failure
from pyres.failure.redis import RedisBackend
class Job(object):
"""Every job on the ResQ is an instance of the *Job* class.
The ``__init__`` takes these keyword arguments:
``queue`` -- A string defining the queue to which this Job will be
added.
``payload`` -- A dictionary which contains the string name of a class
which extends this Job and a list of args which will be
passed to that class.
``resq`` -- An instance of the ResQ class.
``worker`` -- The name of a specific worker if you'd like this Job to be
done by that worker. Default is "None".
"""
safe_str_to_class = staticmethod(safe_str_to_class)
def __init__(self, queue, payload, resq, worker=None):
self._queue = queue
self._payload = payload
self.resq = resq
self._worker = worker
self.enqueue_timestamp = self._payload.get("enqueue_timestamp")
# Set the default back end, jobs can override when we import them
# inside perform().
failure.backend = RedisBackend
def __str__(self):
return "(Job{%s} | %s | %s)" % (
self._queue, self._payload['class'], repr(self._payload['args']))
def perform(self):
"""This method converts payload into args and calls the ``perform``
method on the payload class.
Before calling ``perform``, a ``before_perform`` class method
is called, if it exists. It takes a dictionary as an argument;
currently the only things stored on the dictionary are the
args passed into ``perform`` and a timestamp of when the job
was enqueued.
Similarly, an ``after_perform`` class method is called after
``perform`` is finished. The metadata dictionary contains the
same data, plus a timestamp of when the job was performed, a
``failed`` boolean value, and if it did fail, a ``retried``
boolean value. This method is called after retry, and is
called regardless of whether an exception is ultimately thrown
by the perform method.
"""
payload_class_str = self._payload["class"]
payload_class = self.safe_str_to_class(payload_class_str)
payload_class.resq = self.resq
args = self._payload.get("args")
metadata = dict(args=args)
if self.enqueue_timestamp:
metadata["enqueue_timestamp"] = self.enqueue_timestamp
before_perform = getattr(payload_class, "before_perform", None)
metadata["failed"] = False
metadata["perform_timestamp"] = time.time()
check_after = True
try:
if before_perform:
before_perform(payload_class, metadata)
return payload_class.perform(*args)
except:
check_after = False
metadata["failed"] = True
if not self.retry(payload_class, args):
metadata["retried"] = False
raise
else:
metadata["retried"] = True
finally:
after_perform = getattr(payload_class, "after_perform", None)
if after_perform and check_after:
after_perform(payload_class, metadata)
delattr(payload_class,'resq')
def fail(self, exception):
"""This method provides a way to fail a job and will use whatever
failure backend you've provided. The default is the ``RedisBackend``.
"""
fail = failure.create(exception, self._queue, self._payload,
self._worker)
fail.save(self.resq)
return fail
def retry(self, payload_class, args):
"""This method provides a way to retry a job after a failure.
If the jobclass defined by the payload containes a ``retry_every`` attribute then pyres
will attempt to retry the job until successful or until timeout defined by ``retry_timeout`` on the payload class.
"""
retry_every = getattr(payload_class, 'retry_every', None)
retry_timeout = getattr(payload_class, 'retry_timeout', 0)
if retry_every:
now = ResQ._current_time()
first_attempt = self._payload.get("first_attempt", now)
retry_until = first_attempt + timedelta(seconds=retry_timeout)
retry_at = now + timedelta(seconds=retry_every)
if retry_at < retry_until:
self.resq.enqueue_at(retry_at, payload_class, *args,
**{'first_attempt':first_attempt})
return True
return False
@classmethod
def reserve(cls, queues, res, worker=None, timeout=10):
"""Reserve a job on one of the queues. This marks this job so
that other workers will not pick it up.
"""
if isinstance(queues, basestring):
queues = [queues]
queue, payload = res.pop(queues, timeout=timeout)
if payload:
return cls(queue, payload, res, worker)
|
Python
| 0.999996
|
@@ -2866,32 +2866,46 @@
+payload_class.
before_perform(p
@@ -2899,39 +2899,24 @@
ore_perform(
-payload_class,
metadata)%0A
@@ -3371,32 +3371,46 @@
+payload_class.
after_perform(pa
@@ -3407,31 +3407,16 @@
perform(
-payload_class,
metadata
|
da0794fd63960fa8a836e27ab540cd9f8b8713d7
|
Test program for issue #81
|
unresolved_bugs/bug_81.py
|
unresolved_bugs/bug_81.py
|
Python
| 0
|
@@ -0,0 +1,1118 @@
+# -*- coding: utf-8 -*-%0A%22%22%22%0A Aho-Corasick string search algorithm.%0A%0A Author : Wojciech Mu%C5%82a, wojciech_mula@poczta.onet.pl%0A WWW : http://0x80.pl%0A License : public domain%0A%22%22%22%0A%0Aimport os%0Aimport sys%0A%0Aimport ahocorasick%0A%0A%0Atry:%0A range = xrange # for Py2%0Aexcept NameError:%0A pass%0A%0Adef get_memory_usage():%0A # Linux only%0A pid = os.getpid()%0A%0A lines = %5B%5D%0A try:%0A with open('/proc/%25d/status' %25 pid, 'rt') as f:%0A lines = f.readlines()%0A except:%0A pass%0A%0A for line in lines:%0A if line.startswith('VmSize'):%0A return float(line.split()%5B1%5D)%0A%0A return 0%0A%0Adef test():%0A with open('README.rst', 'r') as f:%0A data = f.read().split()%0A%0A ac = ahocorasick.Automaton()%0A for i, word in enumerate(data):%0A ac.add_word(word, i)%0A%0A ac.make_automaton()%0A%0A for i in range(1024):%0A s = list(ac.keys())%0A%0A%0Aif __name__ == '__main__':%0A%0A before = get_memory_usage()%0A test()%0A after = get_memory_usage()%0A%0A print(%22Memory's usage growth: %25s (before = %25s, after = %25s)%22 %25 (after - before, before, after))%0A assert(before == after)%0A%0A
|
|
1d4137d43f1b91400d1347d131f56b1698163337
|
Create rockpaper.py
|
rockpaper.py
|
rockpaper.py
|
Python
| 0.000159
|
@@ -0,0 +1,2429 @@
+import players%0A%0Adef showdown(human_choice, computer_guess, h_obj, c_obj):%0A if (human_choice, computer_guess) == (1, 3):%0A print('Rock crushes scissors. Human Wins!')%0A print('-------------------------------------')%0A h_obj.add_to_score()%0A elif (human_choice, computer_guess) == (1, 2):%0A print('Paper smothers rock. Computer Wins!')%0A print('-------------------------------------')%0A c_obj.add_to_score()%0A elif (human_choice, computer_guess) == (2, 1):%0A print('Paper smothers rock. Human Wins!')%0A print('-------------------------------------')%0A h_obj.add_to_score()%0A elif (human_choice, computer_guess) == (2, 3):%0A print('Scissors cut paper. Computer Wins!')%0A print('-------------------------------------')%0A c_obj.add_to_score()%0A elif (human_choice, computer_guess) == (3, 2):%0A print('Scissors cut paper. Human Wins!')%0A print('-------------------------------------')%0A h_obj.add_to_score()%0A elif (human_choice, computer_guess) == (3, 1):%0A print('Rock crushes scissors. Computer Wins!')%0A print('-------------------------------------')%0A c_obj.add_to_score()%0A elif (human_choice, computer_guess) == (1, 1):%0A print('Were all getting our Rocks on today!')%0A print('------------------------------------')%0A elif (human_choice, computer_guess) == (2, 2):%0A print('Paper is on sale at Office Depot!!!!')%0A print('------------------------------------')%0A elif (human_choice, computer_guess) == (3, 3):%0A print('Scissors! Dead Again is a great movie!')%0A print('--------------------------------------')%0A else:%0A print('Hmmm... something is wrong with the code.')%0A %0A%0Adef main():%0A human = players.Human()%0A computer = players.Computer()%0A while human.score %3C 10 and computer.score %3C 10:%0A print('Human: %7B%7D ... '%0A 'Computer: %7B%7D'.format(human.score, computer.score))%0A print('====================================================')%0A showdown(human.user_output(),computer.get_random(), human, computer)%0A if human.score %3E computer.score:%0A print('Human wins by score '%0A 'of %7B%7D to %7B%7D'.format(human.score, computer.score))%0A else:%0A print('Computer wins by score '%0A 'of %7B%7D to %7B%7D'.format(computer.score, human.score))%0A%0Aif __name__ == '__main__':%0A main()%0A %0A %0A%0A%0A
|
|
48fc7cad7eb4cec0b928aba3daca7e934d46d87c
|
Add unit tests for sdnvpn
|
functest/tests/unit/features/test_sdnvpn.py
|
functest/tests/unit/features/test_sdnvpn.py
|
Python
| 0
|
@@ -0,0 +1,1100 @@
+#!/usr/bin/env python%0A%0A# Copyright (c) 2017 Orange and others.%0A#%0A# All rights reserved. This program and the accompanying materials%0A# are made available under the terms of the Apache License, Version 2.0%0A# which accompanies this distribution, and is available at%0A# http://www.apache.org/licenses/LICENSE-2.0%0A%0A# pylint: disable=missing-docstring%0A%0Aimport logging%0Aimport unittest%0A%0Afrom functest.opnfv_tests.features import sdnvpn%0Afrom functest.utils import constants%0A%0A%0Aclass SdnVpnTesting(unittest.TestCase):%0A%0A logging.disable(logging.CRITICAL)%0A%0A def setUp(self):%0A self.sdnvpn = sdnvpn.SdnVpnTests()%0A%0A def test_init(self):%0A self.assertEqual(self.sdnvpn.project_name, %22sdnvpn%22)%0A self.assertEqual(self.sdnvpn.case_name, %22bgpvpn%22)%0A self.assertEqual(%0A self.sdnvpn.repo,%0A constants.CONST.__getattribute__(%22dir_repo_sdnvpn%22))%0A self.assertEqual(%0A self.sdnvpn.cmd,%0A 'cd %7B%7D/sdnvpn/test/functest && python ./run_tests.py'.format(%0A self.sdnvpn.repo))%0A%0A%0Aif __name__ == %22__main__%22:%0A unittest.main(verbosity=2)%0A
|
|
35f19e61df4c14a2766709f6ab88f08e7fab9756
|
add run_test
|
run_tests.py
|
run_tests.py
|
Python
| 0.000001
|
@@ -0,0 +1,492 @@
+#!/usr/bin/env python%0Aimport sys%0Aimport pytest%0A%0Aif __name__ == '__main__':%0A # show output results from every test function%0A args = %5B'-v'%5D%0A # show the message output for skipped and expected failure tests%0A args.append('-vrxs')%0A if len(sys.argv) %3E 1:%0A args.extend(sys.argv%5B1:%5D)%0A print('pytest arguments: %7B%7D'.format(args))%0A # call pytest and exit with the return code from pytest so that%0A # travis will fail correctly if tests fail%0A sys.exit(pytest.main(args))%0A
|
|
a91b633ba88a01b12305fdfafd570c0b3776b42d
|
Add a tool script to print errors statistics in output JSON files.
|
utils/print_num_errors.py
|
utils/print_num_errors.py
|
Python
| 0
|
@@ -0,0 +1,1798 @@
+#!/usr/bin/env python3%0A# -*- coding: utf-8 -*-%0A%0A%22%22%22%0AMake statistics on score files (stored in JSON files).%0A%22%22%22%0A%0Aimport argparse%0Aimport json%0Aimport numpy as np%0A%0A%0Adef parse_json_file(json_file_path):%0A with open(json_file_path, %22r%22) as fd:%0A json_data = json.load(fd)%0A return json_data%0A%0A%0Adef extract_data_list(json_dict):%0A io_list = json_dict%5B%22io%22%5D%0A%0A success_list = %5Bimage_dict for image_dict in io_list if %22error%22 not in image_dict%5D%0A aborted_list = %5Bimage_dict for image_dict in io_list if %22error%22 in image_dict%5D%0A%0A return success_list, aborted_list%0A%0A%0Aif __name__ == '__main__':%0A%0A # PARSE OPTIONS ###########################################################%0A%0A parser = argparse.ArgumentParser(description=%22Make statistics on score files (JSON files).%22)%0A%0A parser.add_argument(%22fileargs%22, nargs=1, metavar=%22FILE%22,%0A help=%22The JSON file to process%22)%0A%0A args = parser.parse_args()%0A json_file_path = args.fileargs%5B0%5D%0A%0A # FETCH SCORE #############################################################%0A%0A json_data = parse_json_file(json_file_path)%0A%0A success_list, aborted_list = extract_data_list(json_data)%0A%0A print(%22%7B%7D images%22.format(len(success_list) + len(aborted_list)))%0A print(%22%7B%7D succeeded%22.format(len(success_list)))%0A print(%22%7B%7D failed%22.format(len(aborted_list)))%0A%0A if len(aborted_list) %3E 0:%0A error_message_dict = %7B%7D%0A for image_dict in aborted_list:%0A error_message = image_dict%5B%22error%22%5D%5B%22message%22%5D%0A if error_message in error_message_dict:%0A error_message_dict%5Berror_message%5D += 1%0A else:%0A error_message_dict%5Berror_message%5D = 1%0A%0A for error_message, count in error_message_dict.items():%0A print(%22-%3E %7B%7D: %7B%7D%22.format(error_message, count))%0A
|
|
4a06723a475fb6312196ea4e0a5ee47414a2c157
|
add power_line, power_minor_line
|
integration-test/232-power-lines.py
|
integration-test/232-power-lines.py
|
Python
| 0.00001
|
@@ -0,0 +1,599 @@
+from . import FixtureTest%0A%0A%0Aclass PowerLines(FixtureTest):%0A%0A def test_power_line(self):%0A self.load_fixtures(%5B'http://www.openstreetmap.org/way/29399873'%5D)%0A%0A self.assert_has_feature(%0A 14, 2621, 6338, 'landuse',%0A %7B'id': 29399873, 'kind': 'power_line', 'min_zoom': 14, 'sort_rank': 272%7D)%0A%0A def test_power_line(self):%0A self.load_fixtures(%5B'http://www.openstreetmap.org/way/444660087'%5D)%0A%0A self.assert_has_feature(%0A 16, 10485, 25335, 'landuse',%0A %7B'id': 444660087, 'kind': 'power_minor_line', 'min_zoom': 17, 'sort_rank': 271%7D)%0A
|
|
e2d72a20b241fe2dca1dad1eb391350460c06060
|
Update TFRT dependency to use revision http://github.com/tensorflow/runtime/commit/4efe74c2473de1220989199258b7a4924dd2a679.
|
third_party/tf_runtime/workspace.bzl
|
third_party/tf_runtime/workspace.bzl
|
"""Provides the repository macro to import TFRT."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
"""Imports TFRT."""
# Attention: tools parse and update these lines.
TFRT_COMMIT = "ab36dc9c9829c8574b7760e98de18cc4d2b2eaf3"
TFRT_SHA256 = "afe45af9014fdf72e5a58cbfcea2c17522c7ce1a082c1a33b8bcf3db3fac5fd1"
tf_http_archive(
name = "tf_runtime",
sha256 = TFRT_SHA256,
strip_prefix = "runtime-{commit}".format(commit = TFRT_COMMIT),
urls = [
"http://mirror.tensorflow.org/github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
"https://github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
],
)
|
Python
| 0.000003
|
@@ -210,133 +210,133 @@
= %22
-ab36dc9c9829c8574b7760e98de18cc4d2b2eaf3%22%0A TFRT_SHA256 = %22afe45af9014fdf72e5a58cbfcea2c17522c7ce1a082c1a33b8bcf3db3fac5fd1
+4efe74c2473de1220989199258b7a4924dd2a679%22%0A TFRT_SHA256 = %2276e8b79220d0d68362782b1877b279dacdaa0a9c4b3a80004cf70cca8131414f
%22%0A%0A
|
0b47397b91fec94910f18ea1711184ecfd0f6bf0
|
Add tests for file storage engine
|
jacquard/storage/tests/test_file.py
|
jacquard/storage/tests/test_file.py
|
Python
| 0
|
@@ -0,0 +1,1550 @@
+from jacquard.storage.file import FileStore%0A%0A%0Adef test_get_nonexistent_key():%0A # Just test this works without errors%0A store = FileStore(':memory:')%0A assert store.get('test') is None%0A%0A%0Adef test_simple_write():%0A storage = FileStore(':memory:')%0A with storage.transaction() as store:%0A store%5B'test'%5D = %22Bees%22%0A with storage.transaction() as store:%0A assert store%5B'test'%5D == %22Bees%22%0A%0A%0Adef test_enumerate_keys():%0A storage = FileStore(':memory:')%0A%0A with storage.transaction() as store:%0A store%5B'foo1'%5D = %22Bees%22%0A store%5B'foo2'%5D = %22Faces%22%0A%0A with storage.transaction() as store:%0A assert set(store.keys()) == set(('foo1', 'foo2'))%0A%0A%0Adef test_update_key():%0A storage = FileStore(':memory:')%0A%0A with storage.transaction() as store:%0A store%5B'foo'%5D = %22Bees%22%0A%0A with storage.transaction() as store:%0A store%5B'foo'%5D = %22Eyes%22%0A%0A with storage.transaction() as store:%0A assert store%5B'foo'%5D == %22Eyes%22%0A%0A%0Adef test_delete_key():%0A storage = FileStore(':memory:')%0A%0A with storage.transaction() as store:%0A store%5B'foo'%5D = %22Bees%22%0A%0A with storage.transaction() as store:%0A del store%5B'foo'%5D%0A%0A with storage.transaction() as store:%0A assert 'foo' not in store%0A%0A%0Adef test_exceptions_back_out_writes():%0A storage = FileStore(':memory:')%0A%0A try:%0A with storage.transaction() as store:%0A store%5B'foo'%5D = %22Blah%22%0A raise RuntimeError()%0A except RuntimeError:%0A pass%0A%0A with storage.transaction() as store:%0A assert 'foo' not in store%0A
|
|
d56387ee3edb05aee87bb732fb60b9d3a5e8a94b
|
Add a simple setup.py script
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,582 @@
+#!/usr/bin/env python%0A%0AUSE_SETUPTOOLS = False%0Atry:%0A from setuptools import setup, Extension%0A USE_SETUPTOOLS = True%0Aexcept ImportError:%0A from distutils.core import setup, Extension%0A%0A%0Asetup_kwargs = dict(%0A name='greendns',%0A description='''A module for providing greened DNS access via dnspython ''',%0A version='0.1.0',%0A author='R. Tyler Ballance',%0A author_email='tyler@monkeypox.org',%0A py_modules=%5B'greendns',%5D,%0A url='http://rtyler.github.com/greendns')%0A%0Aif USE_SETUPTOOLS:%0A setup_kwargs.update(%7B'test_suite' : 'test_greendns'%7D)%0A%0Asetup(**setup_kwargs)%0A
|
|
daf53c1d5564942651e5efac0d1daa9dbd7248f2
|
Create setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,70 @@
+%22%22%22Setup script for lechat.%22%22%22%0A%0Afrom setuptools import setup%0A%0Asetup()%0A
|
|
f02d51237443ce239ab44ef7bb38fb625cd0fac1
|
Add generic main function setup to test env
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,122 @@
+#!/Applications/anaconda/envs/Python3/bin%0A%0Adef main():%0A print(%22Hello, World!%22)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
7938b647951bb83604c34ebf0932200e13913e35
|
Bump version.
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import sys
assert sys.version >= '2.5', "Requires Python v2.5 or above."
from distutils.core import setup
from setuptools import find_packages
setup(
name="django-loginas",
version="0.1.2",
author="Stochastic Technologies",
author_email="info@stochastictechnologies.com",
url="https://github.com/stochastic-technologies/django-loginas/",
description="""An app to add a "Log in as user" button in the Django user admin page.""",
long_description="A short Django app that adds a button in the Django user admin page. "
"When a superuser clicks the button, they are instantly logged in as that "
"user.",
license="BSD",
keywords="django",
zip_safe=False,
include_package_data=True,
packages=find_packages(),
test_suite='runtests.run_tests',
tests_require=['Django>=1.4'],
)
|
Python
| 0
|
@@ -211,17 +211,17 @@
on=%220.1.
-2
+3
%22,%0A a
|
162c3cd9b12e559242215d395ae85fc75d8ba37d
|
Create pl_list.py
|
pl_list.py
|
pl_list.py
|
Python
| 0.000002
|
@@ -0,0 +1,2391 @@
+__author__ = %22Dan C Williams%22%0A__version__ = %220.2%22%0A__date__ = %22Jul-24-2016%22%0A__email__ = %22dan.c.williams@gmail.com%22%0A__status__ = %22Development%22%0A__version__ = %22Python 3.5%22%0A%0Aimport netaddr%0Aimport collections%0A%0Araw_lines = %5Bline.rstrip('%5Cn') for line in open('TEST_PL_DATA.txt')%5D%0AblackList = %5B'0.0.0.0/0', 'description', '!'%5D%0Asplit_list = %5B%5D%0Aip_list =%5B%5D%0Apl_list = %5B%5D%0Apl_dict = collections.defaultdict(list)%0Apl_dict_final = %7B%7D%0Adel_list = %5B%5D%0Atemp_list = %5B%5D%0Asplit_list = %5B%5D%0A%0Adef main():%0A%0A temp_list = %5B%5D%0A %0A for i, line in enumerate(raw_lines): # IDs DESCRIPTIONS & DEFAULT ROUTES%0A for j in blackList:%0A if j in line:%0A temp_list.append(line)%0A%0A for del_lines in temp_list: # CLEARS OUT DESCRIPTIONS & DEFAULT ROUTES%0A raw_lines.remove(del_lines)%0A%0A for i, line in enumerate(raw_lines):%0A temp_list = line.split() #SPLITTING LINES INTO LIST%0A split_list.append(temp_list) #ADDING LIST TO LIST OF LIST%0A temp_list = %5B%5D #Reset TEMP List%0A%0A for i, line in enumerate(split_list): #Grab PL name and network and place them%0A temp_list.append(line%5B2%5D) #in a list of lists for further processing%0A temp_list.append(line%5B6%5D)%0A pl_list.append(temp_list)%0A temp_list = %5B%5D%0A%0A for key, value in pl_list: #create pl_dict using the key and network%0A pl_dict%5Bkey%5D.append(netaddr.IPNetwork(value))%0A%0A for key, value in pl_dict.items():%0A value = netaddr.cidr_merge(value)%0A value.sort()%0A pl_dict_final%5Bkey%5D = value%0A%0A target = open('test_output.txt', 'w')%0A%0A d = collections.OrderedDict(sorted(pl_dict_final.items()))%0A%0A for key, value in d.items():%0A seq_num = 5%0A target.write(%22ip prefix-list %22 + str(key) + %22 description Permit Networks Assigned to the Aviation BU%5Cn%22)%0A for i, ip_address in enumerate(value):%0A if str(ip_address.netmask) == '255.255.255.255':%0A target.write(%22ip prefix-list %22 + str(key) + %22 seq %22 + str(seq_num) + %22 permit %22 + str(ip_address) + (%22%5Cn%22))%0A else:%0A target.write(%22ip prefix-list %22 + str(key) + %22 seq %22 + str(seq_num) + %22 permit %22 + str(ip_address) + %22 le 32%5Cn%22)%0A seq_num += 5%0A target.write(%22ip prefix-list %22 + str(key) + %22 seq 500000 deny 0.0.0.0/0 le 32%5Cn%22)%0A target.write(%22!%5Cn%22)%0A%0A target.close()%0A%0A print('COMPLETE')%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
|
|
dc1d43acb5730bd9b555b63aa589b0eeceb14e52
|
Add a test case to exercise the 'target stop-hook add' command without relying on pexpect to spawn an lldb child command. The test is not "correct" in that the '** Stop Hooks **' message emitted by the Target implementation is invoked asynchronously and is using a separate:
|
test/stop-hook/TestStopHookCmd.py
|
test/stop-hook/TestStopHookCmd.py
|
Python
| 0.000194
|
@@ -0,0 +1,2716 @@
+%22%22%22%0ATest lldb target stop-hook command.%0A%22%22%22%0A%0Aimport os%0Aimport unittest2%0Aimport lldb%0Aimport pexpect%0Afrom lldbtest import *%0A%0Aclass StopHookCmdTestCase(TestBase):%0A%0A mydir = %22stop-hook%22%0A%0A @unittest2.skipUnless(sys.platform.startswith(%22darwin%22), %22requires Darwin%22)%0A def test_with_dsym(self):%0A %22%22%22Test a sequence of target add-hook commands.%22%22%22%0A self.buildDsym()%0A self.stop_hook_cmd_sequence()%0A%0A def test_with_dwarf(self):%0A %22%22%22Test a sequence of target add-hook commands.%22%22%22%0A self.buildDwarf()%0A self.stop_hook_cmd_sequence()%0A%0A def setUp(self):%0A # Call super's setUp().%0A TestBase.setUp(self)%0A # Find the line numbers inside main.cpp.%0A self.begl = line_number('main.cpp', '// Set breakpoint here to test target stop-hook.')%0A self.endl = line_number('main.cpp', '// End of the line range for which stop-hook is to be run.')%0A self.line = line_number('main.cpp', '// Another breakpoint which is outside of the stop-hook range.')%0A%0A def stop_hook_cmd_sequence(self):%0A %22%22%22Test a sequence of target stop-hook commands.%22%22%22%0A exe = os.path.join(os.getcwd(), %22a.out%22)%0A self.runCmd(%22file %22 + exe, CURRENT_EXECUTABLE_SET)%0A%0A self.expect('breakpoint set -f main.cpp -l %25d' %25 self.begl,%0A BREAKPOINT_CREATED,%0A startstr = %22Breakpoint created: 1: file ='main.cpp', line = %25d%22 %25%0A self.begl)%0A self.expect('breakpoint set -f main.cpp -l %25d' %25 self.line,%0A BREAKPOINT_CREATED,%0A startstr = %22Breakpoint created: 2: file ='main.cpp', line = %25d%22 %25%0A self.line)%0A%0A self.runCmd(%22target stop-hook add -f main.cpp -l %25d -e %25d -o 'expr ptr'%22 %25 (self.begl, self.endl))%0A%0A self.runCmd('target stop-hook list')%0A%0A # Now run the program, expect to stop at the the first breakpoint which is within the stop-hook range.%0A #self.expect('run', 'Stop hook fired',%0A # substrs = '** Stop Hooks **')%0A self.runCmd('run')%0A self.runCmd('thread step-over')%0A self.expect('thread step-over', 'Stop hook fired again',%0A substrs = '** Stop Hooks **')%0A%0A # Now continue the inferior, we'll stop at another breakpoint which is outside the stop-hook range.%0A self.runCmd('process continue')%0A # Verify that the 'Stop Hooks' mechanism is NOT BEING fired off.%0A self.expect('thread step-over', 'Stop hook should not be fired', matching=False,%0A substrs = '** Stop Hooks **')%0A %0A%0Aif __name__ == '__main__':%0A import atexit%0A lldb.SBDebugger.Initialize()%0A atexit.register(lambda: lldb.SBDebugger.Terminate())%0A unittest2.main()%0A
|
|
250e0d2d0e2264b83a82548df3b30dbc784a4fe5
|
Add some example client code
|
docker-registry-show.py
|
docker-registry-show.py
|
Python
| 0.000001
|
@@ -0,0 +1,3157 @@
+%22%22%22%0ACopyright 2015 Red Hat, Inc%0A%0ALicensed under the Apache License, Version 2.0 (the %22License%22);%0Ayou may not use this file except in compliance with the License.%0AYou may obtain a copy of the License at%0A%0A http://www.apache.org/licenses/LICENSE-2.0%0A%0AUnless required by applicable law or agreed to in writing, software%0Adistributed under the License is distributed on an %22AS IS%22 BASIS,%0AWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0ASee the License for the specific language governing permissions and%0Alimitations under the License.%0A%22%22%22%0A%0A%0Afrom __future__ import absolute_import%0A%0Aimport argparse%0Afrom docker_registry_client import DockerRegistryClient%0Aimport logging%0Aimport requests%0A%0A%0Aclass CLI(object):%0A def __init__(self):%0A self.parser = argparse.ArgumentParser()%0A excl_group = self.parser.add_mutually_exclusive_group()%0A excl_group.add_argument(%22-q%22, %22--quiet%22, action=%22store_true%22)%0A excl_group.add_argument(%22-v%22, %22--verbose%22, action=%22store_true%22)%0A%0A self.parser.add_argument('--verify-ssl', dest='verify_ssl',%0A action='store_true')%0A self.parser.add_argument('--no-verify-ssl', dest='verify_ssl',%0A action='store_false')%0A%0A self.parser.add_argument('registry', metavar='REGISTRY', nargs=1,%0A help='registry URL (including scheme)')%0A self.parser.add_argument('repository', metavar='REPOSITORY', nargs='?')%0A%0A self.parser.set_defaults(verify_ssl=True)%0A%0A def run(self):%0A args = self.parser.parse_args()%0A%0A basic_config_args = %7B%7D%0A if args.verbose:%0A basic_config_args%5B'level'%5D = logging.DEBUG%0A elif args.quiet:%0A basic_config_args%5B'level'%5D = logging.WARNING%0A%0A logging.basicConfig(**basic_config_args)%0A%0A client = DockerRegistryClient(args.registry%5B0%5D,%0A verify_ssl=args.verify_ssl)%0A%0A if args.repository:%0A self.show_tags(client, args.repository)%0A else:%0A self.show_repositories(client)%0A%0A def show_repositories(self, client):%0A try:%0A repositories = client.repositories()%0A except requests.HTTPError as e:%0A if e.response.status_code == requests.codes.not_found:%0A print(%22Catalog/Search not supported%22)%0A else:%0A raise%0A else:%0A print(%22Repositories:%22)%0A for repository in repositories.keys():%0A print(%22 - %7B0%7D%22.format(repository))%0A%0A def show_tags(self, client, repository):%0A try:%0A repo = client.repository(repository)%0A except requests.HTTPError as e:%0A if e.response.status_code == requests.codes.not_found:%0A print(%22Repository %7B0%7D not found%22.format(repository))%0A else:%0A raise%0A else:%0A print(%22Tags in repository %7B0%7D:%22.format(repository))%0A for tag in repo.tags():%0A print(%22 - %7B0%7D%22.format(tag))%0A%0A%0Aif __name__ == '__main__':%0A try:%0A cli = CLI()%0A cli.run()%0A except KeyboardInterrupt:%0A pass%0A
|
|
94ca75328c7aeeb80815ef5e4af6bcbbeaeb53be
|
Update the example emane 802.11 python script.
|
daemon/examples/netns/emane80211.py
|
daemon/examples/netns/emane80211.py
|
#!/usr/bin/python -i
# Copyright (c)2010-2014 the Boeing Company.
# See the LICENSE file included in this distribution.
# Example CORE Python script that attaches N nodes to an EMANE 802.11abg
# network. One of the parameters is changed, the pathloss mode.
import sys, datetime, optparse
from core import pycore
from core.misc import ipaddr
from core.constants import *
from core.emane.ieee80211abg import EmaneIeee80211abgModel
# node list (count from 1)
n = [None]
def main():
usagestr = "usage: %prog [-h] [options] [args]"
parser = optparse.OptionParser(usage = usagestr)
parser.set_defaults(numnodes = 5)
parser.add_option("-n", "--numnodes", dest = "numnodes", type = int,
help = "number of nodes")
def usage(msg = None, err = 0):
sys.stdout.write("\n")
if msg:
sys.stdout.write(msg + "\n\n")
parser.print_help()
sys.exit(err)
# parse command line options
(options, args) = parser.parse_args()
if options.numnodes < 1:
usage("invalid number of nodes: %s" % options.numnodes)
for a in args:
sys.stderr.write("ignoring command line argument: '%s'\n" % a)
start = datetime.datetime.now()
# IP subnet
prefix = ipaddr.IPv4Prefix("10.83.0.0/16")
# session with some EMANE initialization
session = pycore.Session(persistent=True)
session.master = True
session.location.setrefgeo(47.57917,-122.13232,2.00000)
session.location.refscale = 150.0
session.cfg['emane_models'] = "RfPipe, Ieee80211abg, Bypass"
session.emane.loadmodels()
if 'server' in globals():
server.addsession(session)
# EMANE WLAN
print "creating EMANE WLAN wlan1"
wlan = session.addobj(cls = pycore.nodes.EmaneNode, name = "wlan1")
wlan.setposition(x=80,y=50)
names = EmaneIeee80211abgModel.getnames()
values = list(EmaneIeee80211abgModel.getdefaultvalues())
# TODO: change any of the EMANE 802.11 parameter values here
try:
values[ names.index('pathlossmode') ] = 'pathloss'
except ValueError:
values[ names.index('propagationmodel') ] = 'precomputed'
session.emane.setconfig(wlan.objid, EmaneIeee80211abgModel._name, values)
services_str = "zebra|OSPFv3MDR|vtysh|IPForward"
print "creating %d nodes with addresses from %s" % \
(options.numnodes, prefix)
for i in xrange(1, options.numnodes + 1):
tmp = session.addobj(cls = pycore.nodes.CoreNode, name = "n%d" % i,
objid=i)
tmp.newnetif(wlan, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
tmp.cmd([SYSCTL_BIN, "net.ipv4.icmp_echo_ignore_broadcasts=0"])
tmp.setposition(x=150*i,y=150)
session.services.addservicestonode(tmp, "", services_str, verbose=False)
n.append(tmp)
# this starts EMANE, etc.
session.node_count = str(options.numnodes + 1)
session.instantiate()
# start a shell on node 1
n[1].term("bash")
print "elapsed time: %s" % (datetime.datetime.now() - start)
if __name__ == "__main__" or __name__ == "__builtin__":
main()
|
Python
| 0
|
@@ -1327,16 +1327,47 @@
ization%0A
+ cfg = %7B'verbose': 'false'%7D%0A
sess
@@ -1387,16 +1387,27 @@
Session(
+cfg = cfg,
persiste
@@ -1412,12 +1412,15 @@
tent
-=Tru
+ = Fals
e)%0A
@@ -2093,24 +2093,20 @@
') %5D = '
-pathloss
+2ray
'%0A ex
@@ -2179,19 +2179,12 @@
= '
-precomputed
+2ray
'%0A%0A
|
e7cbd3e2d5a21b003c6ee392da5b8ebe70d279a8
|
add lockfile dependency
|
setup.py
|
setup.py
|
#########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
from setuptools import setup
setup(
name='cloudify-script-plugin',
version='1.1a1',
author='Gigaspaces',
author_email='cloudify@gigaspaces.com',
packages=['script_runner'],
description='Plugin for running scripts',
install_requires=[
'cloudify-plugins-common==3.1a1',
'pyzmq==14.3.1',
'bottle==0.12.7'
],
license='LICENSE',
entry_points={
'console_scripts': [
'ctx = script_runner.ctx_proxy:main',
'ctx-server = script_runner.ctx_server:main'
]
}
)
|
Python
| 0.000001
|
@@ -987,16 +987,43 @@
=0.12.7'
+,%0A 'lockfile==0.9.1'
%0A %5D,%0A
|
83bcb62c98c406e2aa6ce6a9a98750d0b565f750
|
Add tests for generic hash
|
tests/unit/test_raw_generichash.py
|
tests/unit/test_raw_generichash.py
|
Python
| 0
|
@@ -0,0 +1,532 @@
+# Import nacl libs%0Aimport libnacl%0A%0A# Import python libs%0Aimport unittest%0A%0A%0Aclass TestGenericHash(unittest.TestCase):%0A '''%0A Test sign functions%0A '''%0A def test_keyless_generichash(self):%0A msg1 = b'Are you suggesting coconuts migrate?'%0A msg2 = b'Not at all, they could be carried.'%0A chash1 = libnacl.crypto_generichash(msg1)%0A chash2 = libnacl.crypto_generichash(msg2)%0A self.assertNotEqual(msg1, chash1)%0A self.assertNotEqual(msg2, chash2)%0A self.assertNotEqual(chash2, chash1)%0A
|
|
ff814e3dff10ffa54a0569868f32056d37babff6
|
Create test1.py
|
test1.py
|
test1.py
|
Python
| 0.000018
|
@@ -0,0 +1,12 @@
+import this%0A
|
|
064124d09973dc58a444d22aa7c47acf94f8fa81
|
Add a script to generate JSON bigram frequencies for English
|
data/bigramfreq.py
|
data/bigramfreq.py
|
Python
| 0.000003
|
@@ -0,0 +1,611 @@
+import json%0Aimport lxml.html%0Afrom lxml.cssselect import CSSSelector%0Aimport requests%0Aimport sys%0A%0A%0Adef main():%0A raw = requests.get(%22http://norvig.com/mayzner.html%22)%0A if not raw:%0A print %3E%3Esys.stderr, %22Request failed with code %25d%22 %25 (raw.status_code)%0A return 1%0A%0A tree = lxml.html.fromstring(raw.text)%0A%0A sel = CSSSelector(%22td%22)%0A%0A freq = %7Bkey%5B:-1%5D.lower(): float(value%5B:-2%5D) / 100 for key, value, _ in map(lambda x: x.get(%22title%22).split(), filter(lambda y: y.get(%22title%22) is not None, sel(tree)))%7D%0A%0A print json.dumps(freq)%0A return 0%0A%0Aif __name__ == %22__main__%22:%0A sys.exit(main())%0A
|
|
b9b6b8a9337888fdcfcf15af1dedc758d0662dd0
|
add nexted evalute=False test
|
sympy/core/tests/test_evaluate.py
|
sympy/core/tests/test_evaluate.py
|
Python
| 0.000049
|
@@ -0,0 +1,440 @@
+from sympy.abc import x, y%0Afrom sympy.core.evaluate import evaluate%0Afrom sympy.core import Mul, Add%0A%0Adef test_add():%0A with evaluate(False):%0A expr = x + x%0A assert isinstance(expr, Add)%0A assert expr.args == (x, x)%0A assert isinstance(x + x, Mul)%0A%0A%0Adef test_nested():%0A with evaluate(False):%0A expr = (x + x) + (y + y)%0A assert expr.args == ((x + x), (y + y))%0A assert expr.args%5B0%5D.args == (x, x)%0A
|
|
28dc9e241b60be9b961a9f63398d2d8b3229693a
|
Test that creation fails on an unknown RAID value.
|
tests/dbus/manager/test_create.py
|
tests/dbus/manager/test_create.py
|
# Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Test 'CreatePool'.
"""
import time
import unittest
from stratisd_client_dbus import Manager
from stratisd_client_dbus import StratisdErrorsGen
from stratisd_client_dbus import get_object
from stratisd_client_dbus._implementation import ManagerSpec
from stratisd_client_dbus._constants import TOP_OBJECT
from .._misc import checked_call
from .._misc import _device_list
from .._misc import Service
_MN = ManagerSpec.MethodNames
_DEVICE_STRATEGY = _device_list(0)
class Create2TestCase(unittest.TestCase):
"""
Test 'create'.
"""
_POOLNAME = 'deadpool'
def setUp(self):
"""
Start the stratisd daemon with the simulator.
"""
self._service = Service()
self._service.setUp()
time.sleep(1)
self._proxy = get_object(TOP_OBJECT)
self._errors = StratisdErrorsGen.get_object()
Manager.ConfigureSimulator(self._proxy, denominator=8)
def tearDown(self):
"""
Stop the stratisd simulator and daemon.
"""
self._service.tearDown()
def testCreate(self):
"""
Type of result should always be correct.
If rc is OK, then pool must exist.
"""
devs = _DEVICE_STRATEGY.example()
((poolpath, devnodes), rc, _) = checked_call(
Manager.CreatePool(
self._proxy,
name=self._POOLNAME,
redundancy=0,
force=False,
devices=devs
),
ManagerSpec.OUTPUT_SIGS[_MN.CreatePool]
)
(pool, rc1, _) = checked_call(
Manager.GetPoolObjectPath(self._proxy, name=self._POOLNAME),
ManagerSpec.OUTPUT_SIGS[_MN.GetPoolObjectPath]
)
(pools, _, _) = checked_call(
Manager.ListPools(self._proxy),
ManagerSpec.OUTPUT_SIGS[_MN.ListPools]
)
if rc == self._errors.OK:
self.assertEqual(pool, poolpath)
self.assertEqual(rc1, self._errors.OK)
self.assertEqual(len(pools), 1)
self.assertLessEqual(len(devnodes), len(devs))
else:
self.assertEqual(rc1, self._errors.POOL_NOTFOUND)
self.assertEqual(len(pools), 0)
class Create3TestCase(unittest.TestCase):
"""
Test 'create' on name collision.
"""
_POOLNAME = 'deadpool'
def setUp(self):
"""
Start the stratisd daemon with the simulator.
"""
self._service = Service()
self._service.setUp()
time.sleep(1)
self._proxy = get_object(TOP_OBJECT)
self._errors = StratisdErrorsGen.get_object()
Manager.CreatePool(
self._proxy,
name=self._POOLNAME,
redundancy=0,
force=False,
devices=_DEVICE_STRATEGY.example()
)
Manager.ConfigureSimulator(self._proxy, denominator=8)
def tearDown(self):
"""
Stop the stratisd simulator and daemon.
"""
self._service.tearDown()
def testCreate(self):
"""
Create should fail trying to create new pool with same name as previous.
"""
(pools1, _, _) = checked_call(
Manager.ListPools(self._proxy),
ManagerSpec.OUTPUT_SIGS[_MN.ListPools]
)
(_, rc, _) = checked_call(
Manager.CreatePool(
self._proxy,
name=self._POOLNAME,
redundancy=0,
force=False,
devices=_DEVICE_STRATEGY.example()
),
ManagerSpec.OUTPUT_SIGS[_MN.CreatePool]
)
expected_rc = self._errors.ALREADY_EXISTS
self.assertEqual(rc, expected_rc)
(_, rc1, _) = checked_call(
Manager.GetPoolObjectPath(self._proxy, name=self._POOLNAME),
ManagerSpec.OUTPUT_SIGS[_MN.GetPoolObjectPath]
)
(pools2, _, _) = checked_call(
Manager.ListPools(self._proxy),
ManagerSpec.OUTPUT_SIGS[_MN.ListPools]
)
self.assertEqual(rc1, self._errors.OK)
self.assertEqual(pools1, pools2)
|
Python
| 0
|
@@ -1007,16 +1007,48 @@
hodNames
+%0A_MP = ManagerSpec.PropertyNames
%0A%0A_DEVIC
@@ -2823,24 +2823,616 @@
pools), 0)%0A%0A
+ def testCreateBadRAID(self):%0A %22%22%22%0A Creation should always fail if RAID value is wrong.%0A %22%22%22%0A redundancy_values = Manager.Properties.RedundancyValues(self._proxy)%0A%0A devs = _DEVICE_STRATEGY.example()%0A (_, rc, _) = checked_call(%0A Manager.CreatePool(%0A self._proxy,%0A name=self._POOLNAME,%0A redundancy=len(redundancy_values),%0A force=False,%0A devices=devs%0A ),%0A ManagerSpec.OUTPUT_SIGS%5B_MN.CreatePool%5D%0A )%0A self.assertEqual(rc, self._errors.ERROR)%0A
%0Aclass Creat
|
9f551b236a5d4052f2371cc11613e84808f43dee
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,501 @@
+#!/usr/bin/env python%0Afrom distutils.core import setup%0A%0Asetup(%0A name='pyvk',%0A version='2016.08',%0A packages=%5B'pyvk'%5D,%0A url='https://github.com/sgaynetdinov/pyvk',%0A license='MIT License',%0A author='Sergey Gaynetdinov',%0A author_email='s.gaynetdinov@gmail.com',%0A description='Python API wrapper around vk.com API',%0A classifiers=%5B%0A 'Programming Language :: Python',%0A 'Programming Language :: Python :: 2.7'%0A %5D,%0A install_requires=%5B%0A 'requests',%0A %5D,%0A)%0A
|
|
fcd027a115fd3c690f042468c303eeedc74774fa
|
Use setuptools instead of distribute.
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from distutils.core import setup
setup(
name='facebook-sdk',
version='0.4.0',
description='This client library is designed to support the Facebook '
'Graph API and the official Facebook JavaScript SDK, which '
'is the canonical way to implement Facebook authentication.',
author='Facebook',
maintainer='Martey Dodoo',
maintainer_email='facebook-sdk@marteydodoo.com',
url='https://github.com/pythonforfacebook/facebook-sdk',
license='Apache',
py_modules=[
'facebook',
],
long_description=open("README.rst").read(),
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
install_requires=[
'requests',
],
)
|
Python
| 0
|
@@ -24,22 +24,18 @@
rom
-distutils.core
+setuptools
imp
|
923c6b5a4181dfd9ae3f3c26ba411a63e27a79fe
|
add test for custom argument parser
|
tests/test_custom_argument_parser.py
|
tests/test_custom_argument_parser.py
|
Python
| 0
|
@@ -0,0 +1,241 @@
+import pytest%0A%0Afrom python_utility.custom_argument_parser import CustomArgumentParser%0A%0A%0Adef test_custom_argument_parser() -%3E None:%0A parser = CustomArgumentParser()%0A%0A with pytest.raises(SystemExit):%0A parser.error(message='test')%0A
|
|
220671d4bc2300983cf200cc6f7834efef458ff1
|
add a new factors module
|
modules/factors.py
|
modules/factors.py
|
Python
| 0
|
@@ -0,0 +1,536 @@
+# finding all factors for a given number%0Adef find_factors(x): # define a function%0A print (%22The factors of %22, x, %22 are: %22)%0A for i in range(1, x + 1):%0A if x %25 i == 0:%0A print(i)%0A%0Adef print_factors():%0A # ask the user to input a number%0A num = input(%22Enter a number to print its factors: %22)%0A if num %3E= 0: # check if the number is positive%0A find_factors(num)%0A elif num %3C 0: # if not, take the absolute value and find its factors%0A numNew = abs(num)%0A find_factors(numNew)%0A else:%0A print(%22Please enter a valid number.%22)%0A
|
|
291117e0c56fb00fd27c93a95b883784cf69c9bc
|
add dataset parser
|
apps/paper/dataset.py
|
apps/paper/dataset.py
|
Python
| 0.000083
|
@@ -0,0 +1,1075 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A'''%0ACreated on March 7, 2014%0A%0A@author: Chunwei Yan @ PKU%0A@mail: yanchunwei@outlook.com%0A'''%0Afrom __future__ import division%0A%0A%0Aclass DUC(object):%0A def __init__(self, path):%0A self.path = path%0A%0A def get_text(self):%0A '''%0A get lines of the TEXT%0A '''%0A content = %5B%5D%0A with open(self.path) as f:%0A begin = False%0A for line in f.readlines():%0A if line.find('%3CTEXT%3E') != -1:%0A begin = True%0A elif line.find('%3C/TEXT%3E') != -1:%0A break%0A elif begin == True:%0A content.append(line.strip())%0A return content%0A%0A def get_sentences(self):%0A '''%0A :return: %0A list of sentences(str)%0A '''%0A content = ' '.join(self.get_text())%0A sentences = content.split('.')%0A return sentences%0A%0A%0A%0A%0Aif __name__ == '__main__':%0A duc = DUC('/home/chunwei/Lab/NeuralNetworks/apps/paper/data/duc2005_docs/d301i/FT921-10162')%0A duc.get_sentences()%0A
|
|
070d3f780ffab6e866fb3d1d7fc21bd77fb31ae6
|
Add momento pattern
|
momento-pattern.py
|
momento-pattern.py
|
Python
| 0.000052
|
@@ -0,0 +1,991 @@
+#!/usr/bin/python%0Aimport copy%0A%0A%0Aclass Originator(object):%0A%0A class Memento(object):%0A def __init__(self, mstate):%0A self.mstate = mstate%0A%0A def rollback_state(self):%0A return self.mstate%0A%0A def set_state(self, state):%0A print ('Originator: setup state to: %7B0%7D'.format(state))%0A self.state = state%0A%0A def get_state(self):%0A print ('Originator: reading state to: %7B0%7D'.format(self.state))%0A%0A def save_state(self):%0A print ('Originator: saving state')%0A return self.Memento(copy.deepcopy(self))%0A%0A def rollback_state(self, memento):%0A self = memento.rollback_state()%0A print ('Originator: rollbac to state: %7B0%7D'.format(self.state))%0A%0A%0Aif __name__ == '__main__':%0A orig = Originator()%0A orig.set_state('State 1')%0A orig.get_state()%0A orig.set_state('State 2')%0A orig.get_state()%0A saved_state = orig.save_state()%0A orig.set_state('State 3')%0A orig.get_state()%0A orig.rollback_state(saved_state)%0A
|
|
8e3e1883b9aa25091b6a9a1b4684128bd56659f7
|
Add new test
|
setup.py
|
setup.py
|
Python
| 0.000004
|
@@ -0,0 +1,1534 @@
+%22%22%22%0AFinix Python client library.%0ASee %60%60README.md%60%60 for usage advice.%0A%22%22%22%0A%0Aimport os%0Aimport re%0A%0Atry:%0A import setuptools%0Aexcept ImportError:%0A import distutils.core%0A%0A setup = distutils.core.setup%0Aelse:%0A setup = setuptools.setup%0A%0APACKAGE = next((str(s) for s in setuptools.find_packages('.', exclude=(%22tests%22, %22tests.*%22))), None)%0APWD = os.path.abspath(os.path.dirname(__file__))%0AVERSION = (%0A re%0A .compile(r%22.*__version__ = '(.*?)'%22, re.S)%0A .match(open(os.path.join(PWD, PACKAGE, %22__init__.py%22)).read())%0A .group(1)%0A)%0A%0Awith open(os.path.join(PWD, %22README.md%22)) as f:%0A README = f.read()%0A%0Arequires = %5B%0A %22coreapi==1.20.0%22,%0A %22finix-wac==0.31%22%0A%5D%0A%0Aextras_require = %7B%0A %22tests%22: %5B%0A %5D%0A%7D%0A%0Ascripts = %5B%0A # 'bin/citadel'%0A%5D%0A%0Asetup(%0A name=PACKAGE,%0A version=VERSION,%0A url='https://finixpayments.com/',%0A license='MIT License',%0A author='Finix Payments',%0A author_email='dev@finixpayments.com',%0A description='Payments API',%0A long_description=README,%0A packages=%5BPACKAGE%5D,%0A test_suite='nose.collector',%0A install_requires=requires,%0A tests_require=extras_require%5B'tests'%5D,%0A dependency_links=%5B%5D,%0A classifiers=%5B%0A 'Intended Audience :: Developers',%0A 'License :: OSI Approved :: MIT License',%0A 'Programming Language :: Python',%0A 'Topic :: Software Development :: Libraries :: Python Modules',%0A %5D,%0A include_package_data=True,%0A zip_safe=False,%0A scripts=scripts,%0A extras_require=extras_require,%0A setup_requires=%5B'nose%3E=1.3.7'%5D%0A)%0A
|
|
0fe1d3eb78ef3d2c5dbbd5a662829309ab808a6f
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,151 @@
+from setuptools import setup%0A%0Atreeano_version = '0.0.1'%0A%0Asetup(%0A name=%22treeano%22,%0A version=treeano_version,%0A packages=%5B%22treeano%22, %22canopy%22%5D%0A)%0A%0A
|
|
529d9328570febd037077cfe865feedb841a1162
|
Create setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,1599 @@
+from distutils.core import setup%0Asetup(%0A name = 'autoD', # How you named your package folder (MyLib)%0A packages = %5B'autoD'%5D, # Chose the same as %22name%22%0A version = '3.7.0', # Start with a small number and increase it with every change you make%0A license='MIT', # Chose a license from here: https://help.github.com/articles/licensing-a-repository%0A description = 'Forward automatic differentiation', # Give a short description about your library%0A author = 'Wei Xuan Chan', # Type in your name%0A author_email = 'w.x.chan1986@gmail.com', # Type in your E-Mail%0A url = 'https://github.com/WeiXuanChan/autoD', # Provide either the link to your github or to your website%0A download_url = 'https://github.com/WeiXuanChan/autoD/archive/v3.7.0.tar.gz', # I explain this later on%0A keywords = %5B'automatic', 'differentiation'%5D, # Keywords that define your package best%0A install_requires=%5B'numpy'%5D,%0A %0A classifiers=%5B%0A 'Development Status :: 5 - Production/Stable', # Chose either %223 - Alpha%22, %224 - Beta%22 or %225 - Production/Stable%22 as the current state of your package %0A 'Intended Audience :: Developers', # Define that your audience are developers%0A 'Topic :: Software Development :: Build Tools', %0A 'License :: OSI Approved :: MIT License', # Again, pick a license %0A 'Programming Language :: Python :: 3', #Specify which pyhton versions that you want to support%0A 'Programming Language :: Python :: 3.4',%0A 'Programming Language :: Python :: 3.5',%0A 'Programming Language :: Python :: 3.6',%0A %5D,%0A)%0A
|
|
20b31aa5faa155639df8c206de2864af80924254
|
add setup.py script
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,275 @@
+from distutils.core import setup%0A%0Asetup(%0A name='attention',%0A version='0.1.0',%0A author='tllake',%0A author_email='thom.l.lake@gmail.com',%0A packages=%5B'attention'%5D,%0A description='An attention function for PyTorch.',%0A long_description=open('README.md').read())
|
|
5df5a19cba3bd543bcadd92d57fdd07d84b38339
|
update project page link in setup script
|
setup.py
|
setup.py
|
import os, sys
from distutils.core import setup
setup(
# metadata
name='pycparser',
description='C parser in Python',
long_description="""
pycparser is a complete parser of the C language, written in
pure Python using the PLY parsing library.
It parses C code into an AST and can serve as a front-end for
C compilers or analysis tools.
""",
license='BSD',
version='2.09',
author='Eli Bendersky',
maintainer='Eli Bendersky',
author_email='eliben@gmail.com',
url='http://code.google.com/p/pycparser/',
platforms='Cross Platform',
classifiers = [
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',],
packages=['pycparser'],
package_data={'pycparser': ['*.cfg']},
)
|
Python
| 0
|
@@ -561,28 +561,32 @@
http
+s
://
-code.google.com/p
+bitbucket.org/eliben
/pyc
@@ -591,17 +591,16 @@
ycparser
-/
',%0D%0A
|
229c54fa4122f9c08aae9b31dc6720e78daaf90d
|
add setup
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,569 @@
+#!/user/bin/env python%0A%0Afrom setuptools import setup%0A%0Asetup(%0A name='py-readability',%0A version='0.0.1',%0A description='Calculate readability scores. e.g. Gunning Fog',%0A author='Carmine DiMAscio',%0A url='https://github.com/cdimascio/py-readability',%0A packages=%5B'py-readabilitiy-metrics'%5D,%0A install_requires=%5B'nltk%3E=3.3'%5D,%0A package_data=%7B'readability': %5B%5D, '': %5B'README.md', 'LICENSE'%5D%7D,%0A package_dir=%7B'readabiliity': 'readabiliity'%7D,%0A include_package_data=True,%0A author_email='cdimascio@gmail.com',%0A license='MIT',%0A zip_safe=False,%0A)%0A
|
|
9066250b4ccdd98cd6b7cc644e829c0cfacc0a02
|
serpent for CI
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
console_scripts = ['eth=pyethereum.eth:main',
'pyethtool=tools.pyethtool_cli:main']
setup(name="pyethereum",
version='0.0.1',
packages=find_packages("."),
install_requires=[
'six', 'leveldb', 'bitcoin', 'pysha3',
'miniupnpc',
'bottle', 'waitress'],
entry_points=dict(console_scripts=console_scripts))
|
Python
| 0.999999
|
@@ -300,16 +300,46 @@
ysha3',%0A
+ 'ethereum-serpent',%0A
|
e3cd2d3880dbc00e254ac503d5f5c84ab77edc4f
|
Add Invoke tasks for cleaning and building docs.
|
tasks.py
|
tasks.py
|
Python
| 0
|
@@ -0,0 +1,149 @@
+from invoke import task, run%0A%0A@task%0Adef clean():%0A run(%22rm -rf docs/_build%22)%0A%0A@task('clean')%0Adef build():%0A run(%22sphinx-build docs docs/_build%22)%0A
|
|
75131bdf806c56970f3160de3e6d476d9ecbc3a7
|
Add problem delete note in a linked list
|
python/deleteNodeInALinkedList.py
|
python/deleteNodeInALinkedList.py
|
Python
| 0
|
@@ -0,0 +1,583 @@
+# https://leetcode.com/problems/delete-node-in-a-linked-list/%0A%0A# Definition for singly-linked list.%0A# class ListNode(object):%0A# def __init__(self, x):%0A# self.val = x%0A# self.next = None%0A%0Aclass Solution(object):%0A def deleteNode(self, node):%0A %22%22%22%0A :type node: ListNode%0A :rtype: void Do not return anything, modify node in-place instead.%0A %22%22%22%0A%0A while node.next != None:%0A node.val = node.next.val%0A if node.next.next is None:%0A node.next = None%0A else:%0A node = node.next
|
|
1a8c361d90243c44a877ebdc4ae92fbfb3226b40
|
add test file for words
|
day1/words_test.py
|
day1/words_test.py
|
Python
| 0.000001
|
@@ -0,0 +1,649 @@
+import unittest%0Aimport words%0A%0Aclass TestWordsCode(unittest.TestCase):%0A%0A def test_has_no_e(self):%0A self.assertEqual(words.has_no_e(%22bet%22), False)%0A self.assertEqual(words.has_no_e(%22bit%22), True)%0A%0A def test_uses_only(self):%0A self.assertEqual(words.uses_only(%22ababab%22, %22a%22), False)%0A self.assertEqual(words.uses_only(%22ababab%22, %22ab%22), True)%0A%0A def test_uses_all(self):%0A self.assertEqual(words.uses_all(%22ababab%22, %22abc%22), False)%0A self.assertEqual(words.uses_all(%22ababab%22, %22ab%22), True)%0A%0A def test_is_abecedarian(self):%0A self.assertEqual(words.is_abecedarian(%22abcxyz%22), True)%0A self.assertEqual(words.is_abecedarian(%22abczyx%22), False)%0A
|
|
6b92d9fe24fe682c357e3f5a5e6c19f1569bd29e
|
Add riak backend
|
nydus/db/backends/riak.py
|
nydus/db/backends/riak.py
|
Python
| 0
|
@@ -0,0 +1,1178 @@
+%22%22%22%0Anydus.db.backends.riak%0A~~~~~~~~~~~~~~~~~~~~~~%0A%0A:copyright: (c) 2011 DISQUS.%0A:license: Apache License 2.0, see LICENSE for more details.%0A%22%22%22%0A%0Afrom __future__ import absolute_import%0A%0Aimport socket%0Aimport httplib%0A%0Afrom riak import RiakClient, RiakError%0A%0Afrom nydus.db.backends import BaseConnection%0A%0A%0Aclass Riak(BaseConnection):%0A # Exceptions that can be retried by this backend%0A retryable_exceptions = frozenset(%5Bsocket.error, httplib.HTTPException, RiakError%5D)%0A supports_pipelines = False%0A%0A def __init__(self, host='127.0.0.1', port=8098, prefix='riak', mapred_prefix='mapred', client_id=None, **options):%0A self.host = host%0A self.port = port%0A self.prefix = prefix%0A self.mapred_prefix = mapred_prefix%0A self.client_id = client_id%0A super(Riak, self).__init__(**options)%0A%0A @property%0A def identifier(self):%0A mapping = vars(self)%0A return %22http://%25(host)s:%25(port)s/%25(prefix)s%22 %25 mapping%0A%0A def connect(self):%0A return RiakClient(host=self.host, port=self.port, prefix=self.prefix,%5C%0A mapred_prefix=self.mapred_prefix, client_id=self.client_id)%0A%0A def disconnect(self):%0A pass%0A%0A
|
|
7e7d85c7e7bbd79f7bc04d2660e1e1fd30422765
|
add section property to proposalbase
|
symposion/proposals/models.py
|
symposion/proposals/models.py
|
import datetime
import os
import uuid
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
import reversion
from markitup.fields import MarkupField
from model_utils.managers import InheritanceManager
from symposion.conference.models import Section
class ProposalSection(models.Model):
"""
configuration of proposal submissions for a specific Section.
a section is available for proposals iff:
* it is after start (if there is one) and
* it is before end (if there is one) and
* closed is NULL or False
"""
section = models.OneToOneField(Section)
start = models.DateTimeField(null=True, blank=True)
end = models.DateTimeField(null=True, blank=True)
closed = models.NullBooleanField()
published = models.NullBooleanField()
@classmethod
def available(cls):
now = datetime.datetime.now()
return cls._default_manager.filter(
Q(start__lt=now) | Q(start=None),
Q(end__gt=now) | Q(end=None),
Q(closed=False) | Q(closed=None),
)
def is_available(self):
if self.closed:
return False
now = datetime.datetime.now()
if self.start and self.start > now:
return False
if self.end and self.end < now:
return False
return True
def __unicode__(self):
return self.section.name
class ProposalKind(models.Model):
"""
e.g. talk vs panel vs tutorial vs poster
Note that if you have different deadlines, reviewers, etc. you'll want
to distinguish the section as well as the kind.
"""
section = models.ForeignKey(Section, related_name="proposal_kinds")
name = models.CharField(_("Name"), max_length=100)
slug = models.SlugField()
def __unicode__(self):
return self.name
class ProposalBase(models.Model):
objects = InheritanceManager()
kind = models.ForeignKey(ProposalKind)
title = models.CharField(max_length=100)
description = models.TextField(
_("Brief Outline"),
max_length=400, # @@@ need to enforce 400 in UI
help_text="If your talk is accepted this will be made public and printed in the program. Should be one paragraph, maximum 400 characters."
)
abstract = MarkupField(
_("Detailed Abstract"),
help_text=_("Detailed description and outline. Will be made public if your talk is accepted. Edit using <a href='http://daringfireball.net/projects/markdown/basics' target='_blank'>Markdown</a>.")
)
additional_notes = MarkupField(
blank=True,
help_text=_("Anything else you'd like the program committee to know when making their selection: your past speaking experience, open source community experience, etc. Edit using <a href='http://daringfireball.net/projects/markdown/basics' target='_blank'>Markdown</a>.")
)
submitted = models.DateTimeField(
default=datetime.datetime.now,
editable=False,
)
speaker = models.ForeignKey("speakers.Speaker", related_name="proposals")
additional_speakers = models.ManyToManyField("speakers.Speaker", through="AdditionalSpeaker", blank=True)
cancelled = models.BooleanField(default=False)
def can_edit(self):
return True
@property
def speaker_email(self):
return self.speaker.email
@property
def number(self):
return str(self.pk).zfill(3)
def speakers(self):
yield self.speaker
for speaker in self.additional_speakers.exclude(additionalspeaker__status=AdditionalSpeaker.SPEAKING_STATUS_DECLINED):
yield speaker
reversion.register(ProposalBase)
class AdditionalSpeaker(models.Model):
SPEAKING_STATUS_PENDING = 1
SPEAKING_STATUS_ACCEPTED = 2
SPEAKING_STATUS_DECLINED = 3
SPEAKING_STATUS = [
(SPEAKING_STATUS_PENDING, _("Pending")),
(SPEAKING_STATUS_ACCEPTED, _("Accepted")),
(SPEAKING_STATUS_DECLINED, _("Declined")),
]
speaker = models.ForeignKey("speakers.Speaker")
proposalbase = models.ForeignKey(ProposalBase)
status = models.IntegerField(choices=SPEAKING_STATUS, default=SPEAKING_STATUS_PENDING)
class Meta:
db_table = "proposals_proposalbase_additional_speakers"
unique_together = ("speaker", "proposalbase")
def uuid_filename(instance, filename):
ext = filename.split(".")[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join("document", filename)
class SupportingDocument(models.Model):
proposal = models.ForeignKey(ProposalBase, related_name="supporting_documents")
uploaded_by = models.ForeignKey(User)
created_at = models.DateTimeField(default=datetime.datetime.now)
file = models.FileField(upload_to=uuid_filename)
description = models.CharField(max_length=140)
def download_url(self):
return reverse("proposal_document_download", args=[self.pk, os.path.basename(self.file.name).lower()])
|
Python
| 0
|
@@ -3473,32 +3473,107 @@
%0A @property%0A
+ def section(self):%0A return self.kind.section%0A %0A @property%0A
def speaker_
|
6b630687336de18bb0c9179b7002d310772b6871
|
Add corpwiki/iptool
|
tools/check_nameserver_popularity.py
|
tools/check_nameserver_popularity.py
|
#!/usr/bin/env python
import os
import sys
import pickle
import time
import traceback
import yahoo.search
from yahoo.search.web import WebSearch
APP_ID = 'P5ihFKzV34G69QolFfb3nN7p0rSsYfC9tPGq.IUS.NLWEeJ14SG9Lei0rwFtgwL8cDBrA6Egdw--'
QUERY_MODIFIERS = '-site:txdns.net -site:sitedossier.com -mx -site:dataopedia.com -site:l0t3k.net -syslog -"4.2.2.1" -site:cqcounter.com -site:flow.nttu.edu.tw -site:websiteoutlook.com -site:ipgeolocator.com -site:tdyndns.org -site:ebrara.com -site:onsamehost.com -site:ipaddresscentral.com -site:quia.jp -inetnum -site:domaintools.com -site:domainbyip.com -site:pdos.csail.mit.edu -statistics -"country name" -"Q_RTT" -site:botsvsbrowsers.com -"ptr record" -site:ip-db.com -site:chaip.com.cn -site:lookup365.com -"IP Country" -site:iptoolboxes.com -"Unknown Country" -"Q_RTT" -amerika -whois -Mozilla -site:domaincrawler.com -site:geek-tools.org -site:visualware.com -site:robtex.com -site:domaintool.se -site:opendns.se -site:ungefiltert-surfen.de -site:datakitteh.org -"SLOVAKIA (SK)" -"IP Search" -site:www.medicore.com.ua -site:dig.similarbase.com -site:ipcorporationwiki.com -site:coolwhois.com'
CACHE_DIR = os.getenv('HOME') + '/.ycache'
def CheckPopularity(ip):
cache_path = os.path.join(CACHE_DIR, ip) + '.pickle'
if os.path.exists(cache_path):
f = open(cache_path)
return pickle.load(f)
else:
try:
query = '"%s" %s' % (ip, QUERY_MODIFIERS)
srch = WebSearch(APP_ID, query=query, results=50)
results = srch.parse_results()
pf = open(cache_path + '.pickle', 'w')
pickle.dump(results.results, pf)
pf.close()
return results
except yahoo.search.SearchError:
print "%s failed" % (ip)
return []
if __name__ == "__main__":
for ip in sys.argv[1:]:
print '%s = %s' % (ip, total)
for result in results.results:
try:
print ' - %s: %s' % (result['Url'], result['Title'])
except UnicodeEncodeError:
print ' - %s' % result['Url']# print results.results
time.sleep(0.5)
|
Python
| 0
|
@@ -1129,16 +1129,58 @@
hois.com
+ -site:corporationwiki.com -site:iptool.us
'%0ACACHE_
|
dc15986b0ff890250d21a36350b689809d535f44
|
Create KMP.py
|
KMP.py
|
KMP.py
|
Python
| 0
|
@@ -0,0 +1,2428 @@
+# Github username : yatingupta10%0A# Website : http://www.yatingupta.me/%0A%0A# Find occurrences of pattern as a contiguous subsequence of the text.%0A# For the KMP versions the pattern must be a list or string, because we%0A# perform array indexing into it, but the text can be anything that can%0A# be used in a for-loop. The naive match shown first requires the text%0A# to be a list or string as well.%0A%0Afrom __future__ import generators%0A%0A# Naive algorithm to find and return starting position of first match%0A# takes O(p*t) time e.g. for pattern='a'*(p-1)+'b', text='a'*t%0Adef naiveMatch(pattern, text):%0A%09for startPos in range(len(text) - len(pattern) + 1):%0A%09%09matchLen = 0%0A%09%09while pattern%5BmatchLen%5D == text%5BstartPos + matchLen%5D:%0A%09%09%09matchLen += 1%0A%09%09%09if matchLen == len(pattern):%0A%09%09%09%09return startPos%0A%09%0A# Find and return starting position of first match, or None if no match exists%0A#%0A# Time analysis:%0A# each iteration of the inner or outer loops increases 2*startPos + matchLen%0A# this quantity starts at 0 and ends at most at 2*t+p%0A# so the total number of iterations of both loops is O(t+p)%0A#%0Adef kmpFirstMatch(pattern, text):%0A%09shift = computeShifts(pattern)%0A%09startPos = 0%0A%09matchLen = 0%0A%09for c in text:%0A%09%09while matchLen %3E= 0 and pattern%5BmatchLen%5D != c:%0A%09%09%09startPos += shift%5BmatchLen%5D%0A%09%09%09matchLen -= shift%5BmatchLen%5D%0A%09%09matchLen += 1%0A%09%09if matchLen == len(pattern):%0A%09%09%09return startPos%0A%0A# Slightly more complicated version to return sequence of all matches%0A# using Python 2.2 generators (yield keyword in place of return).%0A# Same time analysis as kmpFirstMatch.%0Adef kmpAllMatches(pattern, text):%0A%09shift = computeShifts(pattern)%0A%09startPos = 0%0A%09matchLen = 0%0A%09for c in text:%0A%09%09while matchLen %3E= 0 and pattern%5BmatchLen%5D != c:%0A%09%09%09startPos += shift%5BmatchLen%5D%0A%09%09%09matchLen -= shift%5BmatchLen%5D%0A%09%09matchLen += 1%0A%09%09if matchLen == len(pattern):%0A%09%09%09yield startPos%0A%09%09%09startPos += shift%5BmatchLen%5D%0A%09%09%09matchLen -= shift%5BmatchLen%5D%0A%0A# Construct shift table used in KMP matching%0A# Time analysis: each iteration of either loop increases shift+pos%0A# This quantity starts at 0 and ends at most at 2*p%0A# So total time is O(p).%0A#%0Adef computeShifts(pattern):%0A%09shifts = %5BNone%5D * (len(pattern) + 1)%0A%09shift = 1%0A%09for pos in range(len(pattern) + 1):%0A%09%09while shift %3C pos and pattern%5Bpos-1%5D != pattern%5Bpos-shift-1%5D:%0A%09%09%09shift += shifts%5Bpos-shift-1%5D%0A%09%09shifts%5Bpos%5D = shift%0A%09return shifts%0A%09%0Aif __name__ == %22__main__%22:%0A n = raw_input(%22Enter the text: %22)%0A print (computeShifts(n))%0A
|
|
51642c95ce9d7c7d95648952340d90f4ef2254f3
|
Add test for record_panel
|
opal/tests/test_panels.py
|
opal/tests/test_panels.py
|
Python
| 0
|
@@ -0,0 +1,669 @@
+%22%22%22%0ATests create_singletons command%0A%22%22%22%0Afrom opal.core.test import OpalTestCase%0A%0Afrom opal.templatetags import panels%0A%0Afrom opal.tests.models import Demographics%0A%0Aclass RecordPanelTestCase(OpalTestCase):%0A def test_record_panel(self):%0A expected = dict(%0A name='demographics',%0A singleton=True,%0A title='Demographics',%0A detail_template='records/demographics.html',%0A icon=None,%0A editable=1,%0A angular_filter=None,%0A noentries=None,%0A only_display_if_exists=False%0A )%0A result = panels.record_panel(Demographics())%0A self.assertEqual(expected, result)%0A
|
|
d9959b9a8e38fc5c6b23618fdbd8a67423302e4e
|
include forgotten exceptions.py file
|
ddsc/exceptions.py
|
ddsc/exceptions.py
|
Python
| 0
|
@@ -0,0 +1,145 @@
+class DDSUserException(Exception):%0A %22%22%22%0A Exception with an error message to be displayed to the user on the command line.%0A %22%22%22%0A pass%0A
|
|
45215b36e544f8d7a9ac21a825807d6e49d2ade9
|
Add binarySearch function
|
DataStructuresAndAlgorithmsInPython/BinarySearch.py
|
DataStructuresAndAlgorithmsInPython/BinarySearch.py
|
Python
| 0.000002
|
@@ -0,0 +1,1072 @@
+##-*- coding: utf-8 -*- %0A#!/usr/bin/python%0A%22%22%22 Returns either the index of the location in the array,%0A or -1 if the array did not contain the targetValue%0A%22%22%22%0Aimport math%0A%0A%0Adef binarySearch (array, targetValue):%0A minimum = 0;%0A maximum = len(array) - 1;%0A guess = -1;%0A guessesCount = 0;%0A %0A while (maximum %3E= minimum):%0A guessesCount += 1;%0A guess = int(math.floor((minimum + maximum) / 2));%0A print %22A number of guess: %22 + str(guess);%0A %0A if (array%5Bguess%5D == targetValue):%0A print %22Total number of guesses: %22 + str(guessesCount);%0A return guess; %0A elif (array%5Bguess%5D %3C targetValue):%0A minimum = guess + 1;%0A else:%0A maximum = guess - 1;%0A%0A return -1;%0A%0Aprimes = %5B2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, %0A 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97%5D;%0A%0Aresult = binarySearch(primes, 73);%0Aprint %22Found prime at index %22 + str(result);%0A%0Aassert (binarySearch(primes, 7) is 3)%0Aassert (binarySearch(primes, 13) is 5)%0Aassert (binarySearch(primes, 73) is 20)
|
|
1d2fea42ae0e749aa2f262d8397c978c84b5d7c5
|
Version can be printed by executing python module dictorm.version
|
dictorm/version.py
|
dictorm/version.py
|
Python
| 0.000003
|
@@ -0,0 +1,53 @@
+from .dictorm import __version__%0A%0Aprint(__version__)%0A
|
|
0e43fce67c2c53fe2a7dbf233df86c042501e477
|
Move explain_sam_flags.py to public repository
|
src/scripts/explain_sam_flags.py
|
src/scripts/explain_sam_flags.py
|
Python
| 0.000001
|
@@ -0,0 +1,1341 @@
+#!/usr/bin/env python%0A# The Broad Institute%0A# SOFTWARE COPYRIGHT NOTICE AGREEMENT%0A# This software and its documentation are copyright 2008 by the%0A# Broad Institute/Massachusetts Institute of Technology. All rights are%0A# reserved.%0A%0A# This software is supplied without any warranty or guaranteed support%0A# whatsoever. Neither the Broad Institute nor MIT can be responsible for its%0A# use, misuse, or functionality.%0A# $Header$%0A%22%22%22usage %25prog decimal-flag %5Bdecimal-flag...%5D%0A%0AExplain each flag on the command line in plain English%0A%22%22%22%0A%0Afrom __future__ import division%0Aimport sys%0A%0AlstFlags = %5B%0A (%22read paired%22, 0x1),%0A (%22read mapped in proper pair%22, 0x2),%0A (%22read unmapped%22, 0x4),%0A (%22mate unmapped%22, 0x8),%0A (%22read reverse strand%22, 0x10),%0A (%22mate reverse strand%22, 0x20),%0A (%22first in pair%22, 0x40),%0A (%22second in pair%22, 0x80),%0A (%22not primary alignment%22, 0x100),%0A (%22read fails platform/vendor quality checks%22, 0x200),%0A (%22read is PCR or optical duplicate%22, 0x400)%0A %5D%0A %0A%0Adef explain_sam_flags(iFlags):%0A print iFlags, %22:%22%0A for strFlagName, iMask in lstFlags:%0A if iFlags & iMask:%0A print %22%5Ct%22 + strFlagName%0A%0Adef main(argv=None):%0A if argv is None:%0A argv = sys.argv%0A%0A for strArg in argv%5B1:%5D:%0A explain_sam_flags(int(strArg))%0A%0Aif __name__ == %22__main__%22:%0A sys.exit(main())%0A %0A
|
|
5352740a1cc508a6b902f447a80960fa237414aa
|
Add ProgressPathView
|
ui2/view_classes/ProgressPathView.py
|
ui2/view_classes/ProgressPathView.py
|
Python
| 0
|
@@ -0,0 +1,2018 @@
+from objc_util import *%0Aimport ui%0A%0A%0Adef _get_CGColor(color):%0A %22%22%22Get a CGColor from a wide range of formats.%22%22%22%0A return UIColor.colorWithRed_green_blue_alpha_(%0A *ui.parse_color(color)%0A ).CGColor()%0A%0A%0Aclass ProgressPathView(ui.View):%0A %22%22%22A view class which can turn a ui.Path into a progress bar.%0A %0A This allows you not only to create linear and circular progress bars, but%0A to create progress bars of any shape %22%22%22%0A def __init__(self, path, width=5, color=%22#21abed%22):%0A self._objc = ObjCInstance(self)%0A # Set up the layer on which the path is rendered%0A self._layer = ObjCClass(%22CAShapeLayer%22).new()%0A self._layer.setPath_(ObjCInstance(path).CGPath())%0A self._objc.layer().addSublayer_(self._layer)%0A%0A self._layer.setFillColor_(UIColor.clearColor().CGColor()) # No fill%0A self.tint_color = color%0A%0A self.stroke_width = width%0A self.progress = 0 # Progress starts at 0%0A %0A @property%0A def progress(self):%0A return self._layer.strokeEnd()%0A %0A @progress.setter%0A def progress(self, value):%0A self._layer.setStrokeEnd_(value)%0A%0A @property%0A def stroke_width(self):%0A return self._layer.lineWidth()%0A %0A @stroke_width.setter%0A def stroke_width(self, width):%0A self._layer.setLineWidth_(width)%0A %0A @property%0A def tint_color(self):%0A color = UIColor.colorWithCGColor_(self._layer.strokeColor())%0A return color.red(), color.green(), color.blue(), color.alpha()%0A %0A @tint_color.setter%0A def tint_color(self, color):%0A self._layer.setStrokeColor_(_get_CGColor(color))%0A%0A%0Aif __name__ == %22__main__%22:%0A p = ui.Path()%0A p.move_to(10, 10)%0A p.line_to(50, 10)%0A p.line_to(50, 50)%0A p.close()%0A %0A a = ProgressPathView(p)%0A b = ui.View()%0A b.add_subview(a)%0A%0A b.present(%22sheet%22)%0A %0A a.progress = 0.1%0A def advance():%0A a.progress = 0.7%0A ui.delay(advance, 0.75)%0A def advance2():%0A a.progress = 1%0A ui.delay(advance2, 1.5)%0A
|
|
0611c6f471c730d9f013c776389ae129a11e16e3
|
Rewrite brackets logic to not use while loop
|
editorconfig/fnmatch.py
|
editorconfig/fnmatch.py
|
"""Filename matching with shell patterns.
fnmatch(FILENAME, PATTERN) matches according to the local convention.
fnmatchcase(FILENAME, PATTERN) always takes case in account.
The functions operate by translating the pattern into a regular
expression. They cache the compiled regular expressions for speed.
The function translate(PATTERN) returns a regular expression
corresponding to PATTERN. (It does not compile it.)
Based on code from fnmatch.py file distributed with Python 2.6.
Licensed under PSF License (see LICENSE.txt file).
Changes to original fnmatch module:
- translate function supports ``*`` and ``**`` similarly to fnmatch C library
"""
import os
import re
__all__ = ["fnmatch", "fnmatchcase", "translate"]
_cache = {}
_brace1 = re.compile(r'(?:^|[^\\])\{')
_brace2 = re.compile(r'(?:^|[^\\])\}')
def fnmatch(name, pat):
"""Test whether FILENAME matches PATTERN.
Patterns are Unix shell style:
- ``*`` matches everything except path separator
- ``**`` matches everything
- ``?`` matches any single character
- ``[seq]`` matches any character in seq
- ``[!seq]`` matches any char not in seq
- ``{s1,s2,s3}`` matches any of the strings given (separated by commas)
An initial period in FILENAME is not special.
Both FILENAME and PATTERN are first case-normalized
if the operating system requires it.
If you don't want this, use fnmatchcase(FILENAME, PATTERN).
"""
name = os.path.normpath(name).replace(os.sep, "/")
return fnmatchcase(name, pat)
def fnmatchcase(name, pat):
"""Test whether FILENAME matches PATTERN, including case.
This is a version of fnmatch() which doesn't case-normalize
its arguments.
"""
if not pat in _cache:
res = translate(pat)
_cache[pat] = re.compile(res)
return _cache[pat].match(name) is not None
def translate(pat, nested=False):
"""Translate a shell PATTERN to a regular expression.
There is no way to quote meta-characters.
"""
i, n = 0, len(pat)
brace_level = 0
res = ''
escaped = False
matching_braces = len(_brace1.findall(pat)) == len(_brace2.findall(pat))
while i < n:
c = pat[i]
i = i + 1
if c == '*':
j = i
if j < n and pat[j] == '*':
res = res + '.*'
else:
res = res + '[^/]*'
elif c == '?':
res = res + '.'
elif c == '[':
j = i
if j < n and pat[j] == '!':
j = j + 1
if j < n and pat[j] == ']':
j = j + 1
while j < n and (pat[j] != ']' or escaped):
escaped = pat[j] == '\\' and not escaped
j = j + 1
if j >= n:
res += res + '\\['
else:
stuff = pat[i:j]
i = j + 1
if stuff[0] == '!':
stuff = '^' + stuff[1:]
elif stuff[0] == '^':
stuff = '\\' + stuff
res = '%s[%s]' % (res, stuff)
elif c == '{':
j = i
has_comma = False
while j < n and (pat[j] != '}' or escaped):
if pat[j] == ',' and not escaped:
has_comma = True
break
escaped = pat[j] == '\\' and not escaped
j = j + 1
if not has_comma and j < n:
res = '%s\\{%s\\}' % (res, translate(pat[i:j], nested=True))
i = j + 1
elif matching_braces:
res = res + '(?:'
brace_level += 1
else:
res = res + '\\{'
elif c == ',':
if brace_level > 0 and not escaped:
res = res + '|'
else:
res = res + '\\,'
elif c == '}':
if brace_level > 0 and not escaped:
res = res + ')'
brace_level -= 1
else:
res = res + '\\}'
elif c != '\\':
res = res + re.escape(c)
if c == '\\':
if escaped:
res = res + re.escape(c)
escaped = not escaped
else:
escaped = False
if nested:
return res
else:
return res + '\Z(?ms)'
|
Python
| 0.000006
|
@@ -2097,16 +2097,40 @@
vel = 0%0A
+ in_brackets = False%0A
res
@@ -2541,52 +2541,22 @@
-j = i%0A if j %3C n and pat%5Bj%5D == '!'
+if in_brackets
:%0A
@@ -2565,33 +2565,41 @@
-j = j + 1
+res = res + '%5C%5C%5B'
%0A
@@ -2591,36 +2591,38 @@
%5C%5B'%0A
+el
if
-j
+i
%3C n and pat%5Bj%5D
@@ -2622,16 +2622,17 @@
pat%5B
-j%5D == '%5D
+i%5D in '!%5E
':%0A
@@ -2638,37 +2638,37 @@
-j = j
+i = i
+ 1%0A
@@ -2672,156 +2672,45 @@
-while j %3C n and (pat%5Bj%5D != '%5D' or escaped):%0A escaped = pat%5Bj%5D == '%5C%5C' and not escaped%0A j = j + 1%0A if j %3E= n
+ res = res + '%5B%5E'%0A else
:%0A
@@ -2727,17 +2727,16 @@
res
-+
= res +
@@ -2728,34 +2728,32 @@
res = res + '
-%5C%5C
%5B'%0A e
@@ -2755,277 +2755,163 @@
-else:%0A stuff = pat%5Bi:j%5D%0A i = j + 1%0A if stuff%5B0%5D == '!':%0A stuff = '%5E' + stuff%5B1:%5D%0A elif stuff%5B0%5D == '%5E':%0A stuff = '%5C%5C' + stuff%0A
+in_brackets = True%0A elif c in '-%5D':%0A if in_brackets:%0A res = res + c%0A else:%0A res =
res
-= '%25s%5B%25s%5D' %25 (res, stuff)
++ '%5C%5C' + c
%0A
|
8738accb2a612a3c1e41cc00aa337d0be890f4a0
|
add problem 052
|
problem_052.py
|
problem_052.py
|
Python
| 0.001304
|
@@ -0,0 +1,419 @@
+#!/usr/bin/env python%0A#-*-coding:utf-8-*-%0A%0A'''%0A%0A'''%0A%0Aimport timeit%0A%0A%0Adef loop(n):%0A for i in range(10, 10000000):%0A if str(i)%5B0%5D != '1':%0A continue%0A f = %5B1 for j in range(2, n+1) if sorted(list(str(i))) != sorted(str(i*j))%5D%0A if len(f) == 0:%0A return i%0A%0A%0Aif __name__ == '__main__':%0A print loop(6)%0A print timeit.Timer('problem_052.loop(6)', 'import problem_052').timeit(1)%0A
|
|
88f0e5ba8a404f0fcdaaaacc69109775182b7213
|
Add squashed migrations
|
dj_experiment/migrations/0002_auto_20170802_1206_squashed_0004_auto_20170802_1230.py
|
dj_experiment/migrations/0002_auto_20170802_1206_squashed_0004_auto_20170802_1230.py
|
Python
| 0.000001
|
@@ -0,0 +1,1612 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.3 on 2017-08-02 17:31%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0Aimport django.db.models.deletion%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A replaces = %5B('dj_experiment', '0002_auto_20170802_1206'), ('dj_experiment', '0003_auto_20170802_1708'), ('dj_experiment', '0004_auto_20170802_1230')%5D%0A%0A dependencies = %5B%0A ('dj_experiment', '0001_initial_squashed_0006_auto_20170802_0904'),%0A %5D%0A%0A operations = %5B%0A migrations.RemoveField(%0A model_name='catalog',%0A name='xperiment',%0A ),%0A migrations.AddField(%0A model_name='catalog',%0A name='xperiments',%0A field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, related_name='catalogs', to='dj_experiment.Experiment'),%0A preserve_default=False,%0A ),%0A migrations.AlterField(%0A model_name='experiment',%0A name='data_dir',%0A field=models.CharField(default='./', max_length=250),%0A ),%0A migrations.AlterField(%0A model_name='experiment',%0A name='separator',%0A field=models.CharField(default='.', max_length=1),%0A ),%0A migrations.AlterField(%0A model_name='experiment',%0A name='data_dir',%0A field=models.CharField(default=b'RCM data', max_length=250),%0A ),%0A migrations.AlterField(%0A model_name='experiment',%0A name='separator',%0A field=models.CharField(default=b'_', max_length=1),%0A ),%0A %5D%0A
|
|
26eba1f16c44ed6693b2a575a6a2c5ebef9401b5
|
Create Movie object city_lights
|
entertainment_center.py
|
entertainment_center.py
|
Python
| 0.999489
|
@@ -0,0 +1,1279 @@
+# entertainment_center.py%0Aimport media%0A%0A__author__ = 'vishal lama'%0A%0Acity_lights = media.Movie(%0A %22City Lights%22,%0A %22A tramp falls in love with a beautiful blind girl. Her family is in %22%0A %22financial trouble. The tramp's on-and-off friendship with a wealthy %22%0A %22man allows him to be the girl's benefactor and suitor.%22,%0A %22https://upload.wikimedia.org/wikipedia/en/f/f2/City_Lights_film.jpg%22,%0A %22https://www.youtube.com/watch?v=b2NTUnujk1I%22,%0A %5B%22Charles Chaplin%22, %22Virginia Cherrill%22,%0A %22Florence Lee%22, %22Harry Myers%22,%0A %22Al Ernest Garcia%22, %22Hank Mann%22%0A %5D,%0A %227 March 1931%22,%0A %22G%22,%0A %22English%22,%0A %2287 min%22,%0A %22Charles Chaplin Productions%22,%0A %5B%22When the film opened on 31 January 1931, Albert Einstein joined %22%0A %22Charles Chaplin at the theater. When the film opened in England, %22%0A %22George Bernard Shaw joined him.%22,%0A %22Charles Chaplin's personal favorite of all his films.%22,%0A %22Russian director Andrei Tarkovsky cited this as his favorite film. %22%0A %22Woody Allen also calls it 'Chaplin's best picture'.%22,%0A %22In 2008, this film was voted #1 on AFI's list over the ten best %22%0A %22romantic comedies of all time.%22,%0A %22Virginia Cherrill was cast on a whim when Charles Chaplin spotted %22%0A %22her at a boxing match.%22%0A %5D%0A )%0A
|
|
714537e1cff4009a5e8ba93da94954b84536127a
|
Add Teli API
|
api.py
|
api.py
|
Python
| 0
|
@@ -0,0 +1,825 @@
+import requests%0A%0Aclass Teli:%0A TOKEN = %22%22%0A API = %22%22%0A%0A def __init__(self, TOKEN):%0A self.TOKEN = TOKEN%0A self.API = %22https://sms.teleapi.net/%7B%7D/send%22%0A%0A def send_sms(self, src, dest, message):%0A args = %7B%0A 'token': self.TOKEN,%0A 'source': src,%0A 'destination': dest,%0A 'message': message%0A %7D%0A return requests.post(self.API.format(%22sms%22), data=args).status_code%0A%0A def send_mms(self, src, dest, file_name=None, file_data=None, file_url=None):%0A args = %7B%0A 'token': self.TOKEN,%0A 'source': src,%0A 'destination': dest,%0A 'file_name': file_name,%0A 'file_data': file_data,%0A 'file_url': file_url%0A %7D%0A return requests.post(self.API.format(%22mms%22), data=args).status_code%0A
|
|
c4b2f86f5ae49b75dc47c8ced799d647d3bc70e1
|
fix transport location
|
src/collectors/elasticsearch/elasticsearch.py
|
src/collectors/elasticsearch/elasticsearch.py
|
# coding=utf-8
"""
Collect the elasticsearch stats for the local node
#### Dependencies
* urlib2
"""
import urllib2
try:
import json
json # workaround for pyflakes issue #13
except ImportError:
import simplejson as json
import diamond.collector
class ElasticSearchCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(ElasticSearchCollector,
self).get_default_config_help()
config_help.update({
'host': "",
'port': "",
})
return config_help
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(ElasticSearchCollector, self).get_default_config()
config.update({
'host': '127.0.0.1',
'port': 9200,
'path': 'elasticsearch',
})
return config
def collect(self):
if json is None:
self.log.error('Unable to import json')
return {}
url = 'http://%s:%i/_cluster/nodes/_local/stats?all=true' % (
self.config['host'], int(self.config['port']))
try:
response = urllib2.urlopen(url)
except urllib2.HTTPError, err:
self.log.error("%s: %s", url, err)
return
try:
result = json.load(response)
except (TypeError, ValueError):
self.log.error("Unable to parse response from elasticsearch as a"
+ " json object")
return
metrics = {}
node = result['nodes'].keys()[0]
data = result['nodes'][node]
#
# http connections to ES
metrics['http.current'] = data['http']['current_open']
#
# indices
indices = data['indices']
metrics['indices.docs.count'] = indices['docs']['count']
metrics['indices.docs.deleted'] = indices['docs']['deleted']
metrics['indices.datastore.size'] = indices['store']['size_in_bytes']
transport = indices['transport']
metrics['transport.rx.count'] = transport['rx_count']
metrics['transport.rx.size'] = transport['rx_size_in_bytes']
metrics['transport.tx.count'] = transport['tx_count']
metrics['transport.tx.size'] = transport['tx_size_in_bytes']
cache = indices['cache']
metrics['cache.bloom.size'] = cache['bloom_size_in_bytes']
metrics['cache.field.evictions'] = cache['field_evictions']
metrics['cache.field.size'] = cache['field_size_in_bytes']
metrics['cache.filter.count'] = cache['filter_count']
metrics['cache.filter.evictions'] = cache['filter_evictions']
metrics['cache.filter.size'] = cache['filter_size_in_bytes']
metrics['cache.id.size'] = cache['id_cache_size_in_bytes']
#
# process mem/cpu
process = data['process']
mem = process['mem']
metrics['process.cpu.percent'] = process['cpu']['percent']
metrics['process.mem.resident'] = mem['resident_in_bytes']
metrics['process.mem.share'] = mem['share_in_bytes']
metrics['process.mem.virtual'] = mem['total_virtual_in_bytes']
#
# filesystem
fs_data = data['fs']['data'][0]
metrics['disk.reads.count'] = fs_data['disk_reads']
metrics['disk.reads.size'] = fs_data['disk_read_size_in_bytes']
metrics['disk.writes.count'] = fs_data['disk_writes']
metrics['disk.writes.size'] = fs_data['disk_write_size_in_bytes']
for key in metrics:
self.publish(key, metrics[key])
|
Python
| 0.000006
|
@@ -2087,23 +2087,20 @@
sport =
-indices
+data
%5B'transp
|
8bdf94c29418a3826e5c6fd3a76f96051326bfe6
|
Add management command extract votes #126
|
datasets/management/commands/extract_votes.py
|
datasets/management/commands/extract_votes.py
|
Python
| 0
|
@@ -0,0 +1,2051 @@
+from django.core.management.base import BaseCommand%0Aimport json%0Afrom datasets.models import CandidateAnnotation, Vote, TaxonomyNode, Dataset%0A%0A%0Aclass Command(BaseCommand):%0A help = 'Extract user votes' %5C%0A 'Usage: python manage.py extract_votes %3Cdataset_shor_name%3E %3Coutput_file%3E'%0A%0A def add_arguments(self, parser):%0A parser.add_argument('dataset_short_name', type=str)%0A parser.add_argument('output_file', type=str)%0A%0A def handle(self, *args, **options):%0A dataset_short_name = options%5B'dataset_short_name'%5D%0A output_file = options%5B'output_file'%5D%0A%0A dataset = Dataset.objects.get(short_name=dataset_short_name)%0A nodes = TaxonomyNode.objects.all()%0A votes_dict = %7Bnode_id: %7B'PP': list(),%0A 'PNP': list(),%0A 'NP': list(),%0A 'U': list(),%0A 'candidates': list()%7D for node_id in nodes.values_list('node_id', flat=True)%7D%0A vote_value_to_letter = %7B1: 'PP', 0.5: 'PNP', -1: 'NP', 0: 'U'%7D%0A%0A votes_with_info = Vote.objects.filter(candidate_annotation__sound_dataset__dataset=dataset)%5C%0A .values('vote', 'candidate_annotation__taxonomy_node__node_id',%0A 'candidate_annotation__sound_dataset__sound__freesound_id')%0A candidate_annotations = CandidateAnnotation.objects.filter(sound_dataset__dataset=dataset)%5C%0A .values('taxonomy_node__node_id', 'sound_dataset__sound__freesound_id')%0A%0A for vote in votes_with_info:%0A votes_dict%5Bvote%5B'candidate_annotation__taxonomy_node__node_id'%5D%5D%5C%0A %5Bvote_value_to_letter%5Bvote%5B'vote'%5D%5D%5D%5C%0A .append(vote%5B'candidate_annotation__sound_dataset__sound__freesound_id'%5D)%0A%0A for candidate_annotation in candidate_annotations:%0A votes_dict%5Bcandidate_annotation%5B'taxonomy_node__node_id'%5D%5D%5B'candidates'%5D%5C%0A .append(candidate_annotation%5B'sound_dataset__sound__freesound_id'%5D)%0A%0A json.dump(votes_dict, open(output_file, 'w'))%0A
|
|
21e80314c0b1a2b9f3e139520854ce913038dbfb
|
change docstring format
|
src/collectors/processmemory/processmemory.py
|
src/collectors/processmemory/processmemory.py
|
# coding=utf-8
"""
A Diamond collector that collects memory usage of each process defined in it's
config file by matching them with their executable filepath or the process name.
Example config file ProcessMemoryCollector.conf
```
enabled=True
unit=kB
[process]
[[postgres]]
exe=^\/usr\/lib\/postgresql\/+d.+d\/bin\/postgres$
name=^postgres,^pg
```
exe and name are both lists of comma-separated regexps.
"""
import re
import diamond.collector, diamond.convertor
import psutil
class ProcessMemoryCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(ProcessMemoryCollector,
self).get_default_config_help()
config_help.update({
'unit': 'The unit in which memory data is collected.',
'process': ("A subcategory of settings inside of which each "
"collected process has it's configuration")
})
return config_help
def get_default_config(self):
"""
Default settings are:
path: 'memory.process'
unit: 'B'
"""
config = super(ProcessMemoryCollector, self).get_default_config()
config.update({
'path': 'memory.process',
'unit': 'B',
'process': '',
})
return config
def setup_config(self):
"""
prepare self.processes, which is a descriptor dictionary in
processgroup --> {
exe: [regex],
name: [regex],
procs: [psutil.Process]
}
"""
self.processes = {}
for process, cfg in self.config['process'].items():
# first we build a dictionary with the process aliases and the
# matching regexps
exe = cfg.get('exe', [])
if not isinstance(exe, list):
exe = [exe]
exe = [re.compile(e) for e in exe]
name = cfg.get('name', [])
if not isinstance(name, list):
name = [name]
name = [re.compile(n) for n in name]
self.processes[process] = {
'exe': exe,
'name': name,
'procs': []
}
def filter_processes(self):
def process_filter(proc, cfg):
"""
Decides whether a process matches with a given process descriptor
@param proc: a psutil.Process instance
@param cfg: the dictionary from processes that describes with the
process group we're testing for
@return: True|False
"""
for exe in cfg['exe']:
try:
if exe.match(proc.exe):
return True
except psutil.AccessDenied:
break
for name in cfg['name']:
if name.match(proc.name):
return True
return False
for proc in psutil.process_iter():
# filter and divide the system processes amongst the different
# process groups defined in the config file
for procname, cfg in self.processes.items():
if process_filter(proc, cfg):
cfg['procs'].append(proc)
break
def collect(self):
"""
Collects the RSS memory usage of each process defined under the
`process` subsection of the config file
"""
self.setup_config()
self.filter_processes()
unit = self.config['unit']
for process, cfg in self.processes.items():
# finally publish the results for each process group
metric_name = "{}.rss".format(process)
metric_value = diamond.convertor.binary.convert(
sum(p.get_memory_info().rss for p in cfg['procs']),
oldUnit='byte', newUnit=unit)
# Publish Metric
self.publish(metric_name, metric_value)
metric_name = "{}.vms".format(process)
metric_value = diamond.convertor.binary.convert(
sum(p.get_memory_info().vms for p in cfg['procs']),
oldUnit='byte', newUnit=unit)
# Publish Metric
self.publish(metric_name, metric_value)
|
Python
| 0.000001
|
@@ -2260,32 +2260,175 @@
rocesses(self):%0A
+ %22%22%22%0A Populates self.processes%5Bprocessname%5D%5B'procs'%5D with the corresponding%0A list of psutil.Process instances%0A %22%22%22%0A
def proc
@@ -2553,25 +2553,25 @@
-@
+:
param proc:
@@ -2608,17 +2608,17 @@
-@
+:
param cf
@@ -2738,9 +2738,9 @@
-@
+:
retu
@@ -2751,14 +2751,47 @@
True
-%7CFalse
+ if it matches%0A :rtype: bool
%0A
|
80935a126beabf05a4c8d54e9306d2b67995c81a
|
373. Find K Pairs with Smallest Sums. Brute force
|
p373_bruteforce.py
|
p373_bruteforce.py
|
Python
| 0.999931
|
@@ -0,0 +1,928 @@
+import unittest%0A%0A%0Aclass Solution(object):%0A def kSmallestPairs(self, nums1, nums2, k):%0A %22%22%22%0A :type nums1: List%5Bint%5D%0A :type nums2: List%5Bint%5D%0A :type k: int%0A :rtype: List%5BList%5Bint%5D%5D%0A %22%22%22%0A tuples = %5B%5D%0A for i in nums1:%0A for j in nums2:%0A tuples.append(%5Bi, j%5D)%0A%0A tuples.sort(lambda x, y: x%5B0%5D + x%5B1%5D - y%5B0%5D - y%5B1%5D)%0A return tuples%5B0:k%5D%0A%0A%0Aclass Test(unittest.TestCase):%0A def test(self):%0A self._test(%5B1, 7, 11%5D, %5B2, 4, 6%5D, 3,%0A %5B%5B1, 2%5D, %5B1, 4%5D, %5B1, 6%5D%5D)%0A self._test(%5B1, 1, 2%5D, %5B1, 2, 3%5D, 2,%0A %5B%5B1, 1%5D, %5B1, 1%5D%5D)%0A self._test(%5B1, 2%5D, %5B3%5D, 3,%0A %5B%5B1, 3%5D, %5B2, 3%5D%5D)%0A%0A def _test(self, nums1, nums2, k, expected):%0A actual = Solution().kSmallestPairs(nums1, nums2, k)%0A self.assertItemsEqual(actual, expected)%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
|
|
1ede9bd211cd8ea6aac4db6f8818804cb778a022
|
Add a view that serves a single static file
|
dinosaurs/views.py
|
dinosaurs/views.py
|
Python
| 0.000001
|
@@ -0,0 +1,371 @@
+import os%0A%0Aimport tornado.web%0Aimport tornado.ioloop%0A%0A%0Aclass SingleStatic(tornado.web.StaticFileHandler):%0A def initialize(self, path):%0A self.dirname, self.filename = os.path.split(path)%0A super(SingleStatic, self).initialize(self.dirname)%0A%0A def get(self, path=None, include_body=True):%0A super(SingleStatic, self).get(self.filename, include_body)%0A
|
|
3f7a03baad15da817e81a8524b87f32c9ca79c1b
|
Add image service tests
|
memegen/test/test_services_image.py
|
memegen/test/test_services_image.py
|
Python
| 0.000001
|
@@ -0,0 +1,597 @@
+from unittest.mock import Mock%0A%0Aimport pytest%0A%0A%0Aclass TestImageService:%0A%0A def test_find_template(self, image_service):%0A mock_template = Mock()%0A image_service.template_store.read.return_value = mock_template%0A%0A template = image_service.find_template('my_key')%0A%0A assert image_service.template_store.read.called%0A%0A assert template is mock_template%0A%0A def test_find_template_not_found(self, image_service):%0A image_service.template_store.read.return_value = None%0A%0A with pytest.raises(KeyError):%0A image_service.find_template('unknown_key')%0A
|
|
33a439d5b52036bb272c8866017b973bef18237d
|
Create tests.py
|
tests.py
|
tests.py
|
Python
| 0.000001
|
@@ -0,0 +1,5 @@
+#...%0A
|
|
234897a36cdf5a5cf5b7550f6d176f4168d7a6c7
|
add basic test suite
|
tests.py
|
tests.py
|
Python
| 0.000001
|
@@ -0,0 +1,340 @@
+import os%0Aimport app%0Aimport unittest%0A%0A%0Aclass TestCase(unittest.TestCase):%0A%0A def setUp(self):%0A self.%0A self.app = app.app.test_client()%0A%0A def tearDown(self):%0A pass%0A%0A def test_index(self):%0A resp = self.app.get('/')%0A assert 'Hello World!' in resp.data%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
|
|
4d3ed1ff13cde88abe695c724d7c8946578cde21
|
Add py-docopt package (#8236)
|
var/spack/repos/builtin/packages/py-docopt/package.py
|
var/spack/repos/builtin/packages/py-docopt/package.py
|
Python
| 0
|
@@ -0,0 +1,1596 @@
+##############################################################################%0A# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass PyDocopt(PythonPackage):%0A %22%22%22Command-line interface description language.%22%22%22%0A%0A homepage = %22http://docopt.org/%22%0A url = %22https://pypi.io/packages/source/d/docopt/docopt-0.6.2.tar.gz%22%0A%0A import_modules = %5B'docopt'%5D%0A%0A version('0.6.2', '4bc74561b37fad5d3e7d037f82a4c3b1')%0A%0A depends_on('py-setuptools', type='build')%0A
|
|
889b6254526b5b49cd27d2f7bf7603a60f4f64fe
|
Add py-geeadd package (#12366)
|
var/spack/repos/builtin/packages/py-geeadd/package.py
|
var/spack/repos/builtin/packages/py-geeadd/package.py
|
Python
| 0
|
@@ -0,0 +1,1305 @@
+# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass PyGeeadd(PythonPackage):%0A %22%22%22Google Earth Engine Batch Assets Manager with Addons.%22%22%22%0A%0A homepage = %22https://github.com/samapriya/gee_asset_manager_addon%22%0A url = %22https://pypi.io/packages/source/g/geeadd/geeadd-0.3.0.tar.gz%22%0A%0A version('0.3.0', sha256='591e6ff2847122598ed5b0452a892a76e332ce227d4ba75e4d03eca2c7a4beea')%0A%0A depends_on('py-setuptools', type='build')%0A depends_on('py-earthengine-api@0.1.87:', type=('build', 'run'))%0A depends_on('py-requests@2.10.0:', type=('build', 'run'))%0A depends_on('py-poster@0.8.1:', type=('build', 'run'))%0A depends_on('py-retrying@1.3.3:', type=('build', 'run'))%0A depends_on('py-clipboard@0.0.4:', type=('build', 'run'))%0A depends_on('py-beautifulsoup4@4.5.1:', type=('build', 'run'))%0A depends_on('py-requests-toolbelt@0.7.0:', type=('build', 'run'))%0A depends_on('py-pytest@3.0.0:', type=('build', 'test'))%0A depends_on('py-future@0.16.0:', type=('build', 'run'))%0A depends_on('py-google-cloud-storage@1.1.1:', type=('build', 'run'))%0A depends_on('py-oauth2client@4.1.3:', type=('build', 'run'))%0A
|
|
f9b334b4fab221a7452f682a2748fe8b8a00daef
|
Fix decimal generation.
|
mixer/generators.py
|
mixer/generators.py
|
import datetime
import sys
import random
import decimal
from functools import wraps
DEFAULT_STRING_LENGTH = 8
DEFAULT_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' # nolint
def loop(get_func):
""" Make generator from function.
"""
@wraps(get_func)
def wrapper(*args, **kwargs):
while True:
yield get_func(*args, **kwargs)
return wrapper
def get_choice(choices=None, **kwargs):
if choices is None:
return None
return random.choice(choices)
gen_choice = loop(get_choice)
def get_choices(choices=None, length=None, **kwargs):
gen = gen_choice(choices)
if length is None:
length = len(choices)
return tuple(next(gen) for _ in xrange(length))
gen_choices = loop(get_choices)
def get_date(low=(1900, 1, 1), high=(2020, 12, 31), **kwargs):
low = datetime.date(*low)
high = datetime.date(*high)
delta = high - low
delta = datetime.timedelta(
seconds=random.randrange(delta.days * 24 * 60 * 60 + delta.seconds))
return low + delta
gen_date = loop(get_date)
def get_time(low=(0, 0, 0), high=(23, 59, 59), **kwargs):
h = random.randint(low[0], high[0])
m = random.randint(low[1], high[1])
s = random.randint(low[2], high[2])
return datetime.time(h, m, s)
gen_time = loop(get_time)
def get_datetime(low=(1900, 1, 1, 0, 0, 0),
high=(2020, 12, 31, 23, 59, 59), **kwargs):
date = get_date(low[:3], high[:3])
h = random.randint(low[3], high[3])
ms = random.randint(low[4], high[4])
s = random.randint(low[5], high[5])
return datetime.datetime(date.year, date.month, date.day, h, ms, s)
gen_datetime = loop(get_datetime)
def get_integer(low=-2147483647, high=2147483647, **kwargs):
return random.randint(low, high)
gen_integer = loop(get_integer)
def get_big_integer(**kwargs):
return get_integer(low=-9223372036854775808, high=9223372036854775807)
gen_big_integer = loop(get_big_integer)
def get_small_integer(**kwargs):
return get_integer(low=-32768, high=32768)
gen_small_integer = loop(get_small_integer)
def get_positive_integer(high=4294967294, **kwargs):
return get_integer(low=0, high=high)
gen_positive_integer = loop(get_positive_integer)
def get_small_positive_integer(**kwargs):
return get_integer(low=0, high=65536)
gen_small_positive_integer = loop(get_small_positive_integer)
def get_float(**kwargs):
return random.uniform(sys.float_info.min, sys.float_info.max)
gen_float = loop(get_float)
def get_boolean(**kwargs):
return get_choice((True, False))
gen_boolean = loop(get_boolean)
def get_null_or_boolean(**kwargs):
return get_choice((True, False, None))
gen_null_or_boolean = loop(get_null_or_boolean)
def get_string(length=DEFAULT_STRING_LENGTH, chars=DEFAULT_CHARS, **kwargs):
return ''.join(get_choices(chars, length))
gen_string = loop(get_string)
def get_decimal(i=4, d=2, positive=False, **kwargs):
i = 10 ** i
d = 10 ** d
return decimal.Decimal(
"{0}.{1}".format(
get_integer(low=0 if positive else -i, high=i-1),
get_positive_integer(high=d-1)
)
)
gen_decimal = loop(get_decimal)
def get_positive_decimal(**kwargs):
return get_decimal(positive=True)
gen_positive_decimal = loop(get_positive_decimal)
|
Python
| 0.001161
|
@@ -184,16 +184,17 @@
3456789'
+
# nolin
@@ -3107,18 +3107,24 @@
lse
+(
-i
+ + 1)
, high=i
-1),
@@ -3119,17 +3119,19 @@
, high=i
--
+ -
1),%0A
@@ -3165,17 +3165,19 @@
r(high=d
--
+ -
1)%0A
|
06e7dd815a77739089b2ad0aed5cb9f01a194967
|
Add script to normalize image using Ops
|
Normalize_Image.py
|
Normalize_Image.py
|
Python
| 0
|
@@ -0,0 +1,601 @@
+# @Dataset data%0A# @OpService ops%0A# @OUTPUT Img normalized%0A%0A# Create normalized image to the %5B0, 1%5D range.%0A#%0A# Stefan Helfrich (University of Konstanz), 03/10/2016%0A%0Afrom net.imglib2.type.numeric.real import FloatType%0Afrom net.imglib2.type.numeric.integer import ByteType%0Afrom net.imagej.ops import Ops%0A%0Anormalized = ops.create().imgPlus(data.getImgPlus(), data.getImgPlus());%0Anormalized.setName(%22normalized%22);%0AnormalizeOp = ops.op(Ops.Image.Normalize, normalized, data.getImgPlus(), None, None, FloatType(0.0), FloatType(1.0));%0A%0Aops.slicewise(normalized, data.getImgPlus(), normalizeOp, %5B0,1%5D, False);%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.