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
|
|---|---|---|---|---|---|---|---|
327b4a656347951b1b6bed1f04465dffc5011ec1
|
Update setup.py
|
setup.py
|
setup.py
|
"""Rachiopy setup script."""
from setuptools import find_packages, setup
from datetime import datetime
VERSION = "1.0.0"
GITHUB_USERNAME = "rfverbruggen"
GITHUB_REPOSITORY = "rachiopy"
GITHUB_PATH = f"{GITHUB_USERNAME}/{GITHUB_REPOSITORY}"
GITHUB_URL = f"https://github.com/{GITHUB_PATH}"
DOWNLOAD_URL = f"{GITHUB_URL}/archive/{VERSION}.tar.gz"
PROJECT_URLS = {"Bug Reports": f"{GITHUB_URL}/issues"}
PACKAGES = find_packages(exclude=["tests", "tests.*"])
setup(
name="RachioPy",
version=VERSION,
author="Robbert Verbruggen",
author_email="rfverbruggen@icloud.com",
packages=PACKAGES,
install_requires=["requests"],
url=GITHUB_URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
license="MIT",
description="A Python module for the Rachio API.",
platforms="Cross Platform",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Software Development",
],
)
|
Python
| 0.000001
|
@@ -69,38 +69,8 @@
etup
-%0Afrom datetime import datetime
%0A%0AVE
|
f91007560497d370b7451d212ad91dd23b47c892
|
Create version 0.3.22
|
setup.py
|
setup.py
|
from setuptools import setup
setup(name='DukeDSClient',
version='0.3.21',
description='Command line tool(ddsclient) to upload/manage projects on the duke-data-service.',
url='https://github.com/Duke-GCB/DukeDSClient',
keywords='duke dds dukedataservice',
author='John Bradley',
license='MIT',
packages=['ddsc','ddsc.core'],
install_requires=[
'requests',
'PyYAML',
'pytz',
'future',
'six',
],
test_suite='nose.collector',
tests_require=['nose', 'mock'],
entry_points={
'console_scripts': [
'ddsclient = ddsc.__main__:main'
]
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
Python
| 0.000001
|
@@ -77,9 +77,9 @@
.3.2
-1
+2
',%0A
|
4c15430e02c12f190b95791681f20f1a36a016d9
|
Add Python 3.4 classifier
|
setup.py
|
setup.py
|
__version__ = '0.21-dev'
import os
import sys
py_version = sys.version_info[:2]
PY3 = py_version[0] == 3
if PY3:
if py_version < (3, 2):
raise RuntimeError('On Python 3, Py65 requires Python 3.2 or later')
else:
if py_version < (2, 6):
raise RuntimeError('On Python 2, Py65 requires Python 2.6 or later')
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
DESC = """\
Simulate 6502-based microcomputer systems in Python."""
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: POSIX',
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'Programming Language :: Assembly',
'Topic :: Software Development :: Assemblers',
'Topic :: Software Development :: Disassemblers',
'Topic :: Software Development :: Debuggers',
'Topic :: Software Development :: Embedded Systems',
'Topic :: Software Development :: Interpreters',
'Topic :: System :: Emulators',
'Topic :: System :: Hardware'
]
setup(
name='py65',
version=__version__,
license='License :: OSI Approved :: BSD License',
url='https://github.com/mnaberez/py65',
description='6502 microprocessor simulation package',
long_description=DESC,
classifiers=CLASSIFIERS,
author="Mike Naberezny",
author_email="mike@naberezny.com",
maintainer="Mike Naberezny",
maintainer_email="mike@naberezny.com",
packages=find_packages(),
install_requires=[],
extras_require={},
tests_require=[],
include_package_data=True,
zip_safe=False,
namespace_packages=['py65'],
test_suite="py65.tests",
entry_points={
'console_scripts': [
'py65mon = py65.monitor:main',
],
},
)
|
Python
| 0.999999
|
@@ -682,25 +682,25 @@
POSIX',%0A
-%22
+'
Programming
@@ -717,24 +717,24 @@
: Python
-%22
+'
,%0A
-%22
+'
Programm
@@ -762,24 +762,24 @@
n :: 2.6
-%22
+'
,%0A
-%22
+'
Programm
@@ -807,24 +807,67 @@
n :: 2.7
-%22
+'
,%0A
-%22
+'Programming Language :: Python :: 3',%0A '
Programm
@@ -899,16 +899,16 @@
3.2
-%22
+'
,%0A
-%22
+'
Prog
@@ -940,17 +940,62 @@
n :: 3.3
-%22
+',%0A 'Programming Language :: Python :: 3.4'
,%0A 'P
|
f31d7a224d0c5a3c2b1d2b16fb4bc74edefacf24
|
Bump version string
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='autobuilder',
version='0.6.6',
packages=find_packages(),
license='MIT',
author='Matt Madison',
author_email='matt@madison.systems',
install_requires=['buildbot>=0.8.12m1']
)
|
Python
| 0.000001
|
@@ -86,17 +86,17 @@
on='0.6.
-6
+7
',%0A p
|
014acee66b9cff26cb8f02f65c071f78a0a77e19
|
Bump version to 0.9.4pbs22
|
setup.py
|
setup.py
|
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
dependency_links = [
'http://github.com/pbs/django-cms/tarball/support/2.3.x#egg=django-cms-2.3.5pbs.X.dev',
'http://github.com/pbs/django-filer/tarball/master_pbs#egg=django-filer-0.9pbs.X.dev',
]
setup(
name = "cmsplugin-filer",
version = "0.9.4pbs21",
url = 'http://github.com/stefanfoulis/cmsplugin-filer',
license = 'BSD',
description = "django-cms plugins for django-filer",
long_description = read('README.rst'),
author = 'Stefan Foulis',
author_email = 'stefan.foulis@gmail.com',
packages = find_packages(),
#package_dir = {'':'src'},
dependency_links=dependency_links,
classifiers = [
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
],
install_requires=[
"django-cms>=2.3.5pbs, <2.3.6",
"django-filer >= 0.9pbs, <0.9.1"
],
include_package_data=True,
zip_safe = False,
)
|
Python
| 0
|
@@ -405,17 +405,17 @@
.9.4pbs2
-1
+2
%22,%0A u
|
c53b8a0a06596d9803a8df92e909d4ad28169dda
|
Update the cookiedomain requirement to 0.6, which has httponly.
|
setup.py
|
setup.py
|
AUTHOR = 'Osmosoft'
AUTHOR_EMAIL = 'tiddlyspace@osmosoft.com'
NAME = 'tiddlywebplugins.tiddlyspace'
DESCRIPTION = 'A discoursive social model for TiddlyWiki'
VERSION = '0.2.2' # N.B.: duplicate of tiddlywebplugins.tiddlyspace.__init__
import os
from setuptools import setup, find_packages
setup(
namespace_packages = ['tiddlywebplugins'],
name = NAME,
version = VERSION,
description = DESCRIPTION,
long_description = open(os.path.join(os.path.dirname(__file__), 'README')).read(),
author = AUTHOR,
author_email = AUTHOR_EMAIL,
url = 'http://pypi.python.org/pypi/%s' % NAME,
platforms = 'Posix; MacOS X; Windows',
packages = find_packages(exclude=['test']),
scripts = ['tiddlyspace'],
install_requires = [
'setuptools',
'tiddlyweb>=1.1.dev5',
'tiddlywebwiki>=0.32',
'tiddlywebplugins.utils>=1.0',
'tiddlywebplugins.logout>=0.6',
'tiddlywebplugins.virtualhosting',
'tiddlywebplugins.socialusers>=0.3',
'tiddlywebplugins.magicuser>=0.3',
'tiddlywebplugins.openid2>=0.5',
'tiddlywebplugins.cookiedomain>=0.3',
'tiddlywebplugins.mselect',
'tiddlywebplugins.prettyerror>=0.8',
'tiddlywebplugins.pathinfohack>=0.8',
'tiddlywebplugins.form==dev',
'tiddlywebplugins.reflector>=0.2',
'tiddlywebplugins.whoosher>=0.9.10',
'tiddlywebplugins.atom>=1.2.0',
],
include_package_data = True,
zip_safe = False
)
|
Python
| 0
|
@@ -1124,25 +1124,25 @@
iedomain%3E=0.
-3
+6
',%0A '
|
07656b928c506c0f9d602a5c4195793b5e449693
|
test fix
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import re
with open('requirements.txt') as f:
requirements = f.readlines()
with open('async_connect/__init__.py') as f:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
with open('README.rst') as f:
readme = f.read()
setup(name='async-connect.py',
author='GiovanniMCMXCIX',
author_email='irimea.giovani.9@gmail.com',
url='https://github.com/GiovanniMCMXCIX/async-connect.py',
version=version,
packages=find_packages(),
license='MIT',
description='Asynchronous version of connect.py',
long_description=readme,
include_package_data=True,
install_requires=requirements,
extras_require={'performance': ['uvloop>=0.8.0']},
test_suite='tests',
tests_require=['uvloop>=0.8.0'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.6',
'Topic :: Internet',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
]
)
|
Python
| 0.000001
|
@@ -37,16 +37,27 @@
ackages%0A
+import sys%0A
import r
@@ -328,16 +328,111 @@
read()%0A%0A
+if sys.version_info%5B1%5D == 6:%0A test_require = %5B'uvloop%3E=0.8.0'%5D%0Aelse:%0A test_require = %5B%5D%0A%0A
setup(na
@@ -936,33 +936,28 @@
require=
-%5B'uvloop%3E=0.8.0'%5D
+test_require
,%0A
|
5c1338a623f438c1fdc6ddfcd79baf256819d57e
|
move tests scripts to parent directory to keep the same path in the source code
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2009 Adriano Monteiro Marques.
#
# Author: Bartosz SKOWRON <getxsick at gmail dot com>
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import glob
import os.path
from distutils.core import setup
UMPA_VERSION = '0.1'
TESTS_DIR = [
os.path.join('tests', 'system'),
os.path.join('tests', 'unit'),
os.path.join('tests', 'unit', 'test_extensions'),
os.path.join('tests', 'unit', 'test_protocols'),
os.path.join('tests', 'unit', 'test_utils')
]
test_files = []
for dir in TESTS_DIR:
test_files = test_files + [ (os.path.join('share','umpa', dir),
glob.glob(os.path.join(dir,'*.py')))]
data_files = [ (os.path.join('share','umpa','examples'),
glob.glob(os.path.join('examples','*'))),
(os.path.join('share','umpa','scripts'),
glob.glob(os.path.join('install_scripts','*.sh'))),
(os.path.join('share','doc','umpa','API'),
glob.glob(os.path.join('docs','API','*'))),
(os.path.join('share','umpa','tests'),
('run_tests.sh', 'run_tests.bat')),
(os.path.join('share','umpa','tests'),
glob.glob(os.path.join('tests','*.py')), 'README'),
(os.path.join('share','doc','umpa'),
('README', 'COPYING', 'AUTHORS', 'TODO', 'CHANGES',
'INSTALL')),
] + test_files
setup( name = "UMPA",
version = UMPA_VERSION,
description = "Umit's Manipulations of Packets Art",
author = "Bartosz SKOWRON",
author_email = "getxsick@gmail.com",
url = "http://www.umpa.umitproject.org",
license = "GNU LGPLv2",
platforms = ["Platform Independent"],
packages = [ "umpa",
"umpa.protocols",
"umpa.extensions",
"umpa.utils",
],
data_files = data_files
)
|
Python
| 0.000007
|
@@ -1806,39 +1806,32 @@
('share','umpa',
-'tests'
),%0A
|
ca62972886bcaef6375e78e32514883183f50929
|
bump version UP! Align to pypi
|
setup.py
|
setup.py
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
setup(
name='instapy-cli',
version='0.0.1',
description='Python library and cli used to upload photo on Instagram. W/o a phone!',
long_description=open('README.md.rst').read(),
classifiers=[
# How mature is this project?
'Development Status :: 5 - Production/Stable',
# For who your project is intended for and its usage
'Intended Audience :: Developers',
'Environment :: Console',
# Project's License
'License :: OSI Approved :: MIT License',
# Python versions instapy-cli support here
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='instagram private upload api instapy instapy-cli instapycli',
author='Benedetto Abbenanti',
author_email='benedetto.abbenanti@gmail.com',
url='https://github.com/b3nab/instapy-cli',
license='MIT',
packages=['instapy_cli'],
install_requires=[ # external packages as dependencies
'requests>=2',
'emoji'
],
entry_points={
'console_scripts': [
'instapy=instapy_cli.__main__:main'
]
},
# python_requires='>=2.7'
)
|
Python
| 0.000008
|
@@ -2,16 +2,30 @@
mport os
+%0Aimport codecs
%0A%0Afrom s
@@ -114,16 +114,264 @@
le__))%0A%0A
+def read(*parts):%0A %22%22%22%0A Build an absolute path from *parts* and and return the contents of the%0A resulting file. Assume UTF-8 encoding.%0A %22%22%22%0A with codecs.open(os.path.join(here, *parts), %22rb%22, %22utf-8%22) as f:%0A return f.read()%0A%0A
setup(%0A
@@ -414,9 +414,9 @@
0.0.
-1
+2
',%0A
@@ -525,20 +525,20 @@
ription=
-open
+read
('README
@@ -542,23 +542,13 @@
DME.
-md.
rst')
-.read()
,%0A
|
cee0402b1d8e3c261be789de43aaa8d56b78e743
|
Support for in and function calls
|
plyxproto/logicparser.py
|
plyxproto/logicparser.py
|
__author__ = "Sapan Bhatia"
__copyright__ = "Copyright (C) 2017 Open Networking Lab"
__version__ = "1.0"
import ply.lex as lex
import ply.yacc as yacc
from helpers import LexHelper, LU
class FOLLexer(object):
keywords = ('forall', 'exists', 'True', 'False', 'not')
tokens = ['STRING_LITERAL', 'NUM', 'ESCAPE', 'COLON', 'IMPLIES', 'OR', 'AND', 'LPAREN', 'RPAREN', 'EQUALS', 'SYMBOL', 'LT', 'RT'] + [k.upper() for k in keywords]
# literals = '()+-*/=?:,.^|&~!=[]{};<>@%'
t_ignore_LINE_COMMENT = '//.*'
t_COLON = '\\:'
t_IMPLIES = '\\-\\>'
t_OR = '\\|'
t_LT = '\\<'
t_RT = '\\>'
t_AND = '\\&'
t_LPAREN = '\\('
t_RPAREN = '\\)'
t_NUM = r'[+-]?\d+(\.\d+)?'
t_STRING_LITERAL = r'\"([^\\\n]|(\\.))*?\"'
t_EQUALS = '\\='
literals = '()+-*/=?:,.^|&~!=[]{};<>@%'
t_ignore = ' \t\f'
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_newline2(self, t):
r'(\r\n)+'
t.lexer.lineno += len(t.value) / 2
t_ESCAPE = r'{{ (.|\n)*? }}'
def t_BLOCK_COMMENT(self, t):
r'/\*(.|\n)*?\*/'
t.lexer.lineno += t.value.count('\n')
def t_SYMBOL(self, t):
'[A-Za-z_$][\.A-Za-z0-9_+$]*'
if t.value in FOLLexer.keywords:
t.type = t.value.upper()
return t
def t_error(self, t):
print("Illegal character '{}' ({}) in line {}".format(t.value[0], hex(ord(t.value[0])), t.lexer.lineno))
t.lexer.skip(1)
class FOLParser(object):
tokens = FOLLexer.tokens
offset = 0
lh = LexHelper()
def setOffset(self, of):
self.offset = of
self.lh.offset = of
def p_term_numeric_constant(self, p):
'''term : NUM'''
p[0] = p[1]
def p_term_string_constant(self, p):
'''term : STRING_LITERAL'''
p[0] = p[1]
def p_term_boolean_constant(self, p):
'''term : FALSE
| TRUE'''
p[0] = p[1]
def p_fole_not(self, p):
'''fole : NOT fole'''
p[0] = {p[1]: p[2]}
def p_fole_term(self, p):
'''fole : term'''
p[0] = p[1]
def p_term_symbol(self, p):
'''term : SYMBOL'''
p[0] = p[1]
def p_term_python(self, p):
'''term : ESCAPE'''
p[0] = {'python': p[1].lstrip('{ ').rstrip(' }')}
def p_fole_group(self, p):
"fole : LPAREN fole RPAREN"
p[0] = p[2]
def p_fole_equals(self, p):
"fole : term EQUALS term"
p[0] = {'=': (p[1], p[3])}
def p_fole_binary(self, p):
'''fole : fole AND fole
| fole OR fole
| fole IMPLIES fole'''
p[0] = {p[2]: [p[1], p[3]]}
def p_fole_quant(self, p):
'''fole : FORALL SYMBOL COLON fole
| EXISTS SYMBOL COLON fole'''
p[0] = {p[1]: [p[2], p[4]]}
def p_goal(self, p):
'''goal : LT fole RT'''
p[0] = p[2]
def p_error(self, p):
print('error: {}'.format(p))
|
Python
| 0
|
@@ -264,16 +264,22 @@
', 'not'
+, 'in'
)%0A%0A t
@@ -1224,16 +1224,23 @@
Za-z
-0
+2
-9_+$%5D*
+(%5C(%5C))?
'%0A
@@ -2432,32 +2432,127 @@
p%5B0%5D = p%5B2%5D%0A%0A
+ def p_fole_in(self, p):%0A %22fole : term IN term%22%0A p%5B0%5D = %7B'in': (p%5B1%5D, p%5B3%5D)%7D%0A%0A
def p_fole_e
|
47dd0d3f9d5d150adad7097bb2a24964f3c732b2
|
add pytest dep
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import setuptools
long_description = """python-evtx is a pure Python parser for \
Windows Event Log files (those with the file extension ".evtx"). \
The module provides programmatic access to the File and Chunk headers, \
record templates, and event entries. For example, you can use \
python-evtx to review the event logs of Windows 7 systems from \
a Mac or Linux workstation. The structure definitions and parsing \
strategies were heavily inspired by the work of Andreas Schuster \
and his Perl implementation "Parse-Evtx"."""
setuptools.setup(
name="python-evtx",
version="0.5.3",
description="Pure Python parser for recent Windows event log files (.evtx).",
long_description=long_description,
author="Willi Ballenthin",
author_email="willi.ballenthin@gmail.com",
url="https://github.com/williballenthin/python-evtx",
license="Apache 2.0 License",
packages=setuptools.find_packages(),
install_requires=['hexdump', 'six'],
scripts=['scripts/evtx_dump.py',
'scripts/evtx_dump_chunk_slack.py',
'scripts/evtx_eid_record_numbers.py',
'scripts/evtx_extract_record.py',
'scripts/evtx_filter_records.py',
'scripts/evtx_find_bugs.py',
'scripts/evtx_get_pretty_record.py',
'scripts/evtx_info.py',
'scripts/evtx_record_structure.py',
'scripts/evtx_structure.py',
'scripts/evtx_templates.py',
],
)
|
Python
| 0.000001
|
@@ -1010,24 +1010,85 @@
es=%5B
-'hexdump', 'six'
+%0A 'six',%0A 'pytest',%0A 'hexdump',%0A
%5D,%0A
|
f3cc4d84fbfcb430b004d730e44653079b3b3490
|
Update version to 1.6
|
setup.py
|
setup.py
|
import os
from setuptools import setup
def read(file):
return open(os.path.join(os.path.dirname(__file__), file)).read()
setup(
name="vsut",
version="1.5.5",
author="Alex Egger",
author_email="alex.egger96@gmail.com",
description="A simple unit testing framework for Python 3.4",
license="MIT",
keywords="unit unittest test testing",
url="http://github.com/zillolo/vsut-python",
packages=["vsut"],
scripts=["runner.py"],
entry_points = {"console_scripts" : ["vrun = runner:main"]},
long_description="""For usage information visit:
http://github.com/zillolo/vsut-python
""",
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Topic :: Software Development :: Testing"]
)
|
Python
| 0
|
@@ -163,11 +163,9 @@
=%221.
-5.5
+6
%22,%0A
|
5ea089d150a7e6132670ab92521bf763b1e719bf
|
bump version to 0.2
|
setup.py
|
setup.py
|
#!/usr/bin/python
from setuptools import setup
setup(
name="htmlgen",
version="0.1",
description="HTML 5 Generator",
author="Sebastian Rittau",
author_email="srittau@rittau.biz",
url="https://github.com/srittau/python-htmlgen",
packages=["htmlgen", "test_htmlgen"],
depends=["asserts"],
license="MIT",
)
|
Python
| 0.000001
|
@@ -89,9 +89,9 @@
=%220.
-1
+2
%22,%0A
|
7cfe670f621ac8ee7723e80c279a9794dc0a1bb9
|
update docker version
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='vent',
version='v0.6.9.dev',
packages=['vent', 'vent.core', 'vent.core.file_drop',
'vent.core.rq_worker', 'vent.core.rq_dashboard', 'vent.menus',
'vent.core.network_tap', 'vent.core.network_tap.ncontrol',
'vent.core.rmq_es_connector', 'vent.helpers', 'vent.api'],
install_requires=['docker>=3.5.0', 'npyscreen>=4.10.5', 'pyyaml>=3.13'],
scripts=['bin/vent'],
license='Apache License 2.0',
author='arpit',
author_email='',
maintainer='Charlie Lewis',
maintainer_email='clewis@iqt.org',
description=('A library that includes a CLI designed to serve as a'
' platform to collect and analyze data across a flexible set'
' of tools and technologies.'),
keywords='docker containers platform collection analysis tools devops',
url='https://github.com/CyberReboot/vent',
)
|
Python
| 0
|
@@ -389,17 +389,17 @@
er%3E=3.5.
-0
+1
', 'npys
|
284779dd4c0d13f53b0450c8c564ac23f6611170
|
Use higher degree poly kernel in SVC
|
prepare_outputs.py
|
prepare_outputs.py
|
# Prepare text to become data labels. Decompose phonemes into phonological features.
import nltk, pandas, prepare_data, prepare_EMG
from sklearn.svm import SVC
import numpy as np
class output_preparer():
""" Prepares the target data labels. Takes text, transforms it into phonemes, and then decomposes each phoneme into an array of phonological features. These arrays are returned for association with EMG data.
Attributes:
subvocal_detector: Optional. An estimator trained to detect subvocalizations in EMG windows. This estimator simply returns 'True' or 'False' for whether an EMG window it's passed contains subvocalization. This is only used with the 'zip' method for the output_preparer class when that method's 'auto_align' attribute is True.
"""
def __init__(self, subvocal_detector=None):
""" Initializes the output_preparer class.
"""
self.detector = subvocal_detector
if not self.detector:
estimator = SVC(C=0.90, kernel='poly', random_state=12)
data_prep = prepare_data.data_preparer()
# Use samples from each of the files that are both certain to contain and certain to not contain subvocalizations
EMG_Prep = prepare_EMG.EMG_preparer()
x_1, x_2 = data_prep.sv_detection()
# print("sample dataframes: ",x_1,x_2)
# Get some select samples
X_1, X_2 = EMG_Prep.process(x_1), EMG_Prep.process(x_2)
print("processed sample dataframes: ",X_1,X_2)
labels = []
for row in range(X_1.shape[0]):
# print('lol')
labels.append(0)
# for row in X_2:
for row in range(X_2.shape[0]):
# print('wut')
labels.append(1)
# print(labels)
X = X_1.append(X_2)
labels = pandas.DataFrame(np.ravel(labels), index=[i for i in range(len(labels))], columns=['sv'])
# print(labels['sv'])
estimator.fit(X, labels)
print("Training Score:", estimator.score(X, labels))
self.detector = estimator
# Process them into windows
# Combine those windows with 'yes' or 'no' labels for SV
# Train an estimator on these datapoints to identify SV signals in windows
pass
def transform(self, text):
""" Transforms 'text', a string, into arrays of phonological features corresponding to phonemes. Returns a DataFrame of phonological features and their corresponding phonemes.
"""
arpabet = nltk.corpus.cmudict.dict()
words = text.split(" ")
all_phonemes = []
for word in words:
all_phonemes += [phoneme for phoneme in arpabet[word][0]]
# TODO: Construct arrays of phonological features for each phoneme.
return all_phonemes
def zip(self, data, labels, auto_align=True):
""" Zips data and labels such that labels are sequentially applied to serial rows of 'data' that most likely contain subvocalizations. If the data is already boolean labeled for containing subvocalization, 'auto_align' should be false to make use of those labels.
Attributes:
data: a pandas DataFrame containing rows of subsequent EMG windows.
labels: a pandas DataFrame of phonological features and phonemes.
auto_align: boolean. If true, indicates an automatic method is to be used in aligning each row in 'outputs' with those portions of 'data' most likely to contain actual subvocalization.
Returns:
A dataframe of labels with null values where corresponding rows in 'data' most likely do not contain subvocalization, or are labeled as such.
"""
# For row in data
# If row appears or is marked as containing subvocalization
# Apply next phoneme label to that row
new_labels = DataFrame()
label_row = 0
null_row = 0 # TODO: rewrite this to dynamically scale to 'labels', to act as a null filler row. There might be an integrated method for this already.
if auto_align:
method = self.detector.predict()
else:
method = lambda x: x[row]['subvocalization'] == True
for row in data:
if method(data[row]):
new_labels[row] = labels[label_row]
label_row += 1
else:
new_labels[row] = null_row
return new_labels
|
Python
| 0
|
@@ -989,10 +989,10 @@
C=0.
-90
+25
, ke
@@ -1003,16 +1003,26 @@
='poly',
+ degree=5,
random_
@@ -1469,32 +1469,34 @@
x_2)%0A
+ #
print(%22processe
|
046f9e35568c4f647780e504e2000fabf0f9937b
|
use __version__ from dynash.py
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
SETUP_OPTIONS = dict(
name='dynash',
version='0.5.1',
description='Command line client for DynamoDB',
long_description = open("README.md").read(),
author='Raffaele Sena',
author_email='raff367@gmail.com',
url='https://github.com/raff/dynash',
license = "MIT",
platforms = "Posix; MacOS X; Windows",
py_modules=['dynash'
],
data_files=[('.', ['README.md'])
],
install_requires=['distribute',
'setuptools >= 0.6c11',
'boto >= 2.5.1'
],
entry_points="""
[console_scripts]
dynash=dynash:run_command
"""
)
def do_setup():
setup(**SETUP_OPTIONS)
if __name__ == '__main__':
do_setup()
|
Python
| 0.000043
|
@@ -68,16 +68,47 @@
rt setup
+%0Afrom dynash import __version__
%0A%0ASETUP_
@@ -158,15 +158,19 @@
ion=
-'0.5.1'
+__version__
,%0A
|
1f9b2c7836d6738d5a86d93644a04da7729b3688
|
Prepare openprocurement.api 2.4.5.
|
setup.py
|
setup.py
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
requires = [
'barbecue',
'chaussette',
'cornice',
'couchdb-schematics',
'gevent',
'iso8601',
'jsonpatch',
'libnacl',
'pbkdf2',
'pycrypto',
'pyramid_exclog',
'requests',
'rfc6266',
'setuptools',
'tzlocal',
]
test_requires = requires + [
'webtest',
'python-coveralls',
'mock'
]
docs_requires = requires + [
'sphinxcontrib-httpdomain',
]
entry_points = {
'paste.app_factory': [
'main = openprocurement.api.app:main'
],
'openprocurement.api.plugins': [
'api = openprocurement.api.includeme:includeme'
],
'openprocurement.api.migrations': [
'tenders = openprocurement.api.migration:migrate_data'
],
'console_scripts': [
'bootstrap_api_security = openprocurement.api.database:bootstrap_api_security'
]
}
setup(name='openprocurement.api',
version='2.4.4',
description='openprocurement.api',
long_description=README,
classifiers=[
"Framework :: Pylons",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application"
],
keywords="web services",
author='Quintagroup, Ltd.',
author_email='info@quintagroup.com',
license='Apache License 2.0',
url='https://github.com/openprocurement/openprocurement.api',
package_dir={'': 'src'},
py_modules=['cgi'],
packages=find_packages('src'),
namespace_packages=['openprocurement'],
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=test_requires,
extras_require={'test': test_requires, 'docs': docs_requires},
test_suite="openprocurement.api.tests.main.suite",
entry_points=entry_points)
|
Python
| 0
|
@@ -1065,17 +1065,17 @@
on='2.4.
-4
+5
',%0A
|
cabfe1a7586e5ce313105cab08810f51dae6b479
|
Update setup.py
|
setup.py
|
setup.py
|
#from distutils.core import setup
from setuptools import setup
from odplib import meta
setup(name="rst2odp",
version=meta.__version__,
author=meta.__author__,
author_email=meta.__email__,
description="Converter for rst to OpenOffice Impress",
long_description='''Packacking of rst2odp and opdlib from docutils sandbox. odplib is a standalone library for creating odp output from python. rst2odp wraps it for rst users. Now supports Python 3''',
license='Apache',
url='https://github.com/mattharrison/rst2odp',
scripts=["bin/rst2odp", "bin/otptweak", "bin/odpstyles"],
#package_dir={"odplib":"odplib"},
install_requires=['docutils >= 0.10', 'pygments >= 1.6',
'pillow >= 1.7.8', 'lxml >= 3.6.4'],
package_data={'odplib':['data/*.xml']},
packages=['odplib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: Office/Business'
]
)
|
Python
| 0
|
@@ -491,14 +491,11 @@
se='
-Apache
+MIT
',%0A
|
ec87897adfe021f2f61b96e07eb23e7f31edd2a4
|
Remove set_templates code (it wasnt used)
|
nexus/nexus_modules.py
|
nexus/nexus_modules.py
|
import nexus
from django.conf import settings
from django.contrib import admin
def make_nexus_model_admin(model_admin):
class NexusModelAdmin(model_admin.__class__):
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
opts = self.model._meta
app_label = opts.app_label
self.add_form_template = self.change_form_template = (
'nexus/admin/%s/%s/change_form.html' % (app_label, opts.object_name.lower()),
'nexus/admin/%s/change_form.html' % app_label,
'nexus/admin/change_form.html',
)
extra_context = self.admin_site.get_context(request)
del extra_context['title']
context.update(extra_context)
return super(NexusModelAdmin, self).render_change_form(request, context, add, change, form_url, obj)
def changelist_view(self, request, extra_context=None):
opts = self.model._meta
app_label = opts.app_label
self.change_list_template = (
'nexus/admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()),
'nexus/admin/%s/change_list.html' % app_label,
'nexus/admin/change_list.html'
)
if not extra_context:
extra_context = self.admin_site.get_context(request)
else:
extra_context.update(self.admin_site.get_context(request))
del extra_context['title']
return super(NexusModelAdmin, self).changelist_view(request, extra_context)
def delete_view(self, request, object_id, extra_context=None):
opts = self.model._meta
app_label = opts.app_label
self.delete_confirmation_template = (
'nexus/admin/%s/%s/delete_confirmation.html' % (app_label, opts.object_name.lower()),
'nexus/admin/%s/delete_confirmation.html' % app_label,
'nexus/admin/delete_confirmation.html'
)
if not extra_context:
extra_context = self.admin_site.get_context(request)
else:
extra_context.update(self.admin_site.get_context(request))
del extra_context['title']
return super(NexusModelAdmin, self).delete_view(request, object_id, extra_context)
def history_view(self, request, object_id, extra_context=None):
opts = self.model._meta
app_label = opts.app_label
self.object_history_template = (
'nexus/admin/%s/%s/object_history.html' % (app_label, opts.object_name.lower()),
'nexus/admin/%s/object_history.html' % app_label,
'nexus/admin/object_history.html'
)
if not extra_context:
extra_context = self.admin_site.get_context(request)
else:
extra_context.update(self.admin_site.get_context(request))
del extra_context['title']
return super(NexusModelAdmin, self).history_view(request, object_id, extra_context)
return NexusModelAdmin
def make_nexus_admin_site(admin_site):
class NexusAdminSite(admin_site.__class__):
index_template = 'nexus/admin/index.html'
app_index_template = 'nexus/admin/app_index.html'
# def __init__(self, name, app_name):
# super(NexusAdminSite, self).__init__(name, app_name)
def has_permission(self, request):
return self.module.site.has_permission(request)
def get_context(self, request):
context = self.module.get_context(request)
context.update(self.module.site.get_context(request))
return context
def index(self, request, extra_context=None):
return super(NexusAdminSite, self).index(request, self.get_context(request))
def app_index(self, request, app_label, extra_context=None):
return super(NexusAdminSite, self).app_index(request, app_label, self.get_context(request))
return NexusAdminSite
class AdminModule(nexus.NexusModule):
home_url = 'index'
def __init__(self, site):
new_site = make_nexus_admin_site(site)(site.name, site.app_name)
new_site.module = self
for model, admin in site._registry.iteritems():
new_site.register(model, make_nexus_model_admin(admin))
self.admin_site = new_site
self.app_name = new_site.app_name
self.name = new_site.name
def get_urls(self):
return self.admin_site.get_urls()
def urls(self):
return self.admin_site.urls
urls = property(urls)
def set_templates(self, model, admin):
# TODO:
pass
def get_title(self):
return 'Model Admin'
def render_on_dashboard(self, request):
return self.render_to_string('nexus/admin/dashboard/index.html', {
'base_url': './' + self.app_name + '/'
}, request)
if 'django.contrib.admin' in settings.INSTALLED_APPS:
nexus.site.register(AdminModule(admin.site), admin.site.app_name)
|
Python
| 0
|
@@ -4778,81 +4778,8 @@
s)%0A%0A
- def set_templates(self, model, admin):%0A # TODO:%0A pass%0A%0A
|
1a7eb2627fbf3bc0ddb5d8fd5b051f3139275590
|
Fix moderation rule
|
Rules/Moderation.py
|
Rules/Moderation.py
|
from ._shared import *
class Moderation(Rule):
"""Handles message to moderate listing"""
def __init__(self, bot):
self.bot = bot
def __call__(self, serv, author, args):
"""Handles message to moderate listing"""
if not self.bot.has_admin_rights(serv, author):
return
if len(args) > 1:
liste = args[1].split("@")[0]
query = ("SELECT id, subject, author, liste FROM moderation " +
"WHERE liste=%s AND moderated=0 ORDER BY date DESC")
values = (liste,)
message = ("Messages en attente de modération " +
"pour la liste " + liste + " :")
else:
query = ("SELECT id, subject, author, liste FROM moderation " +
"WHERE moderated=0 ORDER BY date DESC")
values = ()
message = "Messages en attente de modération :"
try:
bdd = self.bot.mysql_connect(serv)
assert(bdd is not None)
except AssertionError:
return
bdd_cursor = bdd.cursor()
bdd_cursor.execute(query, values)
if bdd_cursor.rowcount <= 0:
self.ans(serv,
author,
"Aucun message en attente de modération.")
return
self.ans(serv, author, message)
for (ident, subject, author, liste) in bdd_cursor:
self.say(serv, "["+liste+"] : « "+subject+" » par "+author)
bdd_cursor.close()
bdd.close()
def close(self):
pass
|
Python
| 0.000048
|
@@ -1181,32 +1181,36 @@
self.
+bot.
ans(serv,%0A
@@ -1228,16 +1228,20 @@
+
author,%0A
@@ -1236,16 +1236,20 @@
author,%0A
+
@@ -1336,16 +1336,20 @@
self.
+bot.
ans(serv
@@ -1443,16 +1443,20 @@
self.
+bot.
say(serv
|
90c82f0936addeb4469db2c42c1cd48713e7f3cf
|
Switch from bold to red highlighting.
|
progress_logger.py
|
progress_logger.py
|
# Copyright Google
# BSD License
import copy
import wash
# from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
class TermLogger(object):
def print_progress(self, lots, text, bold_lots):
lots = copy.copy(lots) # so I can re-sort non-destructively
print text
lots.sort(cmp=wash.cmp_by_buy_date)
bold_ids = [id(lot) for lot in bold_lots]
for lot in lots:
header = ''
footer = ''
if id(lot) in bold_ids:
header = color.BOLD
footer = color.END
print header + str(lot) + footer
raw_input('hit enter>')
class NullLogger(object):
def print_progress(self, lots, text, bold_lots):
pass
|
Python
| 0
|
@@ -418,35 +418,34 @@
lf, lots, text,
-bol
+re
d_lots):%0A lot
@@ -561,19 +561,18 @@
te)%0A
-bol
+re
d_ids =
@@ -591,19 +591,18 @@
lot in
-bol
+re
d_lots%5D%0A
@@ -678,19 +678,18 @@
lot) in
-bol
+re
d_ids:%0A
@@ -710,19 +710,18 @@
= color.
-BOL
+RE
D%0A
@@ -874,19 +874,18 @@
, text,
-bol
+re
d_lots):
|
e409c6608abd19f863e8e21452d438bdf9176b4a
|
rename for first run
|
test/test_var_nn_embedded_vec_classifier.py
|
test/test_var_nn_embedded_vec_classifier.py
|
import os
import unittest
import urllib
import sys
import shorttext
# The "test_w2v_model.bin" in this directory is adapted from: https://raw.githubusercontent.com/chinmayapancholi13/shorttext_test_data/master/test_w2v_model
class TestVarNNEmbeddedVecClassifier(unittest.TestCase):
def setUp(self):
print("Downloading word-embedding model....")
link = "https://github.com/stephenhky/PyShortTextCategorization/blob/master/data/test_w2v_model.bin?raw=true"
filename = "test_w2v_model.bin"
if not os.path.isfile("test_w2v_model.bin"):
if sys.version_info[0]==2:
urllib.urlretrieve(link, filename)
else:
urllib.request.urlretrieve(link, filename)
self.w2v_model = shorttext.utils.load_word2vec_model(filename, binary=True) # load word2vec model
self.trainclass_dict = shorttext.data.subjectkeywords() # load training data
def tearDown(self):
print("Removing word-embedding model")
if os.path.isfile("test_w2v_model.bin"):
os.remove('test_w2v_model.bin')
def comparedict(self, dict1, dict2):
self.assertTrue(len(dict1)==len(dict2))
print(dict1, dict2)
for classlabel in dict1:
self.assertTrue(classlabel in dict2)
self.assertAlmostEqual(dict1[classlabel], dict2[classlabel], places=4)
def testCNNWordEmbedWithoutGensim(self):
print("Testing CNN...")
# create keras model using `CNNWordEmbed` class
print("\tKeras model")
keras_model = shorttext.classifiers.frameworks.CNNWordEmbed(wvmodel=self.w2v_model,
nb_labels=len(self.trainclass_dict.keys()))
# create and train classifier using keras model constructed above
print("\tTraining")
main_classifier = shorttext.classifiers.VarNNEmbeddedVecClassifier(self.w2v_model)
main_classifier.train(self.trainclass_dict, keras_model, nb_epoch=2)
# compute classification score
print("\tTesting")
score_vals = main_classifier.score('artificial intelligence')
self.assertAlmostEqual(score_vals['mathematics'] + score_vals['physics'] + score_vals['theology'], 1.0, 1)
def testDoubleCNNWordEmbedWithoutGensim(self):
print("Testing DoubleCNN...")
# create keras model using `DoubleCNNWordEmbed` class
print("\tKeras model")
keras_model = shorttext.classifiers.frameworks.DoubleCNNWordEmbed(wvmodel=self.w2v_model,
nb_labels=len(self.trainclass_dict.keys()))
# create and train classifier using keras model constructed above
print("\tTraining")
main_classifier = shorttext.classifiers.VarNNEmbeddedVecClassifier(self.w2v_model)
main_classifier.train(self.trainclass_dict, keras_model, nb_epoch=2)
# compute classification score
print("\tTesting")
score_vals = main_classifier.score('artificial intelligence')
self.assertAlmostEqual(score_vals['mathematics'] + score_vals['physics'] + score_vals['theology'], 1.0, 1)
def testCLSTMWordEmbedWithoutGensim(self):
print("Testing CLSTM...")
# create keras model using `CLSTMWordEmbed` class
print("\tKeras model")
keras_model = shorttext.classifiers.frameworks.CLSTMWordEmbed(wvmodel=self.w2v_model,
nb_labels=len(self.trainclass_dict.keys()))
# create and train classifier using keras model constructed above
print("\tTraining")
main_classifier = shorttext.classifiers.VarNNEmbeddedVecClassifier(self.w2v_model)
main_classifier.train(self.trainclass_dict, keras_model, nb_epoch=2)
# compute classification score
print("\tTesting")
score_vals = main_classifier.score('artificial intelligence')
self.assertAlmostEqual(score_vals['mathematics'] + score_vals['physics'] + score_vals['theology'], 1.0, 1)
def testSumEmbed(self):
print("Testing SumEmbed")
classifier = shorttext.classifiers.SumEmbeddedVecClassifier(self.w2v_model)
classdict = shorttext.data.subjectkeywords()
classifier.train(classdict)
# compute
self.comparedict(classifier.score('linear algebra'),
{'mathematics': 0.9986082046096036,
'physics': 0.9976047404871671,
'theology': 0.9923434326310248})
self.comparedict(classifier.score('learning'),
{'mathematics': 0.998968177605999,
'physics': 0.9995439648885027,
'theology': 0.9965552994894663})
if __name__ == '__main__':
unittest.main()
|
Python
| 0.000001
|
@@ -4102,16 +4102,18 @@
def test
+AA
SumEmbed
|
a25558ef0f1a902e948424bc0a3e137cc4d0f569
|
implement programming via remote gdb session
|
scons/site_tools/openocd_remote.py
|
scons/site_tools/openocd_remote.py
|
#!/usr/bin/env python
#
# Copyright (c) 2014, Roboterclub Aachen e.V.
# All Rights Reserved.
#
# The file is part of the xpcc library and is released under the 3-clause BSD
# license. See the file `LICENSE` for the full license governing this code.
import platform
from SCons.Script import *
# -----------------------------------------------------------------------------
# Copy the hex file to the remote target as /tmp/openocd.hex
# Then use telnet interface of openocd to remotely control openocd to flash
# hex file to connected target.
# openocd must be running on target at port 4444
def openocd_remote_run(env, source, alias='openocd_remote_run'):
if platform.system() == "Windows":
print "Not supported under windows"
exit(1)
else:
commands = ["init", "reset halt", "flash write_image erase /tmp/openocd.hex", "reset run"]
action = Action("scp $SOURCE $OPENOCD_REMOTE_USER@$OPENOCD_REMOTE_HOST:/tmp/openocd.hex; echo %s | nc $OPENOCD_REMOTE_HOST 4444" % ' '.join(['"%s;"' % c for c in commands]),
cmdstr="$OPENOCD_COMSTR")
return env.AlwaysBuild(env.Alias(alias, source, action))
# -----------------------------------------------------------------------------
def generate(env, **kw):
# build messages
if not ARGUMENTS.get('verbose'):
env['OPENOCD_COMSTR'] = "OpenOCD remote: program $SOURCE"
env['OPENOCD'] = 'openocd'
env.AddMethod(openocd_remote_run, 'OpenOcdRemote')
def exists(env):
return env.Detect('openocd_remote')
|
Python
| 0
|
@@ -1098,16 +1098,586 @@
action))
+%0A# -----------------------------------------------------------------------------%0A# Program elf file via a remote gdb session%0Adef gdb_remote_program(env, source, alias='gdb_remote_program'):%0A%09if platform.system() == %22Windows%22:%0A%09%09print %22Not supported under windows%22%0A%09%09exit(1)%0A%09else:%0A%09%09gdb = %22arm-none-eabi-gdb%22%0A%09%09cmd = %5Bgdb, '-q',%0A%09%09%09'-ex %22target remote $OPENOCD_REMOTE_HOST:3333%22',%0A%09%09%09'-ex %22load%22',%0A%09%09%09'-ex %22monitor reset%22',%0A%09%09%09'-ex %22disconnect%22',%0A%09%09%09'-ex %22quit%22',%0A%09%09%09'$SOURCE'%5D%0A%0A%09%09action = Action(' '.join(cmd))%0A%09%09return env.AlwaysBuild(env.Alias(alias, source, action))
%0A%0A# ----
@@ -1970,16 +1970,72 @@
Remote')
+%0A%09env.AddMethod(gdb_remote_program, 'GdbRemoteProgram')
%0A%0Adef ex
|
9df7691be1e46310736db2a0a3303e39923273a5
|
allow properties to be instantiated via file stream
|
jproperties.py
|
jproperties.py
|
"""
python-jproperties
Java .properties file parsing and handling
"""
from collections import OrderedDict
from collections.abc import MutableMapping
__version__ = "0.3"
__author__ = "Jerome Leclanche"
__email__ = "jerome@leclan.ch"
class Node:
def __repr__(self):
return "<EmptyNode>"
class Comment(Node):
def __init__(self, value, sigil="#"):
self.value = value
self.sigil = sigil
def __str__(self):
return "\n".join("%s %s" % (self.sigil, line) for line in self.value.split("\n")) # noqa: E501
def __repr__(self):
return "<Comment: %r>" % (str(self))
class Property(Node):
DEFAULT_SEPARATOR = " = "
def __init__(self, key, value, separator=DEFAULT_SEPARATOR):
self.key = key.encode("unicode_escape") \
.decode("utf-8") \
.replace(":", r"\:") \
.replace("=", r"\=") \
.replace(" ", r"\ ")
self.value = value
self.separator = separator
def __repr__(self):
return "<Property %r %s %r>" % (self.key, self.separator, self.value)
class Properties(MutableMapping):
def __init__(self, defaults=None):
if defaults is not None:
self._props = defaults.copy()
else:
self._props = OrderedDict()
self.nodes = [Property(k, v) for k, v in self._props.items()]
def __str__(self):
ret = []
for node in self.nodes:
if hasattr(node, 'key'):
line = "{0.key}{0.separator}{0.value}".format(node)
ret.append(line)
elif hasattr(node, 'value'):
ret.append(str(node))
else:
ret.append("")
return "\n".join(ret)
def __getitem__(self, key):
return self._props.get(key, "")
getProperty = __getitem__
def __setitem__(self, key, value):
self._props[key] = value
for node in self.nodes:
if isinstance(node, Property) and node.key == key:
self.nodes[self.nodes.index(node)] = Property(key, value)
break
else:
self.nodes.append(Property(key, value))
setProperty = __setitem__
def __delitem__(self, key):
for node in self.nodes:
if isinstance(node, Property) and node.key == key:
del self.nodes[self.nodes.index(node)]
del self._props[key]
delProperty = __delitem__
def __iter__(self):
for key in self._props.keys():
yield key
def __len__(self):
return len(self._props.keys())
def __contains__(self, key):
return key in self._props
@staticmethod
def escape(value):
return value.encode("unicode_escape").decode("utf-8")
@staticmethod
def unescape(value):
ret = []
backslash = False
for c in value:
if backslash:
if c == "u":
# fall through to native unicode_escape
ret.append(r"\u")
elif c == "t":
ret.append("\t")
elif c == "r":
ret.append("\r")
elif c == "n":
ret.append("\n")
elif c == "f":
ret.append("\f")
else:
ret.append(c)
backslash = False
elif c == "\\":
backslash = True
else:
ret.append(c)
ret = "".join(ret).encode("utf-8").decode("unicode_escape")
return ret
@staticmethod
def _get_lines(stream):
def _strip_line(line):
last = ""
while line.endswith(("\n", "\r", " ")):
if line[-1] == "\\":
line += last
break
last = line[-1]
line = line[:-1]
return line.lstrip()
buf = []
cont = False
for line in stream.readlines():
if line.endswith("\\\n") and not line.endswith("\\\\\n"):
buf.append(line[:-2].lstrip())
cont = True
continue
elif cont:
buf.append(line.strip())
cont = False
else:
buf.append(line)
yield _strip_line("".join(buf))
buf = []
@staticmethod
def _separate(line):
def getkey(s):
ret = []
escaping = False
for c in s:
if not escaping:
if c in " \t:=":
break
elif c == "\\":
escaping = True
else:
escaping = False
ret.append(c)
return "".join(ret)
def getseparator(s):
ret = []
for c in s:
if c not in " \t:=":
return "".join(ret)
ret.append(c)
return "".join(ret)
def getvalue(s):
ret = []
escaping = False
for c in s:
if not escaping:
if c == "\\":
escaping = True
else:
escaping = False
ret.append(c)
return "".join(ret)
key = getkey(line)
idx = len(key)
sep = getseparator(line[idx:])
idx += len(sep)
value = getvalue(line[idx:])
return key, sep, value
def load(self, stream):
comment = []
for line in self._get_lines(stream):
# Skip null lines
if not line:
self.nodes.append(Node())
continue
if line.startswith(("#", "!")):
# NOTE: Multiline comments with different sigils will be normalized on the
# last specified sigil
sigil = line[0]
comment.append(line[1:].strip())
continue
elif comment:
self.nodes.append(Comment("\n".join(comment), sigil))
comment = []
key, separator, value = self._separate(line)
key = self.unescape(key)
value = self.unescape(value)
self._props[key] = value
node = Property(key, value, separator)
self.nodes.append(node)
def save(self, path):
with open(path, 'w') as f:
f.write(str(self) + "\n")
def propertyNames(self):
# Java compat
return self._props.keys()
|
Python
| 0
|
@@ -1157,42 +1157,178 @@
None
-):%0A if defaults is not None
+, stream=None):%0A if stream and defaults:%0A raise ValueError(%0A %22defaults and stream are mutually exclusive parameters%22)%0A if defaults
:%0A
@@ -1492,16 +1492,66 @@
ems()%5D%0A%0A
+ if stream:%0A self.load(stream)%0A%0A
def
|
0263e6782086a97a5f403d9de79b85b2d405aa6b
|
Disable SSH agent forwarding
|
nighttrain/__main__.py
|
nighttrain/__main__.py
|
# Copyright 2017 Codethink Ltd.
#
# 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.
'''Night Train: Simple SSH-based build automation'''
import pssh
import argparse
import logging
import os
import sys
import time
import nighttrain
def argument_parser():
parser = argparse.ArgumentParser(
description="Simple SSH automation for build, test, deployment, etc.")
# Controls for running tasks
parser.add_argument(
'--force', action='store_true',
help="Define 'force=yes' in environment for each task")
parser.add_argument(
'--hosts', '--host', type=str,
help="Select hosts to run on (default: all hosts)")
parser.add_argument(
'--tasks', '--task', '-t', type=str,
help="Select tasks to run (default: all tasks)")
parser.add_argument(
'--log-directory', '-l', type=str, default='/var/log/ci',
help="Base directory for log files")
# Alternative actions
parser.add_argument(
'--command', '-c', type=str, default=None,
help="Run the specified command on the remote hosts, instead of any "
"of the tasks. This is intended for debugging your tasks.")
parser.add_argument(
'--list', action='store_true',
help="List the available tasks and hosts, then exit")
return parser
def check_args(args):
normal_run = True
if args.command:
normal_run = False
if args.list:
raise RuntimeError("--command and --list are incompatible")
if args.tasks:
raise RuntimeError("--command and --tasks are incompatible")
if args.list:
normal_run = False
if args.tasks:
raise RuntimeError("--list and --tasks are incompatible")
if normal_run:
if not os.path.isdir(args.log_directory):
raise RuntimeError("Log directory %s doesn't seem to exist. "
"Use --log-directory to change." %
args.log_directory)
if not os.access(args.log_directory, os.W_OK):
raise RuntimeError("Log directory %s doesn't appear writable" %
args.log_directory)
def ensure_list(string_or_list):
if isinstance(string_or_list, str):
return [string_or_list]
else:
return string_or_list
def name_session():
return time.strftime('%Y.%m.%d-%H.%M.%S')
def run_single_command(client, hosts, command):
'''Implements the --command action.'''
logging.info("Running command %s" % command)
output = client.run_command(command, stop_on_errors=True)
client.join(output)
for host in hosts:
for line in output[host].stdout:
print("[%s] %s" % (host, line))
print("[%s] Exit code: %i" % (host, output[host].exit_code))
def main():
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
args = argument_parser().parse_args()
with open('./tasks') as f:
tasks = nighttrain.tasks.TaskList(f.read())
with open('./hosts') as f:
host_config = nighttrain.ssh_config.SSHConfig(f.read())
check_args(args)
if args.list:
print("Available hosts:\n\n *", '\n * '.join(host_config.keys()))
print()
print("Available tasks:\n\n *", '\n * '.join(tasks.names()))
return
hosts = ensure_list(args.hosts) or host_config.keys()
tasks_to_run = ensure_list(args.tasks) or tasks.names()
logging.info("Selected tasks: %s", ','.join(tasks_to_run))
client = pssh.ParallelSSHClient(hosts, host_config=host_config)
if args.command:
run_single_command(client, hosts, args.command)
return
session_name = name_session()
log_directory = os.path.join(args.log_directory, session_name)
os.makedirs(log_directory, exist_ok=False)
logging.info("Created log directory: %s", log_directory)
results = []
try:
results = nighttrain.tasks.run_all_tasks(
client, hosts, [t for t in tasks if t['name'] in tasks_to_run],
log_directory=log_directory, force=args.force)
finally:
if results:
report_filename = os.path.join(log_directory, 'report')
logging.info("Writing report to: %s", report_filename)
with open(report_filename, 'w') as f:
nighttrain.tasks.write_report(f, results)
try:
main()
except (RuntimeError, pssh.exceptions.ConnectionErrorException,
pssh.exceptions.AuthenticationException) as e:
sys.stderr.write("ERROR: %s\n" % e)
sys.exit(1)
|
Python
| 0
|
@@ -4040,16 +4040,41 @@
t(hosts,
+ forward_ssh_agent=False,
host_co
|
c3f844cfe03a23a5d6207ba99b5dc6abac9b94a1
|
Add unit test.
|
awx/main/tests/unit/models/test_job_unit.py
|
awx/main/tests/unit/models/test_job_unit.py
|
import pytest
import json
from awx.main.tasks import RunJob
from awx.main.models import Job
@pytest.fixture
def job(mocker):
return mocker.MagicMock(**{
'display_extra_vars.return_value': '{\"secret_key\": \"$encrypted$\"}',
'extra_vars_dict': {"secret_key": "my_password"},
'pk': 1, 'job_template.pk': 1, 'job_template.name': '',
'created_by.pk': 1, 'created_by.username': 'admin',
'launch_type': 'manual'})
@pytest.mark.survey
def test_job_survey_password_redaction():
"""Tests the Job model's funciton to redact passwords from
extra_vars - used when displaying job information"""
job = Job(
name="test-job-with-passwords",
extra_vars=json.dumps({
'submitter_email': 'foobar@redhat.com',
'secret_key': '6kQngg3h8lgiSTvIEb21',
'SSN': '123-45-6789'}),
survey_passwords={
'secret_key': '$encrypted$',
'SSN': '$encrypted$'})
assert json.loads(job.display_extra_vars()) == {
'submitter_email': 'foobar@redhat.com',
'secret_key': '$encrypted$',
'SSN': '$encrypted$'}
def test_job_safe_args_redacted_passwords(job):
"""Verify that safe_args hides passwords in the job extra_vars"""
kwargs = {'ansible_version': '2.1'}
run_job = RunJob()
safe_args = run_job.build_safe_args(job, **kwargs)
ev_index = safe_args.index('-e') + 1
extra_vars = json.loads(safe_args[ev_index])
assert extra_vars['secret_key'] == '$encrypted$'
def test_job_args_unredacted_passwords(job):
kwargs = {'ansible_version': '2.1'}
run_job = RunJob()
args = run_job.build_args(job, **kwargs)
ev_index = args.index('-e') + 1
extra_vars = json.loads(args[ev_index])
assert extra_vars['secret_key'] == 'my_password'
|
Python
| 0
|
@@ -1129,16 +1129,548 @@
ted$'%7D%0A%0A
+@pytest.mark.survey%0Adef test_survey_passwords_not_in_extra_vars():%0A %22%22%22Tests that survey passwords not included in extra_vars are%0A not included when displaying job information%22%22%22%0A job = Job(%0A name=%22test-survey-not-in%22,%0A extra_vars=json.dumps(%7B%0A 'submitter_email': 'foobar@redhat.com'%7D),%0A survey_passwords=%7B%0A 'secret_key': '$encrypted$',%0A 'SSN': '$encrypted$'%7D)%0A assert json.loads(job.display_extra_vars()) == %7B%0A 'submitter_email': 'foobar@redhat.com',%0A %7D%0A%0A
def test
|
3b0760ce604ab5e627f8459fc83f4f7b638c224e
|
Fix flake8 warning
|
cmsplugin_forms_builder/cms_plugins.py
|
cmsplugin_forms_builder/cms_plugins.py
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_forms_builder.models import PluginForm
from django.utils.translation import ugettext_lazy as _
class FormBuilderPlugin(CMSPluginBase):
"""
Plugin class for form-builder forms.
"""
model = PluginForm
name = _("Form")
render_template = "forms/form_detail.html"
cache = False
def render(self, context, instance, placeholder):
context['form'] = instance.form
return context
plugin_pool.register_plugin(FormBuilderPlugin)
|
Python
| 0
|
@@ -517,16 +517,17 @@
ontext%0A%0A
+%0A
plugin_p
|
75aa936c489dedc8592f5f27fd013c1bda2decc1
|
Use POST form data instead of GET parameters
|
flask_mwoauth/__init__.py
|
flask_mwoauth/__init__.py
|
#!/usr/bin/env python
# MediaWiki OAuth connector for Flask
#
# Requires flask-oauthlib
#
# (C) 2013 Merlijn van Deen <valhallasw@arctus.nl>
# Licensed under the MIT License // http://opensource.org/licenses/MIT
#
__version__ = '0.2.46'
import sys
from future.utils import iteritems
from future.moves.urllib.parse import urlencode
from flask import request, session, redirect, url_for, flash, Blueprint
from flask_oauthlib.client import OAuth, OAuthException
from requests.models import Request
class MWOAuth(object):
def __init__(self,
base_url='https://www.mediawiki.org/w',
clean_url='https://www.mediawiki.org/wiki',
default_return_to='index',
consumer_key=None, consumer_secret=None, name='mw.org'):
if not consumer_key or not consumer_secret:
raise Exception('MWOAuthBlueprintFactory needs consumer key and secret')
self.base_url = base_url
self.default_return_to = default_return_to
self.oauth = OAuth()
request_url_params = {'title': 'Special:OAuth/initiate',
'oauth_callback': 'oob'}
access_token_params = {'title': 'Special:OAuth/token'}
self.mwoauth = self.oauth.remote_app(
name,
base_url=base_url + "/index.php",
request_token_url=base_url + "/index.php?" +
urlencode(request_url_params),
request_token_params=None,
access_token_url=base_url + "/index.php?" +
urlencode(access_token_params),
authorize_url=clean_url + '/Special:OAuth/authorize',
consumer_key=consumer_key,
consumer_secret=consumer_secret,
)
@self.mwoauth.tokengetter
def get_mwo_token(token=None):
return session.get('mwo_token')
self.bp = Blueprint('mwoauth', __name__)
@self.bp.route('/logout')
def logout():
session['mwo_token'] = None
session['username'] = None
if 'next' in request.args:
return redirect(request.args['next'])
return "Logged out!"
@self.bp.route('/login')
def login():
uri_params = {'oauth_consumer_key': self.mwoauth.consumer_key}
redirector = self.mwoauth.authorize(**uri_params)
if 'next' in request.args:
oauth_token = session[self.mwoauth.name + '_oauthtok'][0]
session[oauth_token + '_target'] = request.args['next']
return redirector
@self.bp.route('/oauth-callback')
def oauth_authorized():
resp = self.mwoauth.authorized_response()
next_url_key = request.args['oauth_token'] + '_target'
default_url = url_for(self.default_return_to)
next_url = session.pop(next_url_key, default_url)
if resp is None:
flash(u'You denied the request to sign in.')
return redirect(next_url)
session['mwo_token'] = (
resp['oauth_token'],
resp['oauth_token_secret']
)
username = self.get_current_user(False)
flash('You were signed in, %s!' % username)
return redirect(next_url)
@staticmethod
def _prepare_long_request(url, api_query):
""" Use requests.Request and requests.PreparedRequest to produce the
body (and boundary value) of a multipart/form-data; POST request as
detailed in https://www.mediawiki.org/wiki/API:Edit#Large_texts
"""
partlist = []
for k, v in iteritems(api_query):
if k in ('title', 'text', 'summary'):
# title, text and summary values in the request
# should be utf-8 encoded
part = (k,
(None, v.encode('utf-8'),
'text/plain; charset=UTF-8',
{'Content-Transfer-Encoding': '8bit'}
)
)
else:
part = (k, (None, v))
partlist.append(part)
return Request(url=url, files=partlist).prepare()
def request(self, api_query, url=None):
""" e.g. {'action': 'query', 'meta': 'userinfo'}. format=json not required
function returns a python dict that resembles the api's json response
"""
api_query['format'] = 'json'
url = url or self.base_url
size = sum([sys.getsizeof(v) for k, v in iteritems(api_query)])
if size > (1024 * 8):
# if request is bigger than 8 kB (the limit is somewhat arbitrary,
# see https://www.mediawiki.org/wiki/API:Edit#Large_texts) then
# transmit as multipart message
req = self._prepare_long_request(url=url + "/api.php?",
api_query=api_query
)
return self.mwoauth.post(url + "/api.php?",
data=req.body,
content_type=req.headers['Content-Type']
).data
else:
return self.mwoauth.post(url + "/api.php?" + urlencode(api_query),
content_type="text/plain").data
def get_current_user(self, cached=True):
if cached:
return session.get('username')
try:
data = self.request({'action': 'query', 'meta': 'userinfo'})
session['username'] = data['query']['userinfo']['name']
except KeyError:
session['username'] = None
if data['error']['code'] == "mwoauth-invalid-authorization":
flash(u'Access to this application was revoked. Please re-login!')
else:
raise
except OAuthException:
session['username'] = None
return session['username']
|
Python
| 0
|
@@ -5329,23 +5329,53 @@
.php
-?%22 + urlencode(
+%22,%0A data=
api_
@@ -5379,18 +5379,16 @@
pi_query
-),
%0A
@@ -5421,33 +5421,8 @@
-content_type=%22text/plain%22
).da
|
a051899ac8365ebb855267a706e3a5c094f9ab24
|
support longer instance ids
|
awsh/__init__.py
|
awsh/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import boto3
from os import path, system
from pprint import pprint
import argparse
import itertools
from collections import deque
VERSION = "1.0.11"
def connect(instance, args):
details = get_details(instance)
print('\nConnecting to: {name}\n'.format(**details))
pprint(details)
if args.console_output:
print('\n========= console output start =========')
print(instance.console_output().get('Output', '').replace('\\n', '\n'))
print('========== console output end ==========\n')
users = deque(args.users)
# return code 65280 is 'Permission Denied'
while _connect(users.popleft(), instance, args) == 65280 and len(users):
pass
def _connect(user, instance, args):
config = {
'key_path': get_key_path(args, instance),
'tunnel': get_tunnel(args),
'host': "{}@{}".format(user, instance.public_dns_name),
'timeout': args.timeout
}
command = 'ssh -i {key_path} {tunnel} {host} -o ConnectTimeout={timeout}'.format(**config)
if args.command:
command = '{} -C {}'.format(command, args.command)
print('\nTrying with user: {}.\nCommand: {}'.format(user, command))
return system(command)
def get_tunnel(args):
if not args.remote_host:
return ''
url = args.remote_host.split(':')
if len(url) == 2:
params = {'local_port': args.local_port or url[1], 'remote_host': url[0], 'remote_port': url[1]}
elif len(url) == 3:
params = {'local_port': url[0], 'remote_host': url[1], 'remote_port': url[2]}
else:
if not args.local_port:
args.local_port = args.remote_port
params = args.__dict__
return "-L '{local_port}:{remote_host}:{remote_port}'".format(**params)
def get_details(instance):
return {
'id': instance.id,
'name': get_name(instance),
'type': instance.instance_type,
'private_dns_name': instance.private_dns_name,
'public_dns_name': instance.public_dns_name,
'availability_zone': instance.placement.get('AvailabilityZone'),
'security_groups': instance.security_groups,
'state': instance.state.get('Name'),
'launch time': instance.launch_time.isoformat(),
'block devices': get_device_mappings(instance)
}
def get_key_path(args, instance):
if args.key_path:
return args.key_path
else:
directory = path.expanduser(args.keys)
return path.join(directory, instance.key_name + '.pem')
def get_device_mappings(instance):
return flatten([device.values() for device in instance.block_device_mappings])
def flatten(array):
list(itertools.chain.from_iterable(array))
def get_name(instance):
name = [tag for tag in instance.tags if tag['Key'] == 'Name']
if not name or 'Value' not in name[0]:
return 'not-named'
return name[0].get('Value')
def get_instances(args):
ec2 = boto3.resource('ec2', region_name=args.region)
filters = [{'Name': 'tag:Name', 'Values': ['*{filter}*'.format(**args.__dict__)]}]
print('Querying AWS for EC2 instances in region: {region}...\n'.format(**args.__dict__))
return sorted(ec2.instances.filter(Filters=filters), key=get_name)
def main():
parser = create_parser()
args = parser.parse_args()
if args.version:
print(VERSION)
exit(0)
instances = get_instances(args)
if not instances:
print('No instances found.\n')
exit(1)
if len(instances) == 1:
print('Found one instance and connecting to it...\n')
connect(instances[0], args)
else:
select_instance(args, instances, parser)
def select_instance(args, instances, parser):
details_fmt = "{:2} - {name:<32}{id:<16}{public_dns_name:<48}{private_dns_name:<48}{type:<12}({state})"
for i, instance in enumerate(instances):
print(details_fmt.format(i, **get_details(instance)))
try:
i = int(input("\nEnter server number: "))
connect(instances[i], args)
except ValueError:
print('Invalid instance.\n')
parser.print_help()
except (EOFError, KeyboardInterrupt, SyntaxError):
exit(0)
def create_parser():
parser = argparse.ArgumentParser(description="""
SSH into AWS instances.
The default user list assumes that your instances runs on Ubuntu and or Amazon's AMIs.
ex: "awsh --users user1 user2 --region us-west-2 --keys '~/.keys' instance-name".
Note that "awsh --users user1 user2 instance-name" will not be parsed properly
due to the nature of nargs. In that case you may want to do:
"awsh instance-name --users user1 user2".
""")
parser.add_argument('filter', nargs='?', default='*', help='Optional name filter. '
'If only one instance is found, it will connect to it directly.')
parser.add_argument('--users', nargs='+', help='Specify the users to try.',
default=['ubuntu', 'ec2-user'])
parser.add_argument('--region', help='Specify the aws region.', default='us-east-1')
parser.add_argument('-i', '--key-path', help='Specific key path, overrides, --keys')
parser.add_argument('-c', '--command', help='Translates to ssh -C')
parser.add_argument('-r', '--remote-host',
help='Open a tunnels. Translates to ssh -L <local-port>:<remote-host>:<remote-port> <selected-aws-host>')
parser.add_argument('-p', '--remote-port', help='Port to use on the remote host.', default=5432)
parser.add_argument('-l', '--local-port', help='Port to use on the local host. Get overwritten by remote port if not defined.')
parser.add_argument('--keys', help='Directory of the private keys.', default='~/.ssh/')
parser.add_argument('--timeout', help='SSH connection timeout.', default='5')
parser.add_argument('--console-output', help='Display the instance console out before logging in.',
action='store_true')
parser.add_argument('--version', help='Returns awsh\'s version.', action='store_true')
return parser
if __name__ == '__main__':
main()
|
Python
| 0.000001
|
@@ -3789,10 +3789,10 @@
id:%3C
-16
+24
%7D%7Bpu
|
749b05712474ea8695fb6f2d1662399da42b1d32
|
Update error with user input
|
SimpleCalculator.py
|
SimpleCalculator.py
|
'''
Author : DORIAN JAVA BROWN
Version : N/A
Copyright : All Rights Reserve; You may use, distribute and modify this code.
Description : This is a simple calculator that can add, subtract, multiply and divide using functions
'''
'''function definitions'''
def calculate():
# operation selection from the user
print('\n\n')
print('\t\t\tOperation Selection')
print('-------------------------------------------------------------')
print('+ for addition')
print('- for subtraction')
print('* for multiplication')
print('/ for division')
print('\ for modulus')
print('\n\n')
operation = raw_input('Enter Operation symbol: ')
# check if operation symbol is valid
operator(operation)
# recieving two numbers from user
num1 = int(raw_input('\nEnter first number : '))
num2 = int(raw_input('\nEnter second number : '))
# addition
if operation == '+':
print('\n\n')
print('ANSWER: {} + {} = '.format(num1,num2) + str(num1 + num2))
print('\n\n')
# subtraction
elif operation == '-':
print('\n\n')
print('ANSWER: {} - {} = '.format(num1,num2) + str(num1 - num2))
print('\n\n')
# multiplication
elif operation == '*':
print('\n\n')
print('ANSWER: {} * {} = '.format(num1,num2) + str(num1 * num2))
print('\n\n')
# divison
elif operation == '/':
print('\n\n')
print('ANSWER: {} / {} = '.format(num1,num2) + str(num1 / num2))
print('\n\n')
# modulus
elif operation == '/':
print('\n\n')
print('ANSWER: {} \ {} = '.format(num1,num2) + str(num1 % num2))
print('\n\n')
else: print('Invalid character, please run the program again.')
def operator(operation):
if operation != '+':
if operation == 3 :
print('Invalid operator, please run the program again.')
calculate()
'''function call'''
calculate()
|
Python
| 0.000001
|
@@ -245,35 +245,8 @@
'%0A%0A%0A
-%0A'''function definitions'''
%0A%0Ade
@@ -676,175 +676,10 @@
lid%0A
- operator(operation)%0A %0A # recieving two numbers from user%0A num1 = int(raw_input('%5CnEnter first number : '))%0A num2 = int(raw_input('%5CnEnter second number : '))%0A
+%0A%0A
%0A #
@@ -711,16 +711,41 @@
== '+':%0A
+ userData(num1, num2)%0A
prin
@@ -790,32 +790,33 @@
= '.format(num1,
+
num2) + str(num1
@@ -890,16 +890,31 @@
== '-':%0A
+ userData()%0A
prin
@@ -1554,177 +1554,276 @@
def
-op
+us
er
+D
at
-or(operation
+a(num1, num2
):%0A
-%0A
- if operation != '+':%0A%0A if operation == 3 :%0A print('Invalid operator, please run the program again.')%0A calculate()%0A%0A
+# recieving two numbers from user%0A num1 = int(raw_input('%5CnEnter first number : '))%0A num2 = int(raw_input('%5CnEnter second number : '))%0A return num1, num2%0A%0A %0A'''function definitions'''%0Anum1 = userData(num1, num2)%0Anum2 = userData(num1, num2)%0A
%0A %0A
|
9302f918390063c1bfedf2724e0b1fb9a3d1effb
|
Add the required whitespace before css classes This was preventing some email clients from correctly displaying the styling.
|
portal/models/message.py
|
portal/models/message.py
|
"""Model classes for message data"""
from datetime import datetime
from textwrap import fill
from flask import current_app
from flask_mail import Message
from flask_mail import email_dispatched
from ..audit import auditable_event
from ..database import db
from ..extensions import mail
from .user import User
def log_message(message, app):
"""Configured to handle signals on email_dispatched - log the event"""
app.logger.info(u"Message sent; To: {0} Subj: {1}".format(
message.recipients, message.subject))
email_dispatched.connect(log_message)
EMAIL_HEADER = (
"<!DOCTYPE html>"
"<html><head><style>"
"body {"
" font-size: 16px;"
"}"
".btn {"
" font-size: 0.9em;"
" font-family: Helvetica, Arial, sans-serif;"
" display: inline-block;"
" color: #FFF;"
" background-color: #7C959E;"
" border-color: #7C959E;"
" border-radius: 0;"
" letter-spacing: 2px;"
" cursor: pointer;"
" text-transform: uppercase;"
" text-align: center;"
" line-height: 1.42857143;"
" font-weight: 400;"
" padding: 0.6em;"
" text-decoration: none;"
"}"
".btn:hover {"
" background-color: #576e76;"
"}"
"</style></head><body>")
EMAIL_FOOTER = "</body></html>"
class EmailMessage(db.Model):
__tablename__ = 'email_messages'
id = db.Column(db.Integer, primary_key=True)
subject = db.Column(db.String(255), nullable=False)
recipients = db.Column(db.Text, nullable=False)
sender = db.Column(db.String(255), nullable=False)
sent_at = db.Column(db.DateTime, default=datetime.utcnow)
body = db.Column(db.Text, nullable=False)
# nullable as anonymous support requests won't have associated users
user_id = db.Column(
db.Integer(), db.ForeignKey('users.id', ondelete='CASCADE'))
def style_message(self, body):
"""Implicitly called on send, to wrap body with style tags"""
# Catch duplicate styling attempts
restricted = ('doctype', 'html', 'head', 'body')
lower_body = body.lower()
for element in restricted:
if element in lower_body:
raise ValueError(
"Unexpected element '{}' found in email body".format(
element))
return '{header}{body}{footer}'.format(
header=EMAIL_HEADER, body=body, footer=EMAIL_FOOTER)
def send_message(self):
message = Message(
subject=self.subject,
sender=current_app.config['DEFAULT_MAIL_SENDER'],
recipients=self.recipients.split())
body = self.style_message(self.body)
message.html = fill(body, width=280)
mail.send(message)
user = User.query.filter_by(email='__system__').first()
user_id = user.id if user else None
recipient = self.recipients.split()[0]
subject = User.query.filter_by(email=recipient).first()
subject_id = subject.id if subject else self.user_id
if user_id and subject_id:
audit_msg = ("EmailMessage '{0.subject}' sent to "
"{0.recipients} from {0.sender}".format(self))
auditable_event(message=audit_msg, user_id=user_id,
subject_id=subject_id, context="user")
def __str__(self):
return "EmailMessage subj:{} sent_at:{}".format(self.subject,
self.sent_at)
|
Python
| 0.00007
|
@@ -619,16 +619,44 @@
%3E%3Chead%3E%3C
+title%3ETrueNTH email%3C/title%3E%3C
style%3E%22%0A
@@ -701,24 +701,25 @@
%22%7D%22%0A %22
+
.btn %7B%22%0A
@@ -1164,16 +1164,17 @@
%7D%22%0A %22
+
.btn:hov
|
1072487ce3ffe96557d5a14efed3715c2592cebc
|
Fix OSX
|
prompty/userdir.py
|
prompty/userdir.py
|
#!/usr/bin/env python
# vim:set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import shutil
import errno
import distutils.dir_util
PROMPTY_USER_DIR = os.path.join(".local", "share", "prompty")
PROMPTY_CONFIG_FILE = "prompty.cfg"
SKEL_DIR = "skel"
FUNCTIONS_DIR = "functions"
def getPromptyBaseDir():
"""
Get the directory where the prompty module is located
"""
return os.path.dirname(
os.path.dirname(
# The filename of this module
os.path.normpath(os.path.abspath(sys.modules[__name__].__file__))
)
)
class UserDir(object):
def __init__(self, homeDir=None):
if homeDir is None:
self.homeDir = os.path.expanduser('~')
else:
self.homeDir = homeDir
self.promtyUserDir = os.path.join(self.homeDir, PROMPTY_USER_DIR)
self.promtyBaseDir = getPromptyBaseDir()
self.promtyUserFunctionsDir = os.path.join(self.promtyUserDir, FUNCTIONS_DIR)
self.skelDir = os.path.join(self.promtyBaseDir, SKEL_DIR)
if not os.path.exists(self.skelDir):
# Installed locally
self.skelDir = os.path.join(self.homeDir, ".local", "share", "prompty", SKEL_DIR)
if not os.path.exists(self.skelDir):
# Install dir as defined in setup.py
self.skelDir = os.path.join(sys.prefix, "share", "prompty", SKEL_DIR)
if not os.path.exists(self.skelDir):
# Install dir as defined in setup.py
self.skelDir = os.path.join(sys.prefix, "local", "share", "prompty", SKEL_DIR)
if not os.path.exists(self.skelDir):
raise IOError("Cannot find installed skel directory")
# Initialise if promptyUserDir does not exist
self.initialise()
def initialise(self):
if not os.path.isfile(self.getConfigFile()):
# No prompty dir - check if there is a file blocking the name
if os.path.isfile(self.promtyUserDir):
raise IOError("Cannot create %s directory - file exists!" % PROMPTY_USER_DIR)
# Create prompty dir from skel
self.copy(self.skelDir, self.promtyUserDir)
@staticmethod
def copy(src, dest):
try:
if os.path.isdir(src):
distutils.dir_util.copy_tree(src, dest)
else:
shutil.copytree(src, dest)
except OSError as e:
# If the error was caused because the source wasn't a directory
if e.errno == errno.ENOTDIR:
shutil.copy(src, dest)
else:
raise IOError('Directory not copied. Error: %s' % e)
def getDir(self):
return self.promtyUserDir
def getConfigFile(self):
return os.path.join(self.promtyUserDir, PROMPTY_CONFIG_FILE)
|
Python
| 0.000659
|
@@ -1627,32 +1627,222 @@
#
+ Mac OSX%0A self.skelDir = os.path.join(self.promtyBaseDir, %22share%22, %22prompty%22, SKEL_DIR)%0A%0A if not os.path.exists(self.skelDir):%0A #
Install dir as
@@ -1853,32 +1853,36 @@
ned in setup.py%0A
+
@@ -1973,32 +1973,40 @@
+
if not os.path.e
@@ -2018,32 +2018,40 @@
(self.skelDir):%0A
+
|
101b48fed741c0c95f69e4ce678fbb390d7f709e
|
Fix flake8
|
ykman/native/pyusb.py
|
ykman/native/pyusb.py
|
# Copyright (c) 2015 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import ctypes
import ctypes.util
import os
import sys
import usb.core
import usb.backend.libusb1 as libusb1
import usb.backend.libusb0 as libusb0
import usb.backend.openusb as openusb
def _find_library(libname):
libpath = os.path.join(os.path.dirname(sys.executable), libname)
if sys.platform == 'win32':
libpath += '.dll'
if os.path.isfile(libpath):
return libpath
if sys.platform == 'darwin':
libpath = os.path.join(os.path.dirname(sys.executable), "../Frameworks", libname)
if os.path.isfile(libpath):
return libpath
return ctypes.util.find_library(libname)
def _load_usb_backend():
for m in (libusb1, openusb, libusb0):
backend = m.get_backend(find_library=_find_library)
if backend is not None:
return backend
_usb_backend = None
def get_usb_backend():
global _usb_backend
_usb_backend = _usb_backend or _load_usb_backend()
return _usb_backend
class LibUsb1Version(ctypes.Structure):
_fields_ = [
('major', ctypes.c_uint16),
('minor', ctypes.c_uint16),
('micro', ctypes.c_uint16),
('nano', ctypes.c_uint16),
('rc', ctypes.c_char_p),
('describe', ctypes.c_char_p)
]
def get_usb_backend_version():
backend = get_usb_backend()
if backend is None:
return None
elif isinstance(backend, libusb1._LibUSB):
lib = backend.lib
lib.libusb_get_version.restype = ctypes.POINTER(LibUsb1Version)
version = lib.libusb_get_version().contents
return 'libusb {0.major}.{0.minor}.{0.micro}'.format(version)
elif isinstance(backend, openusb._OpenUSB):
from usb.backend.openusb import _lib as lib
usb.core.find(True) # OpenUSB seems to hang if not called.
elif isinstance(backend, libusb0._LibUSB):
from usb.backend.libusb0 import _lib as lib
return lib._name
|
Python
| 0
|
@@ -1817,32 +1817,45 @@
= os.path.join(
+%0A
os.path.dirname(
|
85912ea3988ffc4e0516ff14fa51c4bab9ac1630
|
fix string formatting
|
slask.py
|
slask.py
|
#!/usr/bin/env python
from __future__ import print_function
from glob import glob
import importlib
import logging
import os
import re
import sys
import time
import traceback
from slackclient import SlackClient
def init_log(config):
loglevel = config.get("loglevel", logging.INFO)
logformat = config.get("logformat", '%(asctime)s:%(levelname)s:%(message)s')
logfile = config.get("logfile", "slask.log")
# create logger
logger = logging.getLogger(__name__)
logger.setLevel(loglevel)
# create console handler and set level to debug
ch = logging.FileHandler(logfile)
ch.setLevel(loglevel)
# create formatter
formatter = logging.Formatter(logformat)
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# make it the root logger (I hate the logging module)
logging.root = logger
def init_plugins(plugindir):
hooks = {}
for plugin in glob(os.path.join(plugindir, "[!_]*.py")):
logging.debug("plugin: {0}".format(plugin))
try:
mod = importlib.import_module(plugin.replace(os.path.sep, ".")[:-3])
modname = mod.__name__.split('.')[1]
for hook in re.findall("on_(\w+)", " ".join(dir(mod))):
hookfun = getattr(mod, "on_" + hook)
logging.debug("attaching {0}.{1} to {2}".format(modname, hookfun, hook))
hooks.setdefault(hook, []).append(hookfun)
if mod.__doc__:
firstline = mod.__doc__.split('\n')[0]
hooks.setdefault('help', {})[modname] = firstline
hooks.setdefault('extendedhelp', {})[modname] = mod.__doc__
#bare except, because the modules could raise any number of errors
#on import, and we want them not to kill our server
except:
logging.info("import failed on module {0}, module not loaded".format(plugin))
logging.info("{0}".format(sys.exc_info()[0]))
logging.info("{0}".format(traceback.format_exc()))
return hooks
def run_hook(hooks, hook, data, server):
responses = []
for hook in hooks.get(hook, []):
h = hook(data, server)
if h: responses.append(h)
return responses
def handle_message(client, event, hooks, config):
# ignore bot messages and edits
subtype = event.get("subtype", "")
if subtype == "bot_message" or subtype == "message_changed": return
botname = client.server.login_data["self"]["name"]
try:
msguser = client.server.users.get(event["user"])
except KeyError:
logging.debug("event {0} has no user".format(event))
return
if msguser["name"] == botname or msguser["name"].lower() == "slackbot":
return
return "\n".join(run_hook(hooks, "message", event, {"client": client, "config": config, "hooks": hooks}))
event_handlers = {
"message": handle_message
}
def main(config):
hooks = init_plugins("plugins")
client = SlackClient(config["token"])
if client.rtm_connect():
users = client.server.users
while True:
events = client.rtm_read()
for event in events:
#print "got {0}".format(event.get("type", event))
handler = event_handlers.get(event.get("type"))
if handler:
response = handler(client, event, hooks, config)
if response:
client.rtm_send_message(event["channel"], response)
time.sleep(1)
else:
logging.warn("Connection Failed, invalid token <{}>?".format(config["token"]))
if __name__=="__main__":
from config import config
init_log(config)
main(config)
|
Python
| 0.000182
|
@@ -3599,16 +3599,17 @@
token %3C%7B
+0
%7D%3E?%22.for
|
fa7fc8181f09340c9778ef6c056674ddc7d3d54e
|
Add run convergence
|
tests/convergence_tests/convergence_lspr.py
|
tests/convergence_tests/convergence_lspr.py
|
import re
import os
import sys
import time
import numpy
import pickle
import datetime
try:
import pycuda
except ImportError:
ans = input('PyCUDA not found. Regression tests will take forever. Do you want to continue? [y/n] ')
if ans in ['Y', 'y']:
pass
else:
sys.exit()
from pygbe.main import main as pygbe
mesh = ['500', '2K', '8K', '32K']
def picklesave(test_outputs):
with open('tests','wb') as f:
pickle.dump(test_outputs, f, 2)
def pickleload():
with open('tests', 'rb') as f:
test_outputs = pickle.load(f)
return test_outputs
def mesh_ratio(N):
"""
Calculates the mesh refinement ratio between consecutive meshes.
Arguments:
----------
N: list of int, Number of elements in test.
Returns:
--------
mesh_ratio: list of float, mesh refinement ratio between consequtive meshes.
"""
mesh_ratio = []
for i in range(len(N)-1):
mesh_ratio.append(N[i+1]/N[i])
return mesh_ratio
def report_results(error, N, expected_rate, iterations, Cext, analytical, total_time, test_name=None):
"""
Prints out information for the convergence tests.
Inputs:
-------
error : list of float, L2 Norm of error against analytical solution.
N : list of int, Number of elements in test.
expected_rate: float, expected error rate acording to mesh refinement.
iterations : list of int, Number of iterations to converge.
Cext : list of float, Cross extinction section.
analytical : list of float, analytical solution of the Cross extinction
section.
total_time: list of float, total wall time of run i.
"""
with open('convergence_test_results', 'a') as f:
print('-' * 60, file=f)
print('{:-^60}'.format('Running: ' + test_name), file=f)
print('-' * 60, file=f)
print(datetime.datetime.now(), file=f)
flag = 0
for i in range(len(error)-1):
rate = error[i]/error[i+1]
if abs(rate-expected_rate)>0.6:
flag = 1
print('Bad convergence for mesh {} to {}, with rate {}'.
format(i, i+1, rate), file=f)
if flag==0:
print('Passed convergence test!', file=f)
print('\nNumber of elements : {}'.format(N), file=f)
print('Number of iteration: {}'.format(iterations), file=f)
print('Cext'.format(Cext), file=f)
print('Analytical solution: {} kcal/mol'.format(analytical), file=f)
print('Error : {}'.format(error), file=f)
print('Total time : {}'.format(total_time), file=f)
|
Python
| 0.000001
|
@@ -2723,20 +2723,1812 @@
otal_time), file=f)%0A
+%0A%0Adef run_convergence(mesh, test_name, problem_folder, param):%0A %22%22%22%0A Runs convergence tests over a series of mesh sizes%0A%0A Inputs:%0A ------%0A mesh : array of mesh suffixes%0A problem_folder: str, name of folder containing meshes, etc...%0A param : str, name of param file%0A%0A Returns:%0A -------%0A N : len(mesh) array, elements of problem.%0A iterations: len(mesh) array, number of iterations to converge.%0A Cext : len(mesh) array of float, Cross extinction section.%0A Time : len(mesh) array of float, time to solution (wall-time)%0A %22%22%22%0A print('Runs lspr case of silver sphere in water medium')%0A N = numpy.zeros(len(mesh))%0A iterations = numpy.zeros(len(mesh))%0A Cext = numpy.zeros(len(mesh))%0A Time = numpy.zeros(len(mesh))%0A for i in range(len(mesh)):%0A try:%0A print('Start run for mesh '+mesh%5Bi%5D)%0A results = pygbe(%5B'',%0A '-p', '%7B%7D'.format(param),%0A '-c', '%7B%7D_%7B%7D.config'.format(test_name, mesh%5Bi%5D),%0A '-o', 'output_%7B%7D_%7B%7D'.format(test_name, mesh%5Bi%5D),%0A '-g', './',%0A '%7B%7D'.format(problem_folder),%5D, return_results_dict=True)%0A%0A N%5Bi%5D = results%5B'total_elements'%5D%0A iterations%5Bi%5D = results%5B'iterations'%5D%0A Cext%5Bi%5D = results.get('Cext', 0)%0A Time%5Bi%5D = results%5B'total_time'%5D%0A%0A except (pycuda._driver.MemoryError, pycuda._driver.LaunchError) as e:%0A print('Mesh %7B%7D failed due to insufficient memory.'%0A 'Skipping this test, but convergence test should still complete'.format(mesh%5Bi%5D))%0A time.sleep(4)%0A%0A%0A return(N, iterations, Esolv, Esurf, Ecoul, Time)%0A
|
9ff9add738807ffcca63fdf02aca5e13a029259a
|
Fix debug message again
|
fluxghost/http_handler.py
|
fluxghost/http_handler.py
|
import os
from http.server import BaseHTTPRequestHandler
from urllib.parse import urlparse
from urllib.request import Request
from urllib.request import urlopen
import logging
from fluxghost.http_websocket_route import get_match_ws_service
from fluxghost import __version__
from io import StringIO
import urllib.error
logger = logging.getLogger("HTTP")
class HttpHandler(BaseHTTPRequestHandler):
server_version = "FLUXGhost/%s" % __version__
protocol_version = "HTTP/1.1"
def __init__(self, request, client, server):
request.settimeout(60.)
try:
BaseHTTPRequestHandler.__init__(self, request, client, server)
except OSError as e:
if server.debug:
logger.exception("OSError in http request")
else:
logger.error("%s", e)
except Exception:
logger.exception("Unhandle Error")
def version_string(self):
return self.server_version
def log_error(self, format, *args):
self.log_message(format, *args, error=True)
def log_message(self, format, *args, **kw):
if kw.get("error"):
logger.warn("%s %s" % (self.address_string(), format % args))
else:
logger.info("%s %s" % (self.address_string(), format % args))
def do_GET(self): # noqa
if self.path.startswith("/ws/"):
klass, kwargs = get_match_ws_service(self.path[4:])
if klass:
self.serve_websocket(klass, kwargs)
else:
logger.exception("Websocket route error: %s" % self.path[4:])
self.response_404()
elif self.path == "/":
return self.serve_assets("index.html")
elif self.path.startswith("/api"):
try:
hostname = os.environ.get("proxy_api_host")
print("Proxying %s" % hostname)
url = 'http://{}{}'.format(hostname, self.path)
req = Request(url=url)
req_headers = self.headers.items()
for header, value in req_headers:
if str(header).startswith("Host"):
continue
if str(header).startswith("Accept-Encoding"):
continue
req.add_header(header, value)
try:
resp = urlopen(req)
except urllib.error.HTTPError as e:
if e.getcode():
resp = e
else:
self.send_error(599, u'error proxying: {}'.format(unicode(e)))
return
self.send_response(resp.getcode())
respheaders = resp.getheaders()
for header, value in respheaders:
if str(header).startswith("Transfer-Encoding"):
continue
print("Response headers: " + header + " vs " + value)
self.send_header(header, value)
self.end_headers()
resp_content = resp.read()
print("Response contents length " + str(resp_content))
self.wfile.write(resp_content)
self.wfile.flush()
except IOError as e:
self.send_error(404, 'error trying to proxy: {}'.format(str(e)))
else:
#self.send_response(200)
#self.end_headers()
#self.wfile.write('sadvd'.encode('utf-8'))
#logger.error("all sent2 %d " % len('sadvd'))
self.serve_assets(self.path[1:])
def do_POST(self):
hostname = os.environ.get("proxy_api_host")
print("Proxying %s" % hostname)
url = 'http://{}{}'.format(hostname, self.path)
req = Request(url=url)
req_headers = self.headers.items()
data_length = 0
print("Getting headers")
for header, value in req_headers:
if str(header).startswith("Host"):
continue
if str(header).startswith("Accept-Encoding"):
continue
if header == "Content-Length":
data_length = int(value) if value else 0
req.add_header(header, value)
print("Reading request %d" % data_length)
request_data = self.rfile.read(data_length)
print("Generating request")
try:
resp = urlopen(req, data=request_data)
print("Response generated")
except urllib.error.HTTPError as e:
if e.getcode():
resp = e
print("Response Error code " + str(e.getcode()))
else:
print("Something went wrong..")
self.send_error(599, u'error proxying: {}'.format(unicode(e)))
return
print("Proxy response code %d" % resp.getcode())
self.send_response(resp.getcode())
respheaders = resp.getheaders()
for header, value in respheaders:
if str(header).startswith("Transfer-Encoding"):
continue
#print(self.path + " RESPH: " + header + " vs " + value)
self.send_header(header, value)
print(self.path + " end headers")
self.end_headers()
data = resp.read();
print(self.path + " response readed")
self.wfile.write(data)
self.wfile.flush()
print(self.path + " flushed")
def serve_assets(self, path):
self.server.assets_handler.handle_request(self, path)
def serve_websocket(self, ws_class, kwargs):
if not self.server.allow_foreign and "Origin" in self.headers:
url = urlparse(self.headers["Origin"])
if url.scheme in ("chrome-extension", "file"):
pass
elif url.hostname not in ('127.0.0.1', '127.0.0.1'):
logger.error("Bad websocket request from %s",
self.headers["Origin"])
self.response_404()
return
if self.server.ws_handler.handle_request(self):
client = self.address_string()
module = ws_class.__name__
logger.debug("%s:%s connected" % (client, module))
ws = ws_class(self.request, client, self.server, self.path,
**kwargs)
if self.path.find('push-studio') != -1:
self.server.set_push_studio_ws(ws)
ws.serve_forever()
logger.debug("%s:%s disconnected" % (client, module))
def response(self, code, message, body):
buf = body.encode()
self.send_response(code, message)
self.send_header('Content-Type', 'text/plain; charset=UTF-8')
self.send_header('Content-Length', len(buf))
if not self.close_connection:
self.send_header('Connection', 'Keep-Alive')
self.end_headers()
self.wfile.write(bytes(buf))
def response_403(self, message="Forbidden", body="Forbidden"):
self.response(403, message, body)
def response_404(self, message="Not Found", body="Not Found"):
self.response(404, message, body)
|
Python
| 0.000001
|
@@ -3164,16 +3164,20 @@
%22 + str(
+len(
resp_con
@@ -3182,16 +3182,17 @@
ontent))
+)
%0A
|
8f815c41b505c01cbc1c57088ddc3a465f1ac07c
|
Add a configuration key for the URL of the Fedora OpenID server
|
fmn/web/default_config.py
|
fmn/web/default_config.py
|
SECRET_KEY = 'changeme please'
# TODO -- May I set this to true?
FAS_OPENID_CHECK_CERT = False
#ADMIN_GROUPS = ['sysadmin-web']
|
Python
| 0
|
@@ -123,8 +123,60 @@
n-web'%5D%0A
+%0AFMN_FEDORA_OPENID = 'https://id.fedoraproject.org'%0A
|
87b6166bb2f88b54c78569d6b566c4d557733c57
|
Modify proxy to use inlineCallbacks
|
proxy.py
|
proxy.py
|
from twisted.internet import endpoints, protocol, reactor
from twisted.protocols import basic
from twisted.web.client import getPage
import time
class ProxyProtocol(basic.LineReceiver):
def gotPage(self, data, line, start):
print 'Fetched {} in {} sec'.format(line, time.time() - start)
self.transport.write(data)
def errGettingPage(self, reason, line):
print 'Error while fetching {}: {}'.format(line, reason.getErrorMessage())
def lineReceived(self, line):
if not line.startswith('http://'):
return
start = time.time()
print 'Fetching {}'.format(line)
d = getPage(line)
d.addCallback(self.gotPage, line, start)
d.addErrback(self.errGettingPage, line)
if __name__ == '__main__':
factory = protocol.ServerFactory()
factory.protocol = ProxyProtocol
endpoints.serverFromString(reactor, 'tcp:8000').listen(factory)
reactor.run()
|
Python
| 0
|
@@ -21,16 +21,23 @@
t import
+ defer,
endpoin
@@ -200,192 +200,209 @@
def
-gotPage(self, data, line, start):%0A print 'Fetched %7B%7D in %7B%7D sec'.format(line, time.time() - start)%0A self.transport.write(data)%0A%0A def errGettingPage(self, reason, line):
+lineReceived(self, line):%0A if not line.startswith('http://'):%0A return%0A%0A self.getPage(line)%0A%0A @defer.inlineCallbacks%0A def getPage(self, line):%0A start = time.time()%0A
%0A
@@ -417,32 +417,16 @@
nt '
-Error while f
+F
etching
- %7B%7D:
%7B%7D'
@@ -441,185 +441,136 @@
line
-, reason.getErrorMessage())%0A%0A def lineReceived(self, line):%0A if not line.startswith('http://'):%0A return%0A%0A start = time.time()%0A print 'F
+)%0A try:%0A data = yield getPage(line)%0A except Exception as e:%0A print 'Error while f
etching
+ %7B%7D:
%7B%7D'
@@ -573,32 +573,35 @@
%7B%7D'.format(line
+, e
)%0A d = ge
@@ -598,122 +598,126 @@
-d = getPage(line)%0A%0A d.addCallback(self.gotPage, line, start)%0A d.addErrback(self.errGettingPage, line
+else:%0A print 'Fetched %7B%7D in %7B%7D sec'.format(line, time.time() - start)%0A self.transport.write(data
)%0A%0Ai
|
714ecf45aaa233d067768de526955a319ff154f4
|
Add annotation
|
nomenklatura/loader.py
|
nomenklatura/loader.py
|
import json
import logging
from nomenklatura.resolver import Resolver
from typing import (
Dict,
Generator,
Generic,
Iterable,
Iterator,
List,
Optional,
Tuple,
TypeVar,
)
from followthemoney.proxy import EntityProxy
from followthemoney.types import registry
from followthemoney.property import Property
from followthemoney import model
from nomenklatura.dataset import Dataset
from nomenklatura.util import PathLike
log = logging.getLogger(__name__)
E = TypeVar("E", bound=EntityProxy)
DS = TypeVar("DS", bound=Dataset)
class Loader(Generic[DS, E]):
"""An abstract base class for implementing"""
def __init__(self, dataset: DS):
self.dataset = dataset
def get_entity(self, id: str) -> Optional[E]:
raise NotImplemented
def get_inverted(self, id: str) -> Generator[Tuple[Property, E], None, None]:
raise NotImplemented
def __iter__(self) -> Iterator[E]:
raise NotImplemented
def __len__(self) -> int:
raise NotImplemented
def get_adjacent(
self, entity: E, inverted: bool = True
) -> Generator[Tuple[Property, E], None, None]:
for prop, value in entity.itervalues():
if prop.type == registry.entity:
child = self.get_entity(value)
if child is not None:
yield prop, child
if inverted:
for prop, adjacent in self.get_inverted(entity.id):
yield prop, adjacent
class MemoryLoader(Loader[DS, E]):
"""Load entities from the given iterable of entities."""
def __init__(
self, dataset: DS, entities: Iterable[E], resolver: Optional[Resolver] = None
) -> None:
super().__init__(dataset)
self.resolver = resolver
self.entities: Dict[str, E] = {}
self.inverted: Dict[str, List[Tuple[Property, str]]] = {}
log.info("Loading %r to memory...", dataset)
for entity in entities:
if self.resolver is not None:
self.resolver.apply(entity)
if entity.id in self.entities:
self.entities[entity.id].merge(entity)
else:
self.entities[entity.id] = entity
for prop, value in entity.itervalues():
if prop.type != registry.entity:
continue
if value not in self.inverted:
self.inverted[value] = []
if prop.reverse is not None:
self.inverted[value].append((prop.reverse, entity.id))
def get_entity(self, id: str) -> Optional[E]:
if self.resolver is not None:
id = self.resolver.get_canonical(id)
return self.entities.get(id)
def get_inverted(self, id: str) -> Generator[Tuple[Property, E], None, None]:
if self.resolver is not None:
id = self.resolver.get_canonical(id)
for prop, entity_id in self.inverted.get(id, []):
entity = self.get_entity(entity_id)
if entity is not None:
yield prop, entity
def __iter__(self) -> Iterator[E]:
return iter(self.entities.values())
def __len__(self) -> int:
return len(self.entities)
def __repr__(self) -> str:
return f"<MemoryLoader({self.dataset!r}, {len(self.entities)})>"
class FileLoader(MemoryLoader[Dataset, EntityProxy]):
"""Read a given file path into an in-memory entity loader."""
def __init__(self, path: PathLike, resolver: Optional[Resolver] = None) -> None:
dataset = Dataset(path.stem, path.stem)
super().__init__(dataset, self.read_file(path), resolver=resolver)
self.path = path
def read_file(self, path: PathLike) -> Generator[EntityProxy, None, None]:
with open(path, "r") as fh:
while True:
line = fh.readline()
if not line:
break
data = json.loads(line)
yield model.get_proxy(data)
def __repr__(self):
return f"<FileLoader({self.path!r}, {len(self.entities)})>"
|
Python
| 0.000002
|
@@ -4027,16 +4027,23 @@
__(self)
+ -%3E str
:%0A
|
860b6a5a645de9aa69cbd61632a20075edac1553
|
Change remove_accents function to normalize back to NFKC
|
normalizr/normalizr.py
|
normalizr/normalizr.py
|
import codecs
import os
import re
import string
import unicodedata
import normalizr.regex as regex
path = os.path.dirname(__file__)
DEFAULT_NORMALIZATIONS = [
'remove_extra_whitespaces', 'replace_punctuation', 'replace_symbols', 'remove_stop_words'
]
class Normalizr:
"""
This class offers methods for text normalization.
Attributes:
language (string): Language used for normalization.
"""
__punctuation = set(string.punctuation)
__stop_words = set()
def __init__(self, language='en'):
self._load_stop_words(language)
def _load_stop_words(self, language):
"""
Load stop words into __stop_words set.
Stop words will be loaded according to the language code received during instantiation.
Params:
language (string): Language code.
"""
with codecs.open(os.path.join(path, 'data/stop-' + language), 'r', 'UTF-8') as file:
for line in file:
fields = line.split('|')
if fields:
for word in fields[0].split(): self.__stop_words.add(word.strip())
def normalize(self, text, normalizations=None):
if normalizations is None:
normalizations = ['whitespaces', 'punctuation', 'symbols', 'stopwords']
methods = {
'accents': self.remove_accent_marks,
'hyphens': self.replace_hyphens,
'punctuation': self.remove_punctuation,
'stopwords': self.remove_stop_words,
'symbols': self.remove_symbols,
'whitespaces': self.remove_extra_whitespaces
}
for normalization in normalizations:
text = methods[normalization](text)
return text
def _parse_normalizations(self, normalizations):
for normalization in normalizations:
if isinstance(normalization, str):
kwargs = {}
else:
normalization, kwargs = normalization
yield (normalization, kwargs)
def normalize(self, text, normalizations=None):
"""
Normalize a given text applying all normalizations.
Normalizations to apply can be specified through a list parameter and will be executed
in the same order.
Params:
text (string): The text to be processed.
normalizations (list): List of normalizations to apply.
Returns:
The text normalized.
"""
for normalization, kwargs in self._parse_normalizations(normalizations or DEFAULT_NORMALIZATIONS):
text = getattr(self, normalization)(text, **kwargs)
return text
def remove_accent_marks(self, text, format='NFKD', excluded=set()):
"""
Remove accent marks from input text.
Params:
text (string): The text to be processed.
format (string): Unicode format.
excluded (set): Set of unicode characters to exclude.
Returns:
The text without accent marks.
"""
return ''.join(c for c in unicodedata.normalize(format, text)
if unicodedata.category(c) != 'Mn' or c in excluded)
def remove_extra_whitespaces(self, text):
"""
Remove extra whitespaces from input text.
This function removes whitespaces from the beginning and the end of
the string, but also duplicated whitespaces between words.
Params:
text (string): The text to be processed.
Returns:
The text without extra whitespaces.
"""
return ' '.join(text.strip().split())
def remove_stop_words(self, text, ignore_case=True):
"""
Remove stop words.
Stop words are loaded on class instantiation according with the specified language.
Params:
text (string): The text to be processed.
ignore_case (boolean): Whether or not ignore case.
Returns:
The text without stop words.
"""
return ' '.join(
word for word in text.split(' ') if (word.lower() if ignore_case else word) not in self.__stop_words)
def replace_emojis(self, text, replacement=''):
"""
Remove emojis from input text or replace them with a string if specified.
Params:
text (string): The text to be processed.
replacement (string): New text that will replace emojis.
Returns:
The text without hyphens.
"""
try:
highpoints = re.compile(u'([\U00002600-\U000027BF])|([\U0001f300-\U0001f64F])|([\U0001f680-\U0001f6FF])')
except re.error:
highpoints = re.compile(u'([\u2600-\u27BF])|([\uD83C][\uDF00-\uDFFF])|([\uD83D][\uDC00-\uDE4F])|([\uD83D][\uDE80-\uDEFF])')
return highpoints.sub(replacement, text)
def replace_hyphens(self, text, replacement=' '):
"""
Replace hyphens from input text with a whitespace or a string if specified.
Params:
text (string): The text to be processed.
replacement (string): New text that will replace hyphens.
Returns:
The text without hyphens.
"""
return text.replace('-', replacement)
def replace_punctuation(self, text, excluded=set(), replacement='',):
"""
Remove punctuation from input text or replace them with a string if specified.
This function will remove characters from string.punctuation.
Params:
text (string): The text to be processed.
excluded (set): Set of characters to exclude.
replacement (string): New text that will replace punctuation.
Returns:
The text without punctuation.
"""
return ''.join(c if c not in self.__punctuation or c in excluded else replacement for c in text)
def replace_symbols(self, text, format='NFKD', excluded=set(), replacement=''):
"""
Remove symbols from input text or replace them with a string if specified.
Params:
text (string): The text to be processed.
format (string): Unicode format.
excluded (set): Set of unicode characters to exclude.
replacement (string): New text that will replace symbols.
Returns:
The text without symbols.
"""
categories = set(['Mn', 'Sc', 'Sk', 'Sm', 'So'])
return ''.join(c if unicodedata.category(c) not in categories or c in excluded else replacement
for c in unicodedata.normalize(format, text))
def replace_urls(self, text, replacement=''):
"""
Remove URLs from input text or replace them with a string if specified.
Params:
text (string): The text to be processed.
replacement (string): New text that will replace URLs.
Returns:
The text without URLs.
"""
return re.sub(regex.URL_REGEX, replacement, text)
|
Python
| 0.000001
|
@@ -2663,17 +2663,16 @@
n text%0A%0A
-%0A
def
@@ -2698,39 +2698,24 @@
(self, text,
- format='NFKD',
excluded=se
@@ -2851,53 +2851,8 @@
ed.%0A
- format (string): Unicode format.%0A
@@ -2978,32 +2978,33 @@
ks.%0A %22%22%22%0A
+%0A
return '
@@ -2993,32 +2993,62 @@
%0A%0A return
+ unicodedata.normalize('NFKC',
''.join(c for c
@@ -3069,30 +3069,30 @@
a.normalize(
-format
+'NFKD'
, text)%0A
@@ -3162,16 +3162,17 @@
xcluded)
+)
%0A%0A de
|
33b0113b0a3b5ea11e15265479cfde168ebd8a48
|
Fix properties of Evaluation when its dates are None
|
indico/modules/events/evaluation/models/evaluations.py
|
indico/modules/events/evaluation/models/evaluations.py
|
# This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from indico.core.db import db
from indico.core.db.sqlalchemy import UTCDateTime
from indico.util.date_time import now_utc
from indico.util.string import return_ascii
from indico.util.struct.enum import IndicoEnum
class EvaluationState(IndicoEnum):
not_ready = 1
ready_to_open = 2
active_and_clean = 3
active_and_answered = 4
finished = 5
class Evaluation(db.Model):
__tablename__ = 'evaluations'
__table_args__ = {'schema': 'events'}
#: The ID of the submission
id = db.Column(
db.Integer,
primary_key=True
)
#: The ID of the event
event_id = db.Column(
db.Integer,
index=True,
nullable=False
)
#: The title of the evaluation
title = db.Column(
db.String,
nullable=False
)
#: The description of the evaluation
description = db.Column(
db.Text,
nullable=False,
default=''
)
#: Whether submissions will not be linked to a user
anonymous = db.Column(
db.Boolean,
nullable=False,
default=False
)
#: Whether submissions must be done by logged users
require_user = db.Column(
db.Boolean,
nullable=False,
default=True
)
#: Datetime when the evaluation is open
start_dt = db.Column(
UTCDateTime,
nullable=True
)
#: Datetime when the evaluation is closed
end_dt = db.Column(
UTCDateTime,
nullable=True
)
#: Whether the evaluation has been marked as deleted
is_deleted = db.Column(
db.Boolean,
nullable=False,
default=False
)
#: The list of submissions
submissions = db.relationship(
'EvaluationSubmission',
cascade='all, delete-orphan',
lazy=True,
backref=db.backref(
'evaluation',
lazy=True
)
)
#: The list of questions
questions = db.relationship(
'EvaluationQuestion',
cascade='all, delete-orphan',
lazy=True,
backref=db.backref(
'evaluation',
lazy=True
)
)
@property
def event(self):
from MaKaC.conference import ConferenceHolder
return ConferenceHolder().getById(str(self.event_id), True)
@event.setter
def event(self, event):
self.event_id = int(event.getId())
@property
def has_ended(self):
return self.end_dt < now_utc()
@property
def has_started(self):
return self.start_dt < now_utc()
@property
def locator(self):
return {'confId': self.event.id,
'evaluation_id': self.id}
@property
def state(self):
if not self.questions:
return EvaluationState.not_ready
if not self.has_started:
return EvaluationState.ready_to_open
if not self.submissions:
return EvaluationState.active_and_clean
if not self.has_ended:
return EvaluationState.active_and_answered
return EvaluationState.finished
@return_ascii
def __repr__(self):
return '<Evaluation({}, {})>'.format(self.id, self.event_id)
|
Python
| 0.999999
|
@@ -3204,24 +3204,40 @@
self.end_dt
+and self.end_dt
%3C now_utc()%0A
@@ -3289,24 +3289,40 @@
return
+self.end_dt and
self.start_d
|
d75e1309bf41f05489ffcf8502309b765bc8c359
|
handle non dev/rc last release (#5133)
|
scripts/update_bokehjs_versions.py
|
scripts/update_bokehjs_versions.py
|
import os
import re
import sys
def check_input(version):
pat = r'^(\d+.\d+.\d+)((dev|rc)\d+)?$'
if not re.match(pat, version):
print("The new version must be in the format X.X.X([dev|rc]X) (ex. '0.12.0')")
return False
return True
def version_update(version, filename):
pat = r"""(release|version)([\" ][:=] [\"\'])(\d+.\d+.\d+)((dev|rc)\d+)?([\"\'])"""
with open(filename) as f:
text = f.read()
match = re.search(pat, text)
if not match:
print("ERROR: Unable to find version string to replace in %s" % filename)
sys.exit(1)
old_version = match.group(3) + match.group(4)
text = re.sub(pat, r'\g<1>\g<2>%s\g<6>' % version, text)
with open(filename, 'w') as f:
f.write(text)
print("Edited {filename}: Updated version string '{old_version}' to '{version}'".format(filename=filename, version=version, old_version=old_version))
if __name__ == '__main__':
if not len(sys.argv) == 2:
print("Please provide the new version number to update.")
sys.exit(1)
version = sys.argv[1]
if not check_input(version):
sys.exit(1)
os.chdir('../')
filenames = [
'bokehjs/src/coffee/version.coffee',
'bokehjs/package.json',
]
for filename in filenames:
version_update(version, filename)
|
Python
| 0
|
@@ -631,10 +631,66 @@
p(3)
+%0A if match.group(4) is not None:%0A old_version
+
+=
mat
|
001924264830761cfa5938ca542201f2e8bdaf66
|
Fix haystack index
|
freieit/search_indexes.py
|
freieit/search_indexes.py
|
from haystack import indexes, site
from .models import ExpertProfile
class ExpertProfileIndex(indexes.SearchIndex):
#text = indexes.CharField(document=True, use_template=True)
text = indexes.EdgeNgramField(document=True, use_template=True)
#name = indexes.CharField(model_attr='name')
#location = indexes.CharField(model_attr='location')
#services = indexes.CharField(model_attr='services')
def get_model(self):
return ExpertProfile
def index_queryset(self):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(available=True)
site.register(ExpertProfile, ExpertProfileIndex)
|
Python
| 0.000607
|
@@ -25,14 +25,8 @@
exes
-, site
%0A%0Afr
@@ -103,16 +103,35 @@
rchIndex
+, indexes.Indexable
):%0A #
@@ -499,24 +499,36 @@
ueryset(self
+, using=None
):%0A %22
@@ -648,55 +648,4 @@
ue)%0A
-%0A%0Asite.register(ExpertProfile, ExpertProfileIndex)%0A
|
270df828dfc76f993a999daeeb8fa8f6c82b1e62
|
Fix typo in documentation
|
lib/cmdlib/query.py
|
lib/cmdlib/query.py
|
#
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
"""Logical units for queries."""
from ganeti import constants
from ganeti import errors
from ganeti import query
from ganeti.cmdlib.backup import ExportQuery
from ganeti.cmdlib.base import NoHooksLU
from ganeti.cmdlib.cluster import ClusterQuery
from ganeti.cmdlib.group import GroupQuery
from ganeti.cmdlib.instance_query import InstanceQuery
from ganeti.cmdlib.misc import ExtStorageQuery
from ganeti.cmdlib.network import NetworkQuery
from ganeti.cmdlib.node import NodeQuery
from ganeti.cmdlib.operating_system import OsQuery
#: Query type implementations
_QUERY_IMPL = {
constants.QR_CLUSTER: ClusterQuery,
constants.QR_INSTANCE: InstanceQuery,
constants.QR_NODE: NodeQuery,
constants.QR_GROUP: GroupQuery,
constants.QR_NETWORK: NetworkQuery,
constants.QR_OS: OsQuery,
constants.QR_EXTSTORAGE: ExtStorageQuery,
constants.QR_EXPORT: ExportQuery,
}
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
def _GetQueryImplementation(name):
"""Returns the implemtnation for a query type.
@param name: Query type, must be one of L{constants.QR_VIA_OP}
"""
try:
return _QUERY_IMPL[name]
except KeyError:
raise errors.OpPrereqError("Unknown query resource '%s'" % name,
errors.ECODE_INVAL)
class LUQuery(NoHooksLU):
"""Query for resources/items of a certain kind.
"""
# pylint: disable=W0142
REQ_BGL = False
def CheckArguments(self):
qcls = _GetQueryImplementation(self.op.what)
self.impl = qcls(self.op.qfilter, self.op.fields, self.op.use_locking)
def ExpandNames(self):
self.impl.ExpandNames(self)
def DeclareLocks(self, level):
self.impl.DeclareLocks(self, level)
def Exec(self, feedback_fn):
return self.impl.NewStyleQuery(self)
class LUQueryFields(NoHooksLU):
"""Query for resources/items of a certain kind.
"""
# pylint: disable=W0142
REQ_BGL = False
def CheckArguments(self):
self.qcls = _GetQueryImplementation(self.op.what)
def ExpandNames(self):
self.needed_locks = {}
def Exec(self, feedback_fn):
return query.QueryFields(self.qcls.FIELDS, self.op.fields)
|
Python
| 0.999937
|
@@ -1776,10 +1776,11 @@
plem
+en
t
-n
atio
|
afc47fd469d7836dcda0eb8bb027cce2a0ed2121
|
Update MergeSort.py
|
fundamentals/MergeSort.py
|
fundamentals/MergeSort.py
|
"""
@author: Maneesh D
@email: maneeshd77@gmail.com
@date: 24/6/17
Merge Sort -> O(nlog n)
"""
from random import randint
from timeit import Timer, default_timer
def merge_sort(data):
if len(data) == 1:
return data
n = len(data)
mid = n // 2
# Divide and sort the sub lists
left = merge_sort(data[:mid])
right = merge_sort(data[mid:])
# Merge
merged = []
left_len = len(left)
right_len = len(right)
i = 0
j = 0
while i < left_len and j < right_len:
if left[i] <= right[j]: # Insert left list element if smaller.
merged.append(left[i])
i += 1
else:
merged.append(right[j]) # Insert right list element if smaller.
j += 1
while i < left_len: # Insert the remaining elements in left if any.
merged.append(left[i])
i += 1
while j < right_len: # Insert the remaining elements in right if any.
merged.append(right[j])
j += 1
return merged
def main():
start = default_timer()
data = [randint(1, 10) + i for i in range(100001)]
merge_sort(data)
print("Sort Time = %f Seconds" % (default_timer() - start))
if __name__ == '__main__':
print("Merge Sort")
print("-" * len("Merge Sort"))
t = Timer(main)
print("\nAverage sorting time for 100000 elements in 10 runs = %f Seconds" % (t.timeit(10) / 10))
|
Python
| 0
|
@@ -61,16 +61,37 @@
4/6/17%0A%0A
+Worst Case Analysis:
Merge So
@@ -1081,25 +1081,8 @@
= %5B
-randint(1, 10) +
i fo
@@ -1103,11 +1103,57 @@
0000
-1)%5D
+0, 0, -1)%5D # Worst Case Input (Reverse Sorted)
%0A
|
38c96a366b68cd74cbec6e69ca168225ccf3fe18
|
Patch for an Issue #260
|
lib/core/convert.py
|
lib/core/convert.py
|
#!/usr/bin/env python
"""
Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
try:
import hashlib
except:
import md5
import sha
import pickle
import re
import sys
import struct
import urllib
from lib.core.enums import PLACE
from lib.core.settings import IS_WIN
from lib.core.settings import UNICODE_ENCODING
def base64decode(value):
return value.decode("base64")
def base64encode(value):
return value.encode("base64")[:-1].replace("\n", "")
def base64pickle(value):
return base64encode(pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
def base64unpickle(value):
return pickle.loads(base64decode(value))
def hexdecode(value):
value = value.lower()
return (value[2:] if value.startswith("0x") else value).decode("hex")
def hexencode(value):
return utf8encode(value).encode("hex")
def md5hash(value):
if sys.modules.has_key('hashlib'):
return hashlib.md5(value).hexdigest()
else:
return md5.new(value).hexdigest()
def orddecode(value):
packedString = struct.pack("!"+"I" * len(value), *value)
return "".join(chr(char) for char in struct.unpack("!"+"I"*(len(packedString)/4), packedString))
def ordencode(value):
return tuple(ord(char) for char in value)
def sha1hash(value):
if sys.modules.has_key('hashlib'):
return hashlib.sha1(value).hexdigest()
else:
return sha.new(value).hexdigest()
def unicodeencode(value, encoding=None):
"""
Return 8-bit string representation of the supplied unicode value:
>>> unicodeencode(u'test')
'test'
"""
retVal = value
if isinstance(value, unicode):
try:
retVal = value.encode(encoding or UNICODE_ENCODING)
except UnicodeEncodeError:
retVal = value.encode(UNICODE_ENCODING, "replace")
return retVal
def utf8encode(value):
return unicodeencode(value, "utf-8")
def utf8decode(value):
return value.decode("utf-8")
def htmlescape(value):
codes = (('&', '&'), ('<', '<'), ('>', '>'), ('"', '"'), ("'", '''), (' ', ' '))
return reduce(lambda x, y: x.replace(y[0], y[1]), codes, value)
def htmlunescape(value):
retVal = value
if value and isinstance(value, basestring):
codes = (('<', '<'), ('>', '>'), ('"', '"'), (' ', ' '), ('&', '&'))
retVal = reduce(lambda x, y: x.replace(y[0], y[1]), codes, retVal)
return retVal
def singleTimeWarnMessage(message): # Cross-linked function
pass
def stdoutencode(data):
retVal = None
try:
# Reference: http://bugs.python.org/issue1602
if IS_WIN:
output = data.encode('ascii', "replace")
if output != data:
warnMsg = "cannot properly display Unicode characters "
warnMsg += "inside Windows OS command prompt "
warnMsg += "(http://bugs.python.org/issue1602). All "
warnMsg += "unhandled occurances will result in "
warnMsg += "replacement with '?' character. Please, find "
warnMsg += "proper character representation inside "
warnMsg += "corresponding output files. "
singleTimeWarnMessage(warnMsg)
retVal = output
else:
retVal = data.encode(sys.stdout.encoding)
except:
retVal = data.encode(UNICODE_ENCODING)
return retVal
|
Python
| 0
|
@@ -558,19 +558,295 @@
%0A ret
-urn
+Val = None%0A try:%0A retVal = base64encode(pickle.dumps(value, pickle.HIGHEST_PROTOCOL))%0A except:%0A warnMsg = %22problem occurred while serializing %22%0A warnMsg += %22instance of a type '%25s'%22 %25 type(value)%0A singleTimeWarnMessage(warnMsg)%0A%0A retVal =
base64e
@@ -856,37 +856,42 @@
de(pickle.dumps(
+str(
value
+)
, pickle.HIGHEST
@@ -901,16 +901,34 @@
OTOCOL))
+%0A return retVal
%0A%0Adef ba
|
bebbbed6dba82329fcaab32fdb0109ec78cd7ad9
|
Use correct subprotocol
|
ztag/transforms/s7.py
|
ztag/transforms/s7.py
|
from ztag.transform import *
from ztag import protocols, errors
class S7Transform(ZGrabTransform):
name = "s7/status"
port = 102
protocol = protocols.S7
subprotocol = protocols.S7.STATUS
def _transform_object(self, obj):
zout = ZMapTransformOutput()
wrapped = Transformable(obj)
s = wrapped['data']['s7']
if not s['is_s7'].resolve() or not s.resolve():
raise errors.IgnoreObject()
out = s.resolve()
out['support'] = True
del out['is_s7']
zout.transformed = out
return zout
|
Python
| 0.024217
|
@@ -197,13 +197,10 @@
S7.S
-TATUS
+ZL
%0A%0A%0A
|
d16d61c1d3a9eaaef3e4673205a42a9dd010900a
|
Replace Unwrapped with Value on proto method names (#2283)
|
synth.py
|
synth.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""This script is used to synthesize generated parts of this library."""
import os
import synthtool as s
import synthtool.gcp as gcp
import logging
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
common = gcp.CommonTemplates()
v1_library = gapic.php_library(
service='container',
version='v1',
config_path='/google/container/artman_container_v1.yaml',
artman_output_name='google-cloud-container-v1')
# copy all src including partial veneer classes
s.move(v1_library / 'src')
# copy proto files to src also
s.move(v1_library / 'proto/src/Google/Cloud/Container', 'src/')
s.move(v1_library / 'tests/')
# copy GPBMetadata file to metadata
s.move(v1_library / 'proto/src/GPBMetadata/Google/Container', 'metadata/')
# document and utilize apiEndpoint instead of serviceAddress
s.replace(
"**/Gapic/*GapicClient.php",
r"'serviceAddress' =>",
r"'apiEndpoint' =>")
s.replace(
"**/Gapic/*GapicClient.php",
r"@type string \$serviceAddress\n\s+\*\s+The address",
r"""@type string $serviceAddress
* **Deprecated**. This option will be removed in a future major release. Please
* utilize the `$apiEndpoint` option instead.
* @type string $apiEndpoint
* The address""")
s.replace(
"**/Gapic/*GapicClient.php",
r"\$transportConfig, and any \$serviceAddress",
r"$transportConfig, and any `$apiEndpoint`")
# prevent proto messages from being marked final
s.replace(
"src/V*/**/*.php",
r"final class",
r"class")
# fix year
s.replace(
'**/Gapic/*GapicClient.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
'**/V1/ClusterManagerClient.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
'tests/**/V1/*Test.php',
r'Copyright \d{4}',
'Copyright 2018')
# Fix class references in gapic samples
for version in ['V1']:
pathExpr = 'src/' + version + '/Gapic/ClusterManagerGapicClient.php'
types = {
'new Cluster': r'new Google\\Cloud\\Container\\'+ version + r'\\Cluster',
'new NodePoolAutoscaling': r'new Google\\Cloud\\Container\\'+ version + r'\\NodePoolAutoscaling',
'new AddonsConfig': r'new Google\\Cloud\\Container\\'+ version + r'\\AddonsConfig',
'= Action::': r'= Google\\Cloud\\Container\\'+ version + r'\\SetMasterAuthRequest\\Action::',
'new MasterAuth': r'new Google\\Cloud\\Container\\'+ version + r'\\MasterAuth',
'new NodePool': r'new Google\\Cloud\\Container\\'+ version + r'\\NodePool',
'new NodeManagement': r'new Google\\Cloud\\Container\\'+ version + r'\\NodeManagement',
'new NetworkPolicy': r'new Google\\Cloud\\Container\\'+ version + r'\\NetworkPolicy',
'new MaintenancePolicy': r'new Google\\Cloud\\Container\\'+ version + r'\\MaintenancePolicy',
}
for search, replace in types.items():
s.replace(
pathExpr,
search,
replace
)
|
Python
| 0
|
@@ -2112,16 +2112,179 @@
lass%22)%0A%0A
+# Replace %22Unwrapped%22 with %22Value%22 for method names.%0As.replace(%0A %22src/V*/**/*.php%22,%0A r%22public function (%5Cw%7B0,%7D)Unwrapped%22,%0A r%22public function %5C1Value%22%0A)%0A%0A
# fix ye
|
0cd617ddc7e6303139583b6a92e90cfac1e91b31
|
set AUTOSYNTH_MULTIPLE_COMMITS=true for context aware commits (#938)
|
synth.py
|
synth.py
|
import synthtool as s
import synthtool.gcp as gcp
import logging
import subprocess
import os
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
common_templates = gcp.CommonTemplates()
# tasks has two product names, and a poorly named artman yaml
version = 'v1'
library = gapic.node_library(
'pubsub', version, config_path="/google/pubsub/artman_pubsub.yaml")
# skip index, protos, package.json, and README.md
s.copy(
library,
excludes=['package.json', 'README.md', 'src/index.js'])
templates = common_templates.node_library(source_location='build/src')
s.copy(templates)
# https://github.com/googleapis/gapic-generator/issues/2127
s.replace("src/v1/subscriber_client.js",
" }\n\s*/\*\*\n\s+\* The DNS address for this API service\.",
"\n // note: editing generated code\n"
" this.waitForReady = function(deadline, callback) {\n"
" return subscriberStub.then(\n"
" stub => stub.waitForReady(deadline, callback),\n"
" callback\n"
" );\n"
" };\n"
" this.getSubscriberStub = function() {\n"
" return subscriberStub;\n"
" };\n"
"\g<0>")
# Update path discovery due to build/ dir and TypeScript conversion.
s.replace("src/v1/publisher_client.js", "../../package.json", "../../../package.json")
s.replace("src/v1/subscriber_client.js", "../../package.json", "../../../package.json")
# [START fix-dead-link]
s.replace('src/**/doc/google/protobuf/doc_timestamp.js',
'https:\/\/cloud\.google\.com[\s\*]*http:\/\/(.*)[\s\*]*\)',
r"https://\1)")
s.replace('src/**/doc/google/protobuf/doc_timestamp.js',
'toISOString\]',
'toISOString)')
# [END fix-dead-link]
# No browser support for TypeScript libraries yet
os.unlink('webpack.config.js')
os.unlink('src/browser.js')
# Node.js specific cleanup
subprocess.run(['npm', 'install'])
subprocess.run(['npm', 'run', 'fix'])
subprocess.run(['npx', 'compileProtos', 'src'])
|
Python
| 0
|
@@ -129,16 +129,52 @@
DEBUG)%0A%0A
+AUTOSYNTH_MULTIPLE_COMMITS = True%0A%0A%0A
gapic =
|
b3b93f642f88e5f00d22d07fccc9bab1f16ca564
|
exclude Bundle Proto from Synthtool run (#377)
|
synth.py
|
synth.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.java as java
AUTOSYNTH_MULTIPLE_COMMITS = True
gapic = gcp.GAPICBazel()
protobuf_header = "// Generated by the protocol buffer compiler. DO NOT EDIT!"
# License header
license_header = """/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, 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.
*/
"""
bad_license_header = """/\\*
\\* Copyright 2018 Google LLC
\\*
\\* Licensed under the Apache License, Version 2.0 \\(the "License"\\); you may not use this file except
\\* in compliance with the License. You may obtain a copy of the License at
\\*
\\* 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.
\\*/
"""
def generate_client(service, version, proto_path=None, bazel_target=None, package=None, include_gapic=True):
library = gapic.java_library(
service=service,
version=version,
proto_path=proto_path if proto_path else f'google/{service}/{version}',
bazel_target=bazel_target if bazel_target else f'//google/{service}/{version}:google-cloud-{service}-{version}-java',
)
library = library / f"google-cloud-{service}-{version}-java"
s.replace(
library / f'proto-google-cloud-{service}-{version}-java/src/**/*.java',
protobuf_header,
f'{license_header}{protobuf_header}'
)
if service == "firestore-admin":
s.replace(
library / f'grpc-google-cloud-{service}-{version}-java/src/**/*.java',
bad_license_header,
license_header
)
s.replace(
library / f'proto-google-cloud-{service}-{version}-java/src/**/*.java',
bad_license_header,
license_header
)
pkg = package if package else f'com.google.{service}.{version}'
s.replace(
library / f'grpc-google-cloud-{service}-{version}-java/src/**/*.java',
f'package {pkg};',
f'{license_header}package {pkg};'
)
s.copy(library / f'grpc-google-cloud-{service}-{version}-java/src', f'grpc-google-cloud-{service}-{version}/src')
s.copy(library / f'proto-google-cloud-{service}-{version}-java/src', f'proto-google-cloud-{service}-{version}/src')
java.format_code(f'grpc-google-cloud-{service}-{version}/src')
java.format_code(f'proto-google-cloud-{service}-{version}/src')
if include_gapic and service == "firestore-admin":
s.copy(library / f'gapic-google-cloud-{service}-{version}-java/src', 'google-cloud-firestore-admin/src')
java.format_code(f'google-cloud-firestore-admin/src')
else:
s.copy(library / f'gapic-google-cloud-{service}-{version}-java/src', 'google-cloud-firestore/src')
java.format_code(f'google-cloud-firestore/src')
return library
admin_v1 = generate_client(
service='firestore-admin',
version='v1',
proto_path='google/firestore/admin/v1',
bazel_target='//google/firestore/admin/v1:google-cloud-firestore-admin-v1-java',
package='com.google.firestore.admin.v1',
include_gapic=True
)
firestore_v1 = generate_client(
service='firestore',
version='v1',
include_gapic=True
)
bundle_v1 = generate_client(
service='firestore-bundle',
version='v1',
proto_path='firestore',
bazel_target='//firestore:google-cloud-firestore-bundle-v1-java',
)
java.common_templates(excludes=[
# firestore uses a different project for its integration tests
# due to the default project running datastore
'.kokoro/presubmit/integration.cfg',
'.kokoro/presubmit/samples.cfg',
'.kokoro/nightly/integration.cfg',
'.kokoro/nightly/samples.cfg'
])
|
Python
| 0
|
@@ -4485,16 +4485,178 @@
True%0A)%0A%0A
+# TODO(wu-hui): Add %60bundle.proto%60 to googleapis/googleapis.%0A# The target below points to a local file, but synthtool only works against the%0A# googleapis repo.%0A#
bundle_v
@@ -4668,32 +4668,34 @@
enerate_client(%0A
+#
service='fir
@@ -4706,24 +4706,26 @@
re-bundle',%0A
+#
version=
@@ -4722,36 +4722,38 @@
version='v1',%0A
+#
+
proto_path='fire
@@ -4756,24 +4756,26 @@
firestore',%0A
+#
bazel_ta
@@ -4832,16 +4832,18 @@
-java',%0A
+#
)%0A%0Ajava.
|
92771ac9fbe49b5bbf0ed2c178d930a374d42b6f
|
enable context aware commits (#93)
|
synth.py
|
synth.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.java as java
gapic = gcp.GAPICBazel()
service = 'devtools-clouderrorreporting'
versions = ['v1beta1']
ERROR_GROUP_OVERLOAD = """
// Inserted by synthtool to preserve backwards-compatibility
/**
* Get the specified group.
*
* <p>Sample code:
*
* <pre><code>
* try (ErrorGroupServiceClient errorGroupServiceClient = ErrorGroupServiceClient.create()) {
* GroupName groupName = GroupName.of("[PROJECT]", "[GROUP]");
* ErrorGroup response = errorGroupServiceClient.getGroup(groupName);
* }
* </code></pre>
*
* @param groupName Required. The group resource name. Written as
* <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
* Call <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
* <code>groupStats.list</code></a> to return a list of groups belonging to
* this project.
* <p>Example: <code>projects/my-project-123/groups/my-group</code>
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
* @deprecated Use ErrorGroupServiceClient#getGroup(ErrorGroupName)
*/
@Deprecated
public final ErrorGroup getGroup(GroupName groupName) {
GetGroupRequest request =
GetGroupRequest.newBuilder()
.setGroupName(groupName == null ? null : groupName.toString())
.build();
return getGroup(request);
}
"""
ERROR_GROUP_OVERLOAD_PREVIOUS_METHOD = r'(\s+public ErrorGroupServiceStub getStub\(\) {\n\s+return stub;\n\s+})'
for version in versions:
library = gapic.java_library(
service=service,
version=version,
proto_path=f'google/devtools/clouderrorreporting/{version}',
bazel_target=f'//google/devtools/clouderrorreporting/{version}:google-cloud-{service}-{version}-java',
)
library = library / f"google-cloud-{service}-{version}-java"
java.fix_proto_headers(library / f'proto-google-cloud-{service}-{version}-java')
java.fix_grpc_headers(library / f'grpc-google-cloud-{service}-{version}-java', "")
s.replace(
library / f'gapic-google-cloud-{service}-{version}-java/src/**/ErrorGroupServiceClient.java',
ERROR_GROUP_OVERLOAD_PREVIOUS_METHOD,
"\g<1>\n\n" + ERROR_GROUP_OVERLOAD
)
s.replace(
library / f'gapic-google-cloud-{service}-{version}-java/src/**/ErrorGroupServiceClient.java',
"import com.google.devtools.clouderrorreporting.v1beta1.ErrorGroupName;",
"import com.google.devtools.clouderrorreporting.v1beta1.ErrorGroupName;\nimport com.google.devtools.clouderrorreporting.v1beta1.GroupName;"
)
s.copy(library / f'gapic-google-cloud-{service}-{version}-java/src', f'google-cloud-errorreporting/src')
s.copy(library / f'grpc-google-cloud-{service}-{version}-java/src', f'grpc-google-cloud-error-reporting-{version}/src')
s.copy(library / f'proto-google-cloud-{service}-{version}-java/src', f'proto-google-cloud-error-reporting-{version}/src')
java.format_code(f'google-cloud-errorreporting/src')
java.format_code(f'grpc-google-cloud-error-reporting-{version}/src')
java.format_code(f'proto-google-cloud-error-reporting-{version}/src')
java.common_templates()
|
Python
| 0
|
@@ -733,16 +733,51 @@
s java%0A%0A
+AUTOSYNTH_MULTIPLE_COMMITS = True%0A%0A
gapic =
|
59860336a32b4cb438d275ced06a3100a2dd78b6
|
Update synth.py
|
synth.py
|
synth.py
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""This script is used to synthesize generated parts of this library."""
import synthtool.languages.java as java
java.common_templates()
|
Python
| 0
|
@@ -8,17 +8,17 @@
ight 202
-0
+1
Google
@@ -706,8 +706,9 @@
plates()
+%0A
|
171950f63b6a1bc1bdb60b10c25f529e51dbfe8b
|
Split up dev and static servers
|
tasks.py
|
tasks.py
|
from glob import glob
from invoke import task
@task(aliases=['dev-server'])
def dev_server(ctx, pty=True):
"""Run django dev server and servers for static files."""
ctx.run('python manage.py runserver | npm run watch-static', pty=pty)
@task
def build(ctx):
"""Build docs, static-files, etc."""
ctx.run("sphinx-build docs docs/_build")
ctx.run("npm run build-static")
@task
def storybook(ctx):
"""Start react storybook server for developing & testing UI components."""
ctx.run("npm run storybook")
@task
def test(ctx, coverage=True, backend=True, frontend=True, acceptance=False, pty=True):
"""Run automated tests.
By default acceptance tests are not run. Add `--acceptance` flag to include those tests.
"""
if backend:
test_cmd = 'pytest'
test_cmd += ' --cov=scrappyr --cov-report term-missing' if coverage else ''
test_cmd += ' scrappyr' # Root application directory
print_header('Backend tests')
ctx.run(test_cmd, pty=pty)
if frontend:
print_header('Frontend tests')
ctx.run('npm test', pty=pty)
if acceptance:
print_header('Acceptance tests')
# Skip acceptance test directory if `acceptance` is False.
ctx.run('pytest acceptance_tests', pty=pty)
@task
def check(ctx, pty=True):
"""Run code quality checks."""
print_header('Django check')
ctx.run('python manage.py check', pty=pty)
print_header('Flake8')
ctx.run('flake8', pty=pty)
print_header('eslint')
js_files = ' '.join(glob('scrappyr/static/js/**/*.js', recursive=True))
ctx.run(f'./node_modules/.bin/eslint -c .eslintrc {js_files}', pty=pty)
@task
def createapp(ctx, app):
ctx.run('mkdir scrappyr/{}'.format(app))
ctx.run('python manage.py startapp {0} scrappyr/{0}'.format(app))
@task
def clean(ctx, docs=True, bytecode=True, static_files=True, node_modules=True, extra=''):
"""Remove build files.
This command removes:
- Documentation built by Sphinx
- *.pyc files
"""
patterns = ['build']
if docs:
patterns.append('docs/_build')
if bytecode:
patterns.append('**/*.pyc')
patterns.append('`find . -name __pycache__ -type d`')
if static_files:
patterns.append('scrappyr/static/webpack_bundles/')
if node_modules:
patterns.append('node_modules/*')
if extra:
patterns.append(extra)
for pattern in patterns:
ctx.run('rm -rf {0}'.format(pattern))
@task(aliases=['graph-models'])
def graph_models(ctx):
"""Create ./scrappyr-models.pdf file displaying visualization of Django models"""
ctx.run('python manage.py graph_models -ag -o scrappyr-models.pdf')
def print_header(title):
print()
print(title)
print('-' * len(title))
|
Python
| 0
|
@@ -135,12 +135,143 @@
rver
- and
+.%22%22%22%0A ctx.run('python manage.py runserver', pty=pty)%0A%0A%0A@task(aliases=%5B'static-server'%5D)%0Adef static_server(ctx, pty=True):%0A %22%22%22Run
ser
@@ -313,37 +313,8 @@
un('
-python manage.py runserver %7C
npm
|
0e8994d1dbeb6266156fa9615fc003aa0d0a4822
|
remove unused import, flake8
|
tasks.py
|
tasks.py
|
# -*- coding: utf-8 -*-
import os
import sys
from invoke import task, run
from waterbutler import settings
@task
def install(upgrade=False, pip_cache=None, wheel_repo=None):
cmd = 'pip install -r dev-requirements.txt'
if upgrade:
cmd += ' --upgrade'
if pip_cache:
cmd += ' --download-cache={}'.format(pip_cache)
if wheel_repo:
run('pip install wheel', pty=True)
# get the current python version, expected git branch name
ver = '.'.join([str(i) for i in sys.version_info[0:2]])
name = 'wheelhouse-{}'.format(ver)
ext = '.zip'
url = '{}/archive/{}{}'.format(wheel_repo, ver, ext)
# download and extract the wheelhouse github repository archive
run('curl -o {}{} -L {}'.format(name, ext, url), pty=True)
run('unzip {}{}'.format(name, ext, name), pty=True)
# run pip install w/ the wheelhouse dependencies available
run(cmd + ' --use-wheel --find-links={}'.format(name), pty=True)
# cleanup wheelhouse-{ver} folder and wheelhouse-{ver}{ext} file
run('rm -rf {}'.format(name), pty=True)
run('rm -f {}{}'.format(name, ext), pty=True)
else:
run(cmd, pty=True)
@task
def flake():
run('flake8 .')
@task
def test():
cmd = 'py.test --cov-report term-missing --cov waterbutler tests'
run(cmd, pty=True)
@task
def tornado(port=settings.PORT, address=settings.ADDRESS, debug=settings.DEBUG):
from waterbutler.server import serve
serve(port, address, debug)
|
Python
| 0
|
@@ -22,18 +22,8 @@
*-%0A%0A
-import os%0A
impo
|
ca78234cc9bebd3901750e913d87e7f63ebcd7f0
|
test 42
|
tasks.py
|
tasks.py
|
"""
QED celery instance
"""
from __future__ import absolute_import
import os
import logging
import redis
import json
import uuid
from celery import Celery
from flask import request, Response
from flask_restful import Resource
logging.getLogger('celery.task.default').setLevel(logging.DEBUG)
logging.getLogger().setLevel(logging.DEBUG)
try:
from ubertool_ecorest.ubertool.ubertool.sam import sam_exe as sam
from ubertool_ecorest.REST_UBER import rest_model_caller, rest_validation
except:
logging.info("SAM Task except import attempt..")
from ubertool.ubertool.sam import sam_exe as sam
from REST_UBER import rest_model_caller, rest_validation
logging.info("SAM Task except import complete!")
from temp_config.set_environment import DeployEnv
runtime_env = DeployEnv()
runtime_env.load_deployment_environment()
redis_hostname = os.environ.get('REDIS_HOSTNAME')
redis_port = os.environ.get('REDIS_PORT')
REDIS_HOSTNAME = os.environ.get('REDIS_HOSTNAME')
if not os.environ.get('REDIS_HOSTNAME'):
os.environ.setdefault('REDIS_HOSTNAME', 'redis')
REDIS_HOSTNAME = os.environ.get('REDIS_HOSTNAME')
logging.info("REDIS HOSTNAME: {}".format(REDIS_HOSTNAME))
redis_conn = redis.StrictRedis(host=REDIS_HOSTNAME, port=6379, db=0)
#app = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0',)
app = Celery('tasks', broker='redis://redis:6379/0', backend='redis://redis:6379/0',)
app.conf.update(
CELERY_ACCEPT_CONTENT=['json'],
CELERY_TASK_SERIALIZER='json',
CELERY_RESULT_SERIALIZER='json',
CELERY_IGNORE_RESULT=False,
CELERY_TRACK_STARTED=True,
)
class SamStatus(Resource):
def get(self, task_id):
"""
SAM task status
:param jobId:
:return:
"""
logging.info("SAM task status request received for task: {}".format(str(task_id)))
task = {}
try:
task = sam_status(task_id)
logging.info("SAM task id: " + task_id + " status: " + task['status'])
except Exception as ex:
task['status'] = str(ex)
logging.info("SAM task status request error: " + str(ex))
resp_body = json.dumps({'task_id': task_id, 'task_status': task['status']})
response = Response(resp_body, mimetype='application/json')
return response
class SamRun(Resource):
def post(self, jobId="000000100000011"):
"""
SAM post handler.
:param jobId:
:return:
"""
logging.info("SAM task start request with inputs: {}".format(str(request.form)))
indexed_inputs = {}
# TODO: set based on env variable
use_celery = False
# index the input dictionary
for k, v in request.form.items():
indexed_inputs[k] = {"0": v}
valid_input = {"inputs": indexed_inputs, "run_type": "single"}
if use_celery:
# SAM Run with celery
try:
task_id = sam_run.apply_async(args=(jobId, valid_input["inputs"]), queue="sam", taskset_id=jobId)
logging.info("SAM celery task initiated with task id:{}".format(task_id))
resp_body = json.dumps({'task_id': str(task_id.id)})
except Exception as ex:
logging.info("SAM celery task failed: " + str(ex))
resp_body = json.dumps({'task_id': "1234567890"})
else:
# SAM Run without celery
task_id = uuid.uuid4()
sam_run(task_id, valid_input["inputs"])
logging.info("SAM flask task completed with task id:{}".format(task_id))
resp_body = json.dumps({'task_id': str(task_id)})
response = Response(resp_body, mimetype='application/json')
return response
class SamData(Resource):
def get(self, task_id):
dir_path = os.getcwd()
logging.info("SAM data request for task id: {}".format(task_id))
file_path = './ubertool/ubertool/sam/bin/Results/' + str(task_id) + '/out_json.csv'
try:
logging.info("SAM data request file path: {}".format(file_path))
with open(file_path, 'rb') as data:
data_json = data.read()
data_json = json.dumps(json.loads(data_json))
except FileNotFoundError as er:
logging.info("SAM data file not found, data request not successful.")
return "{'error': 'data file not found', 'file_path': " + str(file_path) + "}"
logging.info("SAM data file found, data request successful.")
return Response(data_json, mimetype='application/json')
@app.task(name='tasks.sam_run', bind=True, ignore_result=False)
def sam_run(self, jobID, inputs):
if sam_run.request.id is not None:
task_id = sam_run.request.id
else:
task_id = jobID
logging.info("SAM CELERY task id: {}".format(task_id))
logging.info("SAM CELERY task starting...")
inputs["csrfmiddlewaretoken"] = {"0": task_id}
# Commented out model call for celery connection testing
rest_model_caller.model_run("sam", task_id, inputs, module=sam)
# logging.info("SAM CELERY task test answer is: 42")
logging.info("SAM CELERY task completed.")
def sam_status(task_id):
task = app.AsyncResult(task_id)
return {"status": task.status}
|
Python
| 0.000002
|
@@ -5026,16 +5026,17 @@
ing%0A
+#
rest_mod
@@ -5094,18 +5094,16 @@
sam)%0A
- #
logging
|
fd9ef4b30ef09d52c120e9e8ab2461cbce939dfd
|
Add --show-diff-on-failure
|
tasks.py
|
tasks.py
|
# -*- coding: utf-8 -*-
import os
import sys
import webbrowser
from invoke import task
docs_dir = 'docs'
build_dir = os.path.join(docs_dir, '_build')
@task
def test(ctx, watch=False, last_failing=False):
"""Run the tests.
Note: --watch requires pytest-xdist to be installed.
"""
import pytest
syntax(ctx)
args = []
if watch:
args.append('-f')
if last_failing:
args.append('--lf')
args.append('tests')
retcode = pytest.main(args)
sys.exit(retcode)
@task
def syntax(ctx):
"""Run flake8 on codebase."""
ctx.run('pre-commit run --all-files', echo=True)
@task
def watch(ctx):
"""Run tests when a file changes. Requires pytest-xdist."""
import pytest
errcode = pytest.main(['-f'])
sys.exit(errcode)
@task
def clean(ctx):
ctx.run('rm -rf build')
ctx.run('rm -rf dist')
ctx.run('rm -rf apispec.egg-info')
clean_docs(ctx)
print('Cleaned up.')
@task
def clean_docs(ctx):
ctx.run('rm -rf %s' % build_dir)
@task
def browse_docs(ctx):
path = os.path.join(build_dir, 'index.html')
webbrowser.open_new_tab(path)
def build_docs(ctx, browse):
ctx.run('sphinx-build %s %s' % (docs_dir, build_dir), echo=True)
if browse:
browse_docs(ctx)
@task
def docs(ctx, clean=False, browse=False, watch=False):
"""Build the docs."""
if clean:
clean_docs(ctx)
if watch:
watch_docs(ctx, browse=browse)
else:
build_docs(ctx, browse=browse)
@task
def watch_docs(ctx, browse=False):
"""Run build the docs when a file changes."""
try:
import sphinx_autobuild # noqa
except ImportError:
print('ERROR: watch task requires the sphinx_autobuild package.')
print('Install it with:')
print(' pip install sphinx-autobuild')
sys.exit(1)
ctx.run(
'sphinx-autobuild {0} {1} {2} -z apispec'.format(
'--open-browser' if browse else '', docs_dir, build_dir,
), echo=True, pty=True,
)
@task
def readme(ctx, browse=False):
ctx.run('rst2html.py README.rst > README.html')
if browse:
webbrowser.open_new_tab('README.html')
|
Python
| 0.000107
|
@@ -601,16 +601,39 @@
ll-files
+ --show-diff-on-failure
', echo=
|
59c9e30df3397a9114a59cc8a318cf011ba04085
|
fix terminal size formatting
|
.util/cliformatting.py
|
.util/cliformatting.py
|
import os
import sys
import click
from math import ceil
import shutil
rows, columns = shutil.get_terminal_size()
RESULTS = {"success": 0, "failure": 0}
def header(msg):
click.secho(f"\n# {msg}", bold=True)
def s(n):
if n == 1:
return ""
return "s"
def error(s, details=None):
lineart = "********************************"
click.secho(f"{lineart}\nError {s}", bold=True, fg="red")
if details:
click.echo(details)
click.secho(f"{lineart}", bold=True, fg="red")
def echo(msg, indent=""):
click.echo(f"{indent}{msg}")
def summary():
total = RESULTS["success"] + RESULTS["failure"]
fails = RESULTS["failure"]
if fails != 0:
failcol = {"bold": True, "fg": "red"}
else:
failcol = {}
click.echo(
(
click.style(
f"\nResults: {total} check{s(total)}, ",
bold=True,
)
+ click.style(f"{fails} failure{s(fails)}", **failcol)
+ click.style(".", bold=True)
)
)
if fails == 0:
sys.exit(0)
else:
sys.exit(1)
def result(msg, success=True, details=None):
if success:
success_message = "PASS"
fg = "green"
RESULTS["success"] += 1
else:
success_message = "FAIL"
fg = "red"
RESULTS["failure"] += 1
# overflow math. 7 is the result length ("[FASL] ")
amsg = msg.ljust(ceil((len(msg) + 7) / columns) * columns - 7)
click.echo(amsg + click.style(f"[{success_message}]", fg=fg, bold=True))
if details and not success:
click.echo(details)
"""
Usage:
header("Testing the things")
result("I did a thing")
result("I failed a thing", success=False, details="how to fix the issue")
summary()
"""
|
Python
| 0.000007
|
@@ -68,21 +68,18 @@
il%0A%0A
-rows,
columns
+, _
= s
|
7b8b4c7f76c4623ee58fc7a05aee8a8d62d99b89
|
Improve init
|
polyaxon_cli/cli/init.py
|
polyaxon_cli/cli/init.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import os
import sys
import click
import clint
from polyaxon_cli.cli.getters.project import get_project_or_local
from polyaxon_cli.client import PolyaxonClient
from polyaxon_cli.client.exceptions import PolyaxonHTTPError, PolyaxonShouldExitError
from polyaxon_cli.logger import clean_outputs
from polyaxon_cli.managers.ignore import IgnoreManager
from polyaxon_cli.managers.project import ProjectManager
from polyaxon_cli.schemas.polyaxonfile import PolyaxonFile
from polyaxon_cli.utils import constants
from polyaxon_cli.utils.files import create_init_file
from polyaxon_cli.utils.formatting import Printer
from polyaxon_client.exceptions import PolyaxonClientException
def create_polyaxonfile():
if os.path.isfile(constants.INIT_FILE):
try:
_ = PolyaxonFile(constants.INIT_FILE).specification
Printer.print_success(
"A valid polyaxonfile.yaml was found in the project.".format(constants.INIT_FILE))
except Exception as e:
Printer.print_error("A Polyaxonfile was found but it is not valid.", add_sign=True)
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
else:
create_init_file(constants.INIT_FILE_RUN)
# if we are here the file was not created
if not os.path.isfile(constants.INIT_FILE):
Printer.print_error(
"Something went wrong, init command did not create a file.\n"
"Possible reasons: you don't have enough rights to create the file.")
sys.exit(1)
Printer.print_success("{} was created successfully.".format(constants.INIT_FILE))
@click.command()
@click.argument('project', type=str)
@click.option('--polyaxonfile', is_flag=True, default=False, show_default=False,
help='Init a polyaxon file with `exec` step template.')
@clean_outputs
def init(project, polyaxonfile):
"""Initialize a new polyaxonfile specification."""
user, project_name = get_project_or_local(project)
try:
project_config = PolyaxonClient().project.get_project(user, project_name)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Make sure you have a project with this name `{}`'.format(project))
Printer.print_error(
'You can a create new project with this command: '
'polyaxon project create '
'--name={} [--description=...] [--tags=...]'.format(project_name))
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
init_project = False
if ProjectManager.is_initialized():
local_project = ProjectManager.get_config()
click.echo('Warning! This project is already initialized with the following project:')
with clint.textui.indent(4):
clint.textui.puts('User: {}'.format(local_project.user))
clint.textui.puts('Project: {}'.format(local_project.name))
if click.confirm('Would you like to override this current config?', default=False):
init_project = True
else:
init_project = True
if init_project:
ProjectManager.purge()
ProjectManager.set_config(project_config, init=True)
Printer.print_success('Project was initialized', add_sign=True)
else:
Printer.print_header('Project config was not changed.')
init_ignore = False
if IgnoreManager.is_initialized():
click.echo('Warning! Found a .polyaxonignore file.')
if click.confirm('Would you like to override it?', default=False):
init_ignore = True
else:
init_ignore = True
if init_ignore:
IgnoreManager.init_config()
Printer.print_success('New .polyaxonignore file was created.', add_sign=True)
sys.exit(1)
else:
Printer.print_header('.polyaxonignore file was not changed.')
if polyaxonfile:
create_polyaxonfile()
|
Python
| 0.000015
|
@@ -1729,16 +1729,61 @@
IT_FILE)
+,%0A add_sign=True
)%0A%0A%0A@cli
@@ -3930,36 +3930,16 @@
n=True)%0A
- sys.exit(1)%0A
else
|
88ccfdb981b181087b442fc25877489c019a0679
|
Clean up some inconsistent in error handling
|
gunicorn/workers/sync.py
|
gunicorn/workers/sync.py
|
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
#
from datetime import datetime
import errno
import os
import select
import socket
import ssl
import gunicorn.http as http
import gunicorn.http.wsgi as wsgi
import gunicorn.util as util
import gunicorn.workers.base as base
from gunicorn import six
class SyncWorker(base.Worker):
def run(self):
# self.socket appears to lose its blocking status after
# we fork in the arbiter. Reset it here.
for s in self.sockets:
s.setblocking(0)
ready = self.sockets
while self.alive:
self.notify()
# Accept a connection. If we get an error telling us
# that no connection is waiting we fall down to the
# select which is where we'll wait for a bit for new
# workers to come give us some love.
for sock in ready:
try:
client, addr = sock.accept()
client.setblocking(1)
util.close_on_exec(client)
self.handle(sock, client, addr)
# Keep processing clients until no one is waiting. This
# prevents the need to select() for every client that we
# process.
continue
except socket.error as e:
if e.args[0] not in (errno.EAGAIN, errno.ECONNABORTED,
errno.EWOULDBLOCK):
raise
# If our parent changed then we shut down.
if self.ppid != os.getppid():
self.log.info("Parent changed, shutting down: %s", self)
return
try:
self.notify()
# if no timeout is given the worker will never wait and will
# use the CPU for nothing. This minimal timeout prevent it.
timeout = self.timeout or 0.5
ret = select.select(self.sockets, [], self.PIPE, timeout)
if ret[0]:
ready = ret[0]
continue
except select.error as e:
if e.args[0] == errno.EINTR:
ready = self.sockets
continue
if e.args[0] == errno.EBADF:
if self.nr < 0:
ready = self.sockets
continue
else:
return
raise
def handle(self, listener, client, addr):
req = None
try:
if self.cfg.is_ssl:
client = ssl.wrap_socket(client, server_side=True,
**self.cfg.ssl_options)
parser = http.RequestParser(self.cfg, client)
req = six.next(parser)
self.handle_request(listener, req, client, addr)
except http.errors.NoMoreData as e:
self.log.debug("Ignored premature client disconnection. %s", e)
except StopIteration as e:
self.log.debug("Closing connection. %s", e)
except ssl.SSLError as e:
if e.args[0] == ssl.SSL_ERROR_EOF:
self.log.debug("ssl connection closed")
client.close()
else:
self.log.debug("Error processing SSL request.")
self.handle_error(req, client, addr, e)
except socket.error as e:
if e.args[0] != errno.EPIPE:
self.log.exception("Error processing request.")
else:
self.log.debug("Ignoring EPIPE")
except Exception as e:
self.handle_error(req, client, addr, e)
finally:
util.close(client)
def handle_request(self, listener, req, client, addr):
environ = {}
resp = None
try:
self.cfg.pre_request(self, req)
request_start = datetime.now()
resp, environ = wsgi.create(req, client, addr,
listener.getsockname(), self.cfg)
# Force the connection closed until someone shows
# a buffering proxy that supports Keep-Alive to
# the backend.
resp.force_close()
self.nr += 1
if self.nr >= self.max_requests:
self.log.info("Autorestarting worker after current request.")
self.alive = False
respiter = self.wsgi(environ, resp.start_response)
try:
if isinstance(respiter, environ['wsgi.file_wrapper']):
resp.write_file(respiter)
else:
for item in respiter:
resp.write(item)
resp.close()
request_time = datetime.now() - request_start
self.log.access(resp, req, environ, request_time)
finally:
if hasattr(respiter, "close"):
respiter.close()
except socket.error:
raise
except Exception as e:
if resp and resp.headers_sent:
# If the requests have already been sent, we should close the
# connection to indicate the error.
self.log.exception("Error handling request")
try:
client.shutdown(socket.SHUT_RDWR)
client.close()
except socket.error:
pass
raise StopIteration()
# Only send back traceback in HTTP in debug mode.
self.handle_error(req, client, addr, e)
return
finally:
try:
self.cfg.post_request(self, req, environ, resp)
except Exception:
self.log.exception("Exception in post_request hook")
|
Python
| 0
|
@@ -3527,19 +3527,24 @@
args%5B0%5D
-!=
+not in (
errno.EP
@@ -3546,16 +3546,35 @@
no.EPIPE
+, errno.ECONNRESET)
:%0A
@@ -3599,25 +3599,32 @@
.exception(%22
-E
+Socket e
rror process
@@ -3648,32 +3648,172 @@
else:%0A
+ if e.args%5B0%5D == errno.ECONNRESET:%0A self.log.debug(%22Ignoring connection reset%22)%0A else:%0A
@@ -5280,37 +5280,32 @@
except Exception
- as e
:%0A if
@@ -5750,128 +5750,13 @@
-# Only send back traceback in HTTP in debug mode.%0A self.handle_error(req, client, addr, e)%0A return
+raise
%0A
|
6a651684fa2e3d5d0837ff8ab040493cb0ddb9f3
|
Booleans are sentence case
|
pelican/pelicanconf.py
|
pelican/pelicanconf.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Rich Cornish'
SITENAME = u'Rich learns Python the hard way'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Chicago'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = (('Python', 'http://python.org/'),
('LPTHW', 'http://learnpythonthehardway.org/book/'),)
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
DEFAULT_PAGINATION = False
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
# Custom domain
STATIC_PATHS = ['images', 'extra/CNAME']
EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}
# Typogrify
TYPOGRIFY = TRUE
|
Python
| 0.999999
|
@@ -926,8 +926,8 @@
= T
-RUE
+rue
%0A
|
3ad217795a0e8d570b9759a93d24678bdd67a5b4
|
Replacing pythonic print with Logger.logException
|
UM/Mesh/ReadMeshJob.py
|
UM/Mesh/ReadMeshJob.py
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
from UM.Math.Vector import Vector
from UM.Preferences import Preferences
from UM.Logger import Logger
from UM.Mesh.MeshReader import MeshReader
import time
import math
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
def getFileName(self):
return self._filename
def run(self):
reader = self._handler.getReaderForFile(self._filename)
if not reader:
result_message = Message(i18n_catalog.i18nc("@info:status", "Cannot open file type <filename>{0}</filename>", self._filename), lifetime = 0)
result_message.show()
return
# Give the plugin a chance to display a dialog before showing the loading UI
pre_read_result = reader.preRead(self._filename)
if pre_read_result != MeshReader.PreReadResult.accepted:
if pre_read_result == MeshReader.PreReadResult.failed:
result_message = Message(i18n_catalog.i18nc("@info:status", "Failed to load <filename>{0}</filename>", self._filename), lifetime = 0)
result_message.show()
return
loading_message = Message(i18n_catalog.i18nc("@info:status", "Loading <filename>{0}</filename>", self._filename), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
Job.yieldThread() # Yield to any other thread that might want to do something else.
node = None
try:
begin_time = time.time()
node = self._handler.readerRead(reader, self._filename)
end_time = time.time()
Logger.log("d", "Loading mesh took %s seconds", end_time - begin_time)
except:
Logger.logException("e", "Exception in mesh loader")
if not node:
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("@info:status", "Failed to load <filename>{0}</filename>", self._filename), lifetime = 0)
result_message.show()
return
# Scale down to maximum bounds size if that is available
if hasattr(Application.getInstance().getController().getScene(), "_maximum_bounds"):
max_bounds = Application.getInstance().getController().getScene()._maximum_bounds
node._resetAABB()
build_bounds = node.getBoundingBox()
if Preferences.getInstance().getValue("mesh/scale_to_fit") == True or Preferences.getInstance().getValue("mesh/scale_tiny_meshes") == True:
scale_factor_width = max_bounds.width / build_bounds.width
scale_factor_height = max_bounds.height / build_bounds.height
scale_factor_depth = max_bounds.depth / build_bounds.depth
scale_factor = min(scale_factor_width, scale_factor_depth, scale_factor_height)
if Preferences.getInstance().getValue("mesh/scale_to_fit") == True and (scale_factor_width < 1 or scale_factor_height < 1 or scale_factor_depth < 1): # Use scale factor to scale large object down
# Ignore scaling on models which are less than 3 times bigger than the build volume
if 1/scale_factor < 3:
scale_factor = 1
pass
elif Preferences.getInstance().getValue("mesh/scale_tiny_meshes") == True and (scale_factor_width > 100 and scale_factor_height > 100 and scale_factor_depth > 100):
# Round scale factor to lower factor of 10 to scale tiny object up (eg convert m to mm units)
scale_factor = math.pow(10, math.floor(math.log(scale_factor)/math.log(10)))
else:
scale_factor = 1
if scale_factor != 1:
scale_vector = Vector(scale_factor, scale_factor, scale_factor)
display_scale_factor = scale_factor * 100
scale_message = Message(i18n_catalog.i18nc("@info:status", "Auto scaled object to {0}% of original size", ("%i" % display_scale_factor)))
try:
node.scale(scale_vector)
scale_message.show()
except Exception as e:
print(e)
self.setResult(node)
loading_message.hide()
#result_message = Message(i18n_catalog.i18nc("@info:status", "Loaded <filename>{0}</filename>", self._filename))
#result_message.show()
|
Python
| 0.998468
|
@@ -4674,13 +4674,8 @@
tion
- as e
:%0A
@@ -4700,15 +4700,82 @@
-print(e
+Logger.logException(%22e%22, %22While auto-scaling an exception has been raised%22
)%0A
|
87f31f79ac42d454402d8863cb6ba6bd6a75f860
|
Fix missing researcher parameter
|
backend/tasks.py
|
backend/tasks.py
|
# -*- encoding: utf-8 -*-
# Dissemin: open access policy enforcement tool
# Copyright (C) 2014 Antonin Delpeuch
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
from statistics.models import AccessStatistics
from datetime import timedelta
from datetime import datetime
from backend.zotero import consolidate_publication
from backend.orcid import OrcidPaperSource
from backend.crossref import CrossRefAPI
from backend.utils import run_only_once
from celery import shared_task
from celery.utils.log import get_task_logger
from django.utils import timezone
from papers.errors import MetadataSourceException
from papers.models import Paper
from papers.models import PaperWorld
from papers.models import Researcher
from papers.models import OaiSource
from publishers.models import Publisher
from backend.oai import OaiPaperSource
logger = get_task_logger('dissemin.' + __name__)
def update_researcher_task(r, task_name):
"""
Update the task identifier associated to a given researcher.
This also updates the 'last_harvest' field.
"""
r.current_task = task_name
r.last_harvest = timezone.now()
r.save(update_fields=['current_task', 'last_harvest'])
@shared_task(name='init_profile_from_orcid')
@run_only_once('researcher', keys=['pk'], timeout=60*60)
def init_profile_from_orcid(pk):
"""
Populates the profile from ORCID and Crossref
This task is intended to be very quick, so that users
can see their ORCID publications quickly.
"""
r = Researcher.objects.get(pk=pk)
update_task = lambda name: update_researcher_task(r, name)
update_task('clustering')
fetch_everything_for_researcher(pk)
@shared_task(name='fetch_everything_for_researcher')
@run_only_once('researcher', keys=['pk'], timeout=60*60)
def fetch_everything_for_researcher(pk):
orcid_paper_source = OrcidPaperSource(max_results=1000)
r = Researcher.objects.get(pk=pk)
# If it is the first time we fetch this researcher
# if r.stats is None:
# make sure publications already known are also considered
update_researcher_task(r, 'orcid')
try:
orcid_paper_source.link_existing_papers()
orcid_paper_source.fetch_and_save(r)
update_researcher_task(r, None)
except MetadataSourceException as e:
raise e
finally:
r = Researcher.objects.get(pk=pk)
update_researcher_task(r, 'stats')
r.update_stats()
r.harvester = None
update_researcher_task(r, None)
def refetch_researchers(start_time=timezone.now() - timedelta(days=30*6)):
for r in Researcher.objects.filter(last_harvest__gt=start_time).order_by('last_harvest'):
logger.info(r.url)
fetch_everything_for_researcher(r.pk)
@shared_task(name='consolidate_paper')
@run_only_once('consolidate_paper', keys=['pk'], timeout=1*60)
def consolidate_paper(pk):
p = None
try:
p = Paper.objects.get(pk=pk)
abstract = p.abstract or ''
for pub in p.publications:
pub = consolidate_publication(pub)
if pub.description and len(pub.description) > len(abstract):
break
except Paper.DoesNotExist:
logger.exception("consolidate_paper: unknown paper %d" % pk)
@shared_task(name='update_all_stats')
@run_only_once('refresh_stats', timeout=3*60)
def update_all_stats():
"""
Updates the stats for every model using them
"""
AccessStatistics.update_all_stats(PaperWorld)
AccessStatistics.update_all_stats(Publisher)
@shared_task(name='update_crossref')
@run_only_once('update_crossref', timeout=24*3600)
def update_crossref():
"""
Updates paper metadata from Crossref
"""
c = CrossRefAPI()
c.fetch_and_save_new_records()
@shared_task(name='update_oai_sources')
@run_only_once('update_oai_sources', timeout=24*3600)
def update_oai_sources():
"""
Fetches new and updated records from all configured OAI sources since
their last update.
"""
for source in OaiSource.objects.filter(endpoint__isnull=False):
oai = OaiPaperSource(source)
oai.ingest(source.last_update.replace(tzinfo=None), metadataPrefix='base_dc')
source.last_update = datetime.now()
source.save()
|
Python
| 0.000121
|
@@ -2806,16 +2806,17 @@
_papers(
+r
)%0A
|
3b5473048d40feee7807c5ad50f4521113d8216f
|
copy packages instead of symlinking
|
buildtools/publish_deb.py
|
buildtools/publish_deb.py
|
#!/usr/bin/python2
import os
import sys
import subprocess
import shutil
import gzip
archive_dir = "%s/packages" % (os.environ["WORKSPACE"])
if not os.path.isdir(archive_dir):
print "no artifacts archived. Either this is a failed build or a job that does not archive artifacts"
sys.exit(0)
deb_packages = filter(lambda f: f.endswith(".deb"), os.listdir(archive_dir))
prod_deb_packages = [deb for deb in deb_packages if not deb.endswith("-dev.deb")]
dev_deb_packages = [deb for deb in deb_packages if not deb.endswith("-prod.deb")]
def publish_deb_packages(mode, packages):
prefix_path = "dists/stable/%s/binary-amd64" % os.environ["JOB_NAME"]
def create_package_info(mode, packages):
os.chdir(archive_dir)
if os.path.isdir(mode):
shutil.rmtree(mode)
os.mkdir(mode)
os.chdir(mode)
for pkg in packages:
os.symlink("../%s" % pkg, pkg)
package_info = subprocess.check_output(["dpkg-scanpackages","-m", "./", "/dev/null", prefix_path])
package_info = package_info.replace(prefix_path+"./", prefix_path)
os.chdir("..")
shutil.rmtree(mode)
return package_info
def extend_repo(mode, packages_info, packages):
repo_dir = "/srv/scmrepo/%s/%s" % (mode, prefix_path)
os.chdir(repo_dir)
symlinks_new = True
for pkg in packages:
target = "%s/%s" % (archive_dir, pkg)
if os.path.exists(pkg) or os.path.lexists(pkg):
symlinks_new = False
else:
os.symlink(target, pkg)
if symlinks_new:
packages_file = gzip.open("Packages.gz", "a")
packages_file.write(packages_info)
packages_file.close()
packages_info = create_package_info(mode, packages)
extend_repo(mode, packages_info, packages)
publish_deb_packages("dev", dev_deb_packages)
publish_deb_packages("prod", prod_deb_packages)
|
Python
| 0.000001
|
@@ -1442,26 +1442,31 @@
-os.symlink
+shutil.copyfile
(target,
|
7519bd63bfbd175d49289727d7fed234a8ceb7f5
|
fix tenant properties test
|
bluebottle/clients/tests/test_properties.py
|
bluebottle/clients/tests/test_properties.py
|
import mock
from django.test import TestCase
from bluebottle.clients.middleware import TenantProperties, TenantPropertiesMiddleware
from bluebottle.clients.middleware import properties
Mock = mock.Mock
class TestProperties(TestCase):
def test_property_match(self):
""" A match found in the client properties """
with mock.patch("bluebottle.clients.middleware.settings", foo=1):
p = TenantProperties()
p.tenant_properties = {'foo': 2}
self.failUnless(p.foo == 2)
self.failUnless(hasattr(p, 'foo'))
def test_settings_match(self):
""" No match in properties but match in settings """
with mock.patch("bluebottle.clients.middleware.settings", foo=1):
p = TenantProperties()
self.failUnless(p.foo == 1)
self.failUnless(hasattr(p, 'foo'))
def test_nomatch(self):
""" No match in either properties or settings """
with mock.patch("bluebottle.clients.middleware.settings", Mock(spec_set=[])):
p = TenantProperties()
with self.assertRaises(AttributeError):
p.foo == 1
self.failIf(hasattr(p, 'foo'))
def test_verify_settings(self):
with mock.patch("bluebottle.clients.middleware.settings",
MULTI_TENANT_DIR='/tmp/') as settings, \
mock.patch("__builtin__.execfile") as execfile:
properties.set_tenant(Mock(client_name='testtenant'))
self.assertEquals(execfile.call_args[0][1]['settings'], settings)
class TestTenantMiddleware(TestCase):
def setUp(self):
self.middleware = TenantPropertiesMiddleware()
def test_no_tenant(self):
""" verify that ordinary settings resolving just works """
with mock.patch("bluebottle.clients.middleware.settings", foo=42):
self.middleware.process_request(Mock())
self.assertEquals(properties.foo, 42)
def test_invalid_tenant(self):
""" verify that with an invalid tenant default settings resolving
works """
with mock.patch("bluebottle.clients.middleware.settings", foo=42), \
mock.patch("bluebottle.clients.middleware.connection",
Mock(**{"tenant.client_name": "dontexist"})):
self.middleware.process_request(Mock())
self.assertEquals(properties.foo, 42)
def test_valid_tenant(self):
""" verify that the correct properties are loaded"""
with mock.patch("bluebottle.clients.middleware.settings",
MULTI_TENANT_DIR="/some/client/path/"), \
mock.patch("bluebottle.clients.middleware.connection",
Mock(**{"tenant.client_name": "valid"})), \
mock.patch("__builtin__.execfile") as execfile:
self.middleware.process_request(Mock())
self.assertEquals(execfile.call_args_list[0][0][0],
"/some/client/path/valid/properties.py")
self.assertEquals(execfile.call_args_list[1][0][0],
"/some/client/path/valid/secrets.py")
|
Python
| 0
|
@@ -3003,149 +3003,15 @@
lid/
-properties.py%22)%0A self.assertEquals(execfile.call_args_list%5B1%5D%5B0%5D%5B0%5D,%0A %22/some/client/path/valid/secret
+setting
s.py
|
5e007acb5cf5fafa8d95e012948305157efa1dd7
|
Refactor and simplify code
|
bumblebee/modules/cmus.py
|
bumblebee/modules/cmus.py
|
# pylint: disable=C0111,R0903
# -*- coding: utf-8 -*-
"""Displays information about the current song in cmus.
Requires the following executable:
* cmus-remote
Parameters:
* cmus.format: Format string for the song information. Tag values can be put in curly brackets (i.e. {artist})
"""
from collections import defaultdict
import string
import bumblebee.util
import bumblebee.input
import bumblebee.output
import bumblebee.engine
from bumblebee.output import scrollable
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widgets = [
bumblebee.output.Widget(name="cmus.prev"),
bumblebee.output.Widget(name="cmus.main", full_text=self.description),
bumblebee.output.Widget(name="cmus.next"),
bumblebee.output.Widget(name="cmus.shuffle"),
bumblebee.output.Widget(name="cmus.repeat"),
]
super(Module, self).__init__(engine, config, widgets)
engine.input.register_callback(widgets[0], button=bumblebee.input.LEFT_MOUSE,
cmd="cmus-remote -r")
engine.input.register_callback(widgets[1], button=bumblebee.input.LEFT_MOUSE,
cmd="cmus-remote -u")
engine.input.register_callback(widgets[2], button=bumblebee.input.LEFT_MOUSE,
cmd="cmus-remote -n")
engine.input.register_callback(widgets[3], button=bumblebee.input.LEFT_MOUSE,
cmd="cmus-remote -S")
engine.input.register_callback(widgets[4], button=bumblebee.input.LEFT_MOUSE,
cmd="cmus-remote -R")
self._fmt = self.parameter("format", "{artist} - {title} {position}/{duration}")
self._status = None
self._shuffle = False
self._repeat = False
self._tags = defaultdict(lambda: '')
def hidden(self):
return self._status == None
@scrollable
def description(self, widget):
return string.Formatter().vformat(self._fmt, (), self._tags)
def update(self, widgets):
self._load_song()
def state(self, widget):
if widget.name == "cmus.shuffle":
return "shuffle-on" if self._shuffle else "shuffle-off"
if widget.name == "cmus.repeat":
return "repeat-on" if self._repeat else "repeat-off"
if widget.name == "cmus.prev":
return "prev"
if widget.name == "cmus.next":
return "next"
return self._status
def _load_song(self):
info = ""
try:
info = bumblebee.util.execute("cmus-remote -Q")
except RuntimeError:
self._status = None
pass
self._tags = defaultdict(lambda: '')
for line in info.split("\n"):
if line.startswith("status"):
self._status = line.split(" ", 2)[1]
if line.startswith("tag"):
key, value = line.split(" ", 2)[1:]
self._tags.update({ key: value })
for key in ["duration", "position"]:
if line.startswith(key):
dur = int(line.split(" ")[1])
self._tags.update({key:bumblebee.util.durationfmt(dur)})
if line.startswith("set repeat "):
self._repeat = False if "false" in line else True
if line.startswith("set shuffle "):
self._shuffle = False if "false" in line else True
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
Python
| 0
|
@@ -2060,60 +2060,47 @@
-if widget.name == %22cmus.shuffle%22:%0A return
+returns = %7B%0A %22cmus.shuffle%22:
%22sh
@@ -2140,24 +2140,25 @@
shuffle-off%22
+,
%0A if
@@ -2158,59 +2158,26 @@
-if widget.name == %22cmus.repeat%22:%0A return
+ %22cmus.repeat%22:
%22re
@@ -2218,16 +2218,17 @@
eat-off%22
+,
%0A
@@ -2232,157 +2232,695 @@
-if widget.name == %22cmus.prev%22:%0A return %22prev%22%0A if widget.name == %22cmus.next%22:%0A return %22next%22%0A return self._status
+ %22cmus.prev%22: %22prev%22,%0A %22cmus.next%22: %22next%22,%0A %7D%0A return returns.get(widget.name, self._status)%0A%0A def _eval_line(self, line):%0A items = line.split(%22 %22, 2)%0A name, key, value = (line.split(%22 %22, 2) + %5BNone, None%5D)%5B:3%5D%0A%0A if name == %22status%22:%0A self._status = key%0A if name == %22tag%22:%0A self._tags.update(%7Bkey: value%7D)%0A if name in %5B%22duration%22, %22position%22%5D:%0A self._tags.update(%7Bkey:bumblebee.util.durationfmt(int(key))%7D)%0A if name == %22set%22 and key == %22repeat%22:%0A self._repeat = value == %22true%22%0A if name == %22set%22 and key == %22shuffle%22:%0A self._shuffle = value == %22true%22
%0A%0A
@@ -3099,25 +3099,9 @@
one%0A
- pass
%0A
+
@@ -3195,677 +3195,29 @@
-if line.startswith(%22status%22):%0A self._status = line.split(%22 %22, 2)%5B1%5D%0A if line.startswith(%22tag%22):%0A key, value = line.split(%22 %22, 2)%5B1:%5D%0A self._tags.update(%7B key: value %7D)%0A for key in %5B%22duration%22, %22position%22%5D:%0A if line.startswith(key):%0A dur = int(line.split(%22 %22)%5B1%5D)%0A self._tags.update(%7Bkey:bumblebee.util.durationfmt(dur)%7D)%0A if line.startswith(%22set repeat %22):%0A self._repeat = False if %22false%22 in line else True%0A if line.startswith(%22set shuffle %22):%0A self._shuffle = False if %22false%22 in line else True
+self._eval_line(line)
%0A%0A#
|
6ac618821c3fb83f439849208742417c50decbd2
|
Fix forced error message display for non-503 errors
|
src/adhocracy/controllers/error.py
|
src/adhocracy/controllers/error.py
|
import cgi
import re
from pylons import request, response, tmpl_context as c
from pylons.i18n import _
from pylons.controllers.util import abort
from paste.urlparser import PkgResourcesParser
from pylons.controllers.util import forward
from adhocracy import config
from adhocracy.lib.base import BaseController
from adhocracy.lib.templating import render
BODY_RE = re.compile("<br \/><br \/>(.*)<\/body", re.S)
ERROR_MESSAGES = {
503: _(u"The system is currently down for maintenance. Please check back "
u"soon!"),
}
class ErrorController(BaseController):
"""Generates error documents as and when they are required.
The ErrorDocuments middleware forwards to ErrorController when error
related status codes are returned from the application.
This behaviour can be altered by changing the parameters to the
ErrorDocuments middleware in your config/middleware.py file.
"""
identifier = "error"
def document(self):
resp = request.environ.get('pylons.original_response')
if resp is None:
raise abort(404)
response.status = resp.status
if resp.content_type == 'text/javascript':
response.content_type == resp.content_type
return resp.body
# YOU DO NOT SEE THIS. IF YOU DO, ITS NOT WHAT IT LOOKS LIKE
# I DID NOT HAVE REGEX RELATIONS WITH THAT HTML PAGE
for match in BODY_RE.finditer(resp.body):
c.error_message = match.group(1)
c.error_code = cgi.escape(request.GET.get('code',
str(resp.status_int)))
if not c.error_message:
c.error_message = _("Error %s") % c.error_code
if config.get_bool('adhocracy.interactive_debugging'):
c.trace_url = request.environ['pylons.original_response']\
.headers.get('X-Debug-URL', None)
if c.trace_url is not None:
# this may only happen in debug mode
assert(config.get_bool('debug', False))
else:
c.trace_url = None
return render("/error/http.html")
def show(self):
"""
Force an error message.
"""
status = request.GET.get('force_status')
if status is None:
raise abort(404)
data = {
'hide_code': 'hide_code' in request.GET,
'hide_notify': 'hide_notify' in request.GET,
'error_code': int(status),
'error_message': ERROR_MESSAGES.get(int(status)),
}
return render("/error/http.html", data)
def img(self, id):
"""Serve Pylons' stock images"""
return self._serve_file('/'.join(['media/img', id]))
def style(self, id):
"""Serve Pylons' stock stylesheets"""
return self._serve_file('/'.join(['media/style', id]))
def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
request.environ['PATH_INFO'] = '/%s' % path
return forward(PkgResourcesParser('pylons', 'pylons'))
|
Python
| 0.000004
|
@@ -2536,16 +2536,20 @@
(status)
+, ''
),%0A
|
09dbfc7ee6eb6db2ac18a8696406cd8c92dbfef4
|
fix pylint issues
|
sdcm/wait.py
|
sdcm/wait.py
|
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright (c) 2016 ScyllaDB
"""
Wait functions appropriate for tests that have high timing variance.
"""
import time
import logging
import tenacity
from tenacity.retry import retry_if_result, retry_if_exception_type
from tenacity import RetryError
LOGGER = logging.getLogger('sdcm.wait')
def wait_for(func, step=1, text=None, timeout=None, throw_exc=True, **kwargs):
"""
Wrapper function to wait with timeout option.
:param func: Function to evaluate.
:param step: Time to sleep between attempts in seconds
:param text: Text to print while waiting, for debug purposes
:param timeout: Timeout in seconds
:param throw_exc: Raise exception if timeout expired, but func result is not True
:param kwargs: Keyword arguments to func
:return: Return value of func.
"""
if not timeout:
return forever_wait_for(func, step, text, **kwargs)
res = None
def retry_logger(retry_state):
# pylint: disable=protected-access
LOGGER.debug('wait_for: Retrying {}: attempt {} ended with: {}'.format(text if text else retry_state.fn.__name__,
retry_state.attempt_number,
str(retry_state.outcome._exception) if retry_state.outcome._exception else retry_state.outcome._result))
try:
retry = tenacity.Retrying(
reraise=throw_exc,
stop=tenacity.stop_after_delay(timeout),
wait=tenacity.wait_fixed(step),
before_sleep=retry_logger,
retry=(retry_if_result(lambda value: not value) | retry_if_exception_type())
)
res = retry.call(func, **kwargs)
except Exception as ex: # pylint: disable=broad-except
err = 'Wait for: {}: timeout - {} seconds - expired'.format(text if text else func.__name__, timeout)
LOGGER.error(err)
if hasattr(ex, 'last_attempt') and ex.last_attempt.exception() is not None: # pylint: disable=no-member
LOGGER.error("last error: %s", repr(ex.last_attempt.exception())) # pylint: disable=no-member
else:
LOGGER.error("last error: %s", repr(ex))
if throw_exc:
if hasattr(ex, 'last_attempt') and not ex.last_attempt._result: # pylint: disable=protected-access,no-member
raise RetryError(err)
raise
return res
def forever_wait_for(func, step=1, text=None, **kwargs):
"""
Wait indefinitely until func evaluates to True.
This is similar to avocado.utils.wait.wait(), but there's no
timeout, we'll just keep waiting for it.
:param func: Function to evaluate.
:param step: Amount of time to sleep before another try.
:param text: Text to log, for debugging purposes.
:param kwargs: Keyword arguments to func
:return: Return value of func.
"""
ok = False
start_time = time.time()
while not ok:
ok = func(**kwargs)
time.sleep(step)
time_elapsed = time.time() - start_time
if text is not None:
LOGGER.debug('%s (%s s)', text, time_elapsed)
return ok
|
Python
| 0.000001
|
@@ -1477,16 +1477,29 @@
R.debug(
+%0A
'wait_fo
@@ -1510,18 +1510,18 @@
etrying
-%7B%7D
+%25s
: attemp
@@ -1522,18 +1522,18 @@
attempt
-%7B%7D
+%25s
ended w
@@ -1541,19 +1541,25 @@
th:
-%7B%7D'.format(
+%25s',%0A
text
@@ -1613,170 +1613,36 @@
- retry_state.attempt_number,%0A
+retry_state.attempt_number,%0A
@@ -1751,17 +1751,25 @@
._result
-)
+%0A
)%0A%0A t
@@ -2771,32 +2771,40 @@
RetryError(err)
+ from ex
%0A rai
|
2f0dc639a4448e0762843fe3c9a4239eb7fac8c6
|
Fix bug- socks_http does not resolve DNS remotely via Tor
|
nowallet/socks_http.py
|
nowallet/socks_http.py
|
import asyncio
import aiohttp
import aiosocks
from aiosocks.connector import ProxyConnector, ProxyClientRequest
class SocksHTTPError(Exception):
pass
async def urlopen(url: str) -> str:
auth5 = aiosocks.Socks5Auth(
'proxyuser1', password='pwd') # type: aiosocks.Socks5Auth
conn = ProxyConnector(remote_resolve=False) # type: ProxyConnector
try:
with aiohttp.ClientSession(connector=conn,
request_class=ProxyClientRequest) as session:
async with session.get(url, # Always connects through Tor.
proxy='socks5://127.0.0.1:9050',
proxy_auth=auth5) as resp:
if resp.status == 200:
return await resp.text()
else:
raise SocksHTTPError("HTTP response not OK")
except aiohttp.ClientProxyConnectionError:
# connection problem
pass
except aiosocks.SocksError:
# communication problem
pass
return "" # Should never happen
def main():
loop = asyncio.get_event_loop() # type: asyncio.AbstractEventLoop
html = loop.run_until_complete(urlopen("https://github.com/")) # type: str
print(html)
loop.close()
if __name__ == '__main__':
main()
|
Python
| 0
|
@@ -330,12 +330,11 @@
lve=
-Fals
+Tru
e)
|
34016dca73f56c6929bf265f597fee0a0b325434
|
Add better introspection
|
barin/manager.py
|
barin/manager.py
|
from . import schema as S
from . import cursor
from . import query
class Manager(object):
def __init__(self, cname, field_collection, indexes, **options):
# schema=S.Missing, db=None):
self._cname = cname
self.f = field_collection
self.indexes = indexes
self.query = query.Query(self)
self.aggregate = query.Aggregate(self)
self._schema = field_collection.make_schema(**options)
self._db = None
@property
def collection(self):
return getattr(self._db, self._cname)
def bind(self, db):
self._db = db
def validate(self, value, state=None):
if self._schema is not S.Missing:
value = self._schema.validate(value, state)
return value
def __getattr__(self, name):
return getattr(self.collection, name)
def __get__(self, obj, cls=None):
if obj is None:
return ClassManager(self, cls)
else:
return InstanceManager(self, obj)
class ClassManager(object):
def __init__(self, manager, cls):
self._manager = manager
self._cls = cls
self._wrap_cursor('find')
self._wrap_single('find_one')
self._wrap_single('find_one_and_update')
self._wrap_single('find_one_and_replace')
self._wrap_single('find_one_and_delete')
def __getattr__(self, name):
return getattr(self._manager, name)
def validate(self, value, state=None):
value = self._manager.validate(value, state)
return self._cls(value)
def get(self, **kwargs):
return self.find_one(kwargs)
def find_by(self, **kwargs):
return self.find(kwargs)
def _wrap_cursor(self, name):
def wrapper(*args, **kwargs):
orig = getattr(self.collection, name)
res = orig(*args, **kwargs)
return cursor.Cursor(self, res)
wrapper.__name__ = 'wrapped_{}'.format(name)
setattr(self, name, wrapper)
return wrapper
def _wrap_single(self, name):
def wrapper(*args, **kwargs):
orig = getattr(self.collection, name)
res = orig(*args, **kwargs)
if res is None:
return res
return self._cls(res)
wrapper.__name__ = 'wrapped_{}'.format(name)
setattr(self, name, wrapper)
return wrapper
class InstanceManager(Manager):
def __init__(self, manager, obj):
self._manager = manager
self._obj = obj
def __getattr__(self, name):
return getattr(self._manager, name)
def insert(self):
return self.collection.insert(self._obj)
def delete(self):
return self.collection.delete(self._obj._id)
|
Python
| 0
|
@@ -757,16 +757,99 @@
value%0A%0A
+ def __dir__(self):%0A return dir(self.collection) + self.__dict__.keys()%0A%0A
def
@@ -1431,16 +1431,97 @@
lete')%0A%0A
+ def __dir__(self):%0A return dir(self._manager) + self.__dict__.keys()%0A%0A
def
|
5a5a7fe10b74b321eade98c35d404a0c83243642
|
fix reverse range bug
|
numba/targets/heapq.py
|
numba/targets/heapq.py
|
# A port of https://github.com/python/cpython/blob/3.7/Lib/heapq.py
from __future__ import print_function, absolute_import, division
import heapq as hq
import numpy as np
from numba import types
from numba.errors import TypingError
from numba.extending import overload, register_jitable
@register_jitable
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if newitem < parent:
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
@register_jitable
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
childpos = 2 * pos + 1
while childpos < endpos:
rightpos = childpos + 1
if rightpos < endpos and not heap[childpos] < heap[rightpos]:
childpos = rightpos
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
heap[pos] = newitem
_siftdown(heap, startpos, pos)
@overload(hq.heapify)
def hq_heapify(x):
if not isinstance(x, types.List):
raise TypingError('heap argument must be a list')
# what to do if list is empty?
dt = x.dtype
if isinstance(dt, types.Complex):
msg = ("'<' not supported between instances "
"of 'complex' and 'complex'")
raise TypingError(msg)
def hq_heapify_impl(x):
n = len(x)
for i in range(n // 2 - 1, -1, -1):
_siftup(x, i)
return hq_heapify_impl
@register_jitable
def _siftdown_max(heap, startpos, pos):
newitem = heap[pos]
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if parent < newitem:
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
@register_jitable
def _siftup_max(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
childpos = 2*pos + 1
while childpos < endpos:
rightpos = childpos + 1
if rightpos < endpos and not heap[rightpos] < heap[childpos]:
childpos = rightpos
heap[pos] = heap[childpos]
pos = childpos
childpos = 2*pos + 1
heap[pos] = newitem
_siftdown_max(heap, startpos, pos)
@register_jitable
def _heapify_max(x):
n = len(x)
#for i in reversed(range(n//2)):
for i in range(n // 2 + 1, -1, -1):
_siftup_max(x, i)
@register_jitable
def _heapreplace_max(heap, item):
returnitem = heap[0]
heap[0] = item
_siftup_max(heap, 0)
return returnitem
@overload(hq.heappop)
def hq_heappop(heap):
def hq_heappop_impl(heap):
lastelt = heap.pop()
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
return hq_heappop_impl
@overload(hq.heappush)
def heappush(heap, item):
def hq_heappush_impl(heap, item):
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
return hq_heappush_impl
@overload(hq.heapreplace)
def heapreplace(heap, item):
def hq_heapreplace(heap, item):
returnitem = heap[0]
heap[0] = item
_siftup(heap, 0)
return returnitem
return hq_heapreplace
@overload(hq.nsmallest)
def nsmallest(n, iterable):
def hq_nsmallest_impl(n, iterable):
if n == 1:
out = np.min(np.asarray(iterable))
return [out]
size = len(iterable)
if n >= size:
return sorted(iterable)[:n]
it = iter(iterable)
result = [(elem, i) for i, elem in zip(range(n), it)]
_heapify_max(result)
top = result[0][0]
order = n
for elem in it:
if elem < top:
_heapreplace_max(result, (elem, order))
top, _order = result[0]
order += 1
result.sort()
return [elem for (elem, order) in result]
return hq_nsmallest_impl
@overload(hq.nlargest)
def nlargest(n, iterable):
def hq_nlargest_impl(n, iterable):
if n == 1:
out = np.max(np.asarray(iterable))
return [out]
size = len(iterable)
if n >= size:
return sorted(iterable)[::-1][:n]
# When key is none, use simpler decoration
it = iter(iterable)
result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)]
hq.heapify(result)
top = result[0][0]
order = -n
for elem in it:
if top < elem:
hq.heapreplace(result, (elem, order))
top, _order = result[0]
order -= 1
result.sort(reverse=True)
return [elem for (elem, order) in result]
return hq_nlargest_impl
|
Python
| 0.000001
|
@@ -1204,44 +1204,8 @@
')%0A%0A
- # what to do if list is empty?%0A%0A
@@ -2373,44 +2373,8 @@
(x)%0A
- #for i in reversed(range(n//2)):
%0A
@@ -2396,17 +2396,17 @@
(n // 2
-+
+-
1, -1,
|
1f74194580b571e678879e4d0f267f180e933cce
|
Use the abbreviate_url function for the Host attachment
|
icinga_slack/webhook.py
|
icinga_slack/webhook.py
|
#!/usr/bin/env python3
import argparse
import json
import urllib.parse
import urllib.request
import sys
from icinga_slack import __version__
alert_colors = {'UNKNOWN': '#6600CC',
'CRITICAL': '#FF0000',
'WARNING': '#FF9900',
'OK': '#36A64F'}
def abbreviate_url(url):
parsed_url = urllib.parse.urlparse(url)
return "<{0}|{1}>".format(url, parsed_url.netloc)
class AttachmentField(dict):
def __init__(self, title, value, short=False):
self['title'] = title
self['value'] = value
self['short'] = short
class AttachmentFieldList(list):
def __init__(self, *args):
for count, field in enumerate(args):
self.append(field)
class Attachment(dict):
def __init__(self, fallback, fields, text=None, pretext=None, color=None):
self['fallback'] = fallback
self['fields'] = fields
if text:
self['text'] = text
if pretext:
self['pretext'] = pretext
if color:
self['color'] = color
class AttachmentList(list):
def __init__(self, *args):
for count, attachment in enumerate(args):
self.append(attachment)
class Message(dict):
def __init__(self, channel, text, username, mrkdwn_in=["fields"],
icon_emoji=":ghost:", attachments=None):
self['channel'] = channel
self['text'] = text
if mrkdwn_in:
self['mrkdwn_in'] = mrkdwn_in
if username:
self['username'] = username
if icon_emoji:
self['icon_emoji'] = icon_emoji
self['attachments'] = AttachmentList()
def attach(
self,
message,
host,
level,
action_url=None,
notes_url=None,
status_cgi_url=''
):
fields = AttachmentFieldList()
fields.append(AttachmentField("Message", message))
fields.append(AttachmentField(
"Host", "<{1}?host={0}|{0}>".format(host, status_cgi_url),
True)
)
fields.append(AttachmentField("Level", level, True))
if action_url:
fields.append(AttachmentField("Actions URL", action_url, True))
if notes_url:
fields.append(AttachmentField("Notes URL", notes_url, True))
if level in alert_colors.keys():
color = alert_colors[level]
else:
color = alert_colors['UNKNOWN']
alert_attachment = Attachment(
fallback=" {0} on {1} is {2}".format(message, host, level),
color=color,
fields=fields
)
self['attachments'].append(alert_attachment)
def send(self, webhook_url):
data = urllib.parse.urlencode({"payload": json.dumps(self)})
response = urllib.request.urlopen(
webhook_url,
data.encode('utf8')
).read()
if response == b'ok':
return True
else:
print("Error: %s" % response)
return False
def parse_options():
parser = argparse.ArgumentParser(
prog="icinga_slack_webhook_notify",
description="Send an Icinga Alert to Slack.com via a generic webhook integration"
)
parser.add_argument(
'-c', '--channel',
required=True,
help="The channel to send the message to"
)
parser.add_argument(
'-m', '--message',
required=True,
help="The text of the message to send"
)
destination_group = parser.add_mutually_exclusive_group()
destination_group.add_argument(
'-u', '--web-hook-url',
help="The webhook URL for your integration"
)
destination_group.add_argument(
'-p', '--print-payload',
action='store_const',
const=True,
default=False,
help="Rather than sending the payload to Slack, print it to STDOUT"
)
parser.add_argument(
'-A', '--service-action-url',
default=None,
help="An optional action_url for this alert {default: None}"
)
parser.add_argument(
'-H', '--host',
default="UNKNOWN",
help="An optional host the message relates to {default: UNKNOWN}"
)
parser.add_argument(
'-L', '--level',
choices=["OK", "WARNING", "CRITICAL", "UNKNOWN"],
default="UNKNOWN",
help="An optional alert level {default: UNKNOWN}"
)
parser.add_argument(
'-M', '--header-message',
default="I have received the following alert:",
help="A header message sent before the formatted alert {default: I have received the following alert:}"
)
parser.add_argument(
'-N', '--service-notes-url',
default=None,
help="An optional notes_url for this alert {default: None}"
)
parser.add_argument(
'-S', '--status-cgi-url',
default='https://nagios.example.com/cgi-bin/icinga/status.cgi',
help="The URL of status.cgi for your Nagios/Icinga instance {default: https://nagios.example.com/cgi-bin/icinga/status.cgi}"
)
parser.add_argument(
'-U', '--username',
default="Icinga",
help="Username to send the message from {default: Icinga}"
)
parser.add_argument(
'-V', '--version',
action='version',
help="Print version information",
version=__version__
)
return parser.parse_args()
def main():
args = parse_options()
message = Message(channel=args.c, text=args.M, username=args.U)
message.attach(message=args.m, host=args.H, level=args.L, action_url=args.A, notes_url=args.N, status_cgi_url=args.S)
if args.print_payload:
print(json.dumps(message, indent=True))
else:
if message.send(webhook_url=args.web_hook_url):
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()
|
Python
| 0
|
@@ -1953,32 +1953,45 @@
fields.append(
+%0A
AttachmentField(
@@ -2007,28 +2007,62 @@
+
%22Host%22,
- %22%3C%7B1
+%0A abbreviate_url(%22%7B0
%7D?host=%7B
0%7D%7C%7B
@@ -2061,15 +2061,10 @@
st=%7B
-0%7D%7C%7B0%7D%3E
+1%7D
%22.fo
@@ -2068,22 +2068,16 @@
.format(
-host,
status_c
@@ -2082,19 +2082,30 @@
_cgi_url
-),%0A
+, host)),%0A
@@ -2112,16 +2112,29 @@
True
+%0A
)%0A
|
a68193102354af807285d0238354314c9aa67a25
|
Move victim selection to enforce
|
senlin/policies/deletion_policy.py
|
senlin/policies/deletion_policy.py
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under 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 senlin.db import api as db_api
from senlin.policies import base
class DeletionPolicy(base.PolicyBase):
'''
Policy for deleting member(s) from a cluster.
'''
CRITERIA = (
OLDEST_FIRST, YOUNGEST_FIRST, RANDOM,
) = (
'oldest_first',
'youngest_first',
'random',
)
TARGET = [
('BEFORE', 'CLUSTER', 'DELETE_MEMBER'),
('AFTER', 'CLUSTER', 'DELETE_MEMBER'),
]
PROFILE_TYPE = [
'ANY'
]
def __init__(self, name, type_name, **kwargs):
super(DeletionPolicy, self).__init__(name, type_name, kwargs)
self.criteria = kwargs.get('criteria')
self.grace_period = kwargs.get('grace_period')
self.delete_desired_capacity = kwargs.get('reduce_desired_capacity')
def _sort_members_by_creation_time(members):
# TODO: do sorting
return members
def pre_op(self, cluster_id, action, **args):
# :cluster_id the cluster
# :action 'DEL_MEMBER'
# :args a list of candidate members
# TODO: choose victims from the given cluster
members = db_api.get_members(cluster_id)
sorted = self._sort_members_by_creation_time(members)
if self.criteria == self.OLDEST_FIRST:
victim = sorted[0]
elif self.criteria ==self.YOUNGEST_FIRST:
victim = sorted[-1]
else:
rand = random(len(sorted))
victim = sorted[rand]
# TODO: return True/False
return victim
def enforce(self, cluster_id, action, **args):
pass
def post_op(self, cluster_id, action, **args):
pass
|
Python
| 0
|
@@ -542,16 +542,31 @@
cense.%0A%0A
+import random%0A%0A
from sen
@@ -664,12 +664,8 @@
licy
-Base
):%0A
@@ -907,14 +907,12 @@
('
-BEFORE
+WHEN
', '
@@ -918,33 +918,67 @@
'CLUSTER
-', 'DELETE_MEMBER
+_SCALE_DOWN'),%0A ('AFTER', 'CLUSTER_DEL_NODES
'),%0A
@@ -1003,25 +1003,19 @@
STER
-', 'DELETE_MEMBER
+_SCALE_DOWN
'),%0A
@@ -1086,27 +1086,27 @@
_(self,
+type_
name,
-type_
name, **
@@ -1159,22 +1159,16 @@
_init__(
-name,
type_nam
@@ -1170,16 +1170,24 @@
e_name,
+name, **
kwargs)%0A
@@ -1232,16 +1232,20 @@
riteria'
+, ''
)%0A
@@ -1291,16 +1291,19 @@
_period'
+, 0
)%0A
@@ -1309,21 +1309,21 @@
self.
-delet
+reduc
e_desire
@@ -1375,301 +1375,363 @@
ity'
-)%0A%0A def _sort_members_by_creation_time(members):%0A # TODO: do sorting%0A return members%0A%0A def pre_op(self, cluster_id, action, **args):%0A # :cluster_id the cluster%0A # :action 'DEL_MEMBER'%0A # :args a list of candidate members%0A%0A # TODO: cho
+,%0A False)%0A random.seed()%0A%0A def pre_op(self, cluster_id, action, **args):%0A '''%0A We don't block the deletion anyhow.%0A '''%0A return True%0A%0A def enforce(self, cluster_id, action, **args):%0A '''%0A The enforcement of a deletion policy returns the ch
ose
+n
victims
fro
@@ -1730,31 +1730,50 @@
tims
- from the given cluster
+%0A that will be deleted.%0A '''
%0A
@@ -1777,22 +1777,20 @@
-member
+node
s = db_a
@@ -1796,92 +1796,242 @@
api.
-get_members(cluster_id)%0A sorted = self._sort_members_by_
+node_get_all_by_cluster_id(cluster_id)%0A if self.criteria == self.RANDOM:%0A rand = random.randrange(len(nodes))%0A return nodes%5Brand%5D%0A%0A sorted_list = sorted(nodes, key=lambda r: (r.
creat
-ion
+ed
_time
-(members
+, r.name)
)%0A
@@ -2102,16 +2102,21 @@
= sorted
+_list
%5B0%5D%0A
@@ -2121,18 +2121,22 @@
el
-if
+se: #
self.cr
@@ -2144,16 +2144,17 @@
teria ==
+
self.YOU
@@ -2197,134 +2197,18 @@
rted
+_list
%5B-1%5D%0A
- else:%0A rand = random(len(sorted))%0A victim = sorted%5Brand%5D%0A%0A # TODO: return True/False
%0A
@@ -2227,39 +2227,39 @@
victim%0A%0A def
-enforce
+post_op
(self, cluster_i
@@ -2290,65 +2290,59 @@
-pass %0A%0A def post_op(self, cluster_id, action, **args):
+# TODO(Qiming): process grace period here if needed
%0A
|
190abc81176855208847ccb171e88b6c12d57de7
|
replace a hack with ProtocolDesc
|
ryu/tests/unit/lib/test_ofp_pktinfilter.py
|
ryu/tests/unit/lib/test_ofp_pktinfilter.py
|
# Copyright (C) 2013 Stratosphere 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.
# vim: tabstop=4 shiftwidth=4 softtabstop=4
import unittest
import logging
from nose.tools import *
from ryu.controller import ofp_event
from ryu.controller.handler import (
set_ev_cls,
MAIN_DISPATCHER,
)
from ryu.lib.packet import vlan, ethernet, ipv4
from ryu.lib.ofp_pktinfilter import packet_in_filter, RequiredTypeFilter
from ryu.lib import mac
from ryu.ofproto import ether, ofproto_v1_3, ofproto_v1_3_parser
LOG = logging.getLogger('test_pktinfilter')
class _Datapath(object):
ofproto = ofproto_v1_3
ofproto_parser = ofproto_v1_3_parser
class _PacketInFilterApp(object):
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
@packet_in_filter(RequiredTypeFilter, {'types': [
vlan.vlan,
]})
def packet_in_handler(self, ev):
return True
class Test_packet_in_filter(unittest.TestCase):
""" Test case for pktinfilter
"""
def setUp(self):
self.app = _PacketInFilterApp()
def tearDown(self):
pass
def test_pkt_in_filter_pass(self):
datapath = _Datapath()
e = ethernet.ethernet(mac.BROADCAST_STR,
mac.BROADCAST_STR,
ether.ETH_TYPE_8021Q)
v = vlan.vlan()
i = ipv4.ipv4()
pkt = (e / v / i)
pkt.serialize()
pkt_in = ofproto_v1_3_parser.OFPPacketIn(datapath,
data=buffer(pkt.data))
ev = ofp_event.EventOFPPacketIn(pkt_in)
ok_(self.app.packet_in_handler(ev))
def test_pkt_in_filter_discard(self):
datapath = _Datapath()
e = ethernet.ethernet(mac.BROADCAST_STR,
mac.BROADCAST_STR,
ether.ETH_TYPE_IP)
i = ipv4.ipv4()
pkt = (e / i)
pkt.serialize()
pkt_in = ofproto_v1_3_parser.OFPPacketIn(datapath,
data=buffer(pkt.data))
ev = ofp_event.EventOFPPacketIn(pkt_in)
ok_(not self.app.packet_in_handler(ev))
def test_pkt_in_filter_truncated(self):
datapath = _Datapath()
truncated_data = buffer('')
pkt_in = ofproto_v1_3_parser.OFPPacketIn(datapath,
data=truncated_data)
ev = ofp_event.EventOFPPacketIn(pkt_in)
ok_(not self.app.packet_in_handler(ev))
|
Python
| 0
|
@@ -1010,148 +1010,107 @@
ser%0A
-%0A%0ALOG = logging.getLogger('test_pktinfilter')%0A%0A%0Aclass _Datapath(object):%0A ofproto = ofproto_v1_3%0A ofproto_parser = ofproto_v1_3_parser
+from ryu.ofproto.ofproto_protocol import ProtocolDesc%0A%0A%0ALOG = logging.getLogger('test_pktinfilter')
%0A%0A%0Ac
@@ -1589,34 +1589,69 @@
datapath =
-_Datapath(
+ProtocolDesc(version=ofproto_v1_3.OFP_VERSION
)%0A e
@@ -2169,34 +2169,69 @@
datapath =
-_Datapath(
+ProtocolDesc(version=ofproto_v1_3.OFP_VERSION
)%0A e
@@ -2732,18 +2732,53 @@
h =
-_Datapath(
+ProtocolDesc(version=ofproto_v1_3.OFP_VERSION
)%0A
|
324d0a201150b72bbf965e81c40dab22ce81374f
|
Update DataCleaning.py
|
iembdfa/DataCleaning.py
|
iembdfa/DataCleaning.py
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 15 11:39:04 2016
@author: rahulmehra
"""
# Import the modules
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import numpy as np
raw_data = {'patient': [500,1, 1,-2, 2,3,4,5,6,7,None,9,6,3,4,5,6,7,8,9],
'obs': [1, 2, 3, 1, 2,3,4,5,6,7,8,9,6,3,4,5,6,7,8,9],
'treatment': [0, 1, 0, 1, 0,0, 1, 0, 1, 0,0, 1, 0, 1, 0,0, 1, 0, 1, 0],
'score': ['strong', 'weak', 'normal', 'weak', 'strong','strong', 'weak', 'normal', 'weak', 'strong','strong', 'weak', 'normal', 'weak', 'strong','strong', 'weak', 'normal', 'weak', 'strong'],
'city': ['ML', 'AL', 'BL', 'CL', 'TL','ML', 'AL', 'BL', 'CL', 'TL','ML', 'AL', 'BL', 'CL', 'TL','ML', 'AL', 'BL', 'CL', 'TL']}
input_dataframe = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score', 'city'])
# Define a function to autoclean the pandas dataframe
def autoclean(x):
for column in x.columns:
# Replace NaNs with the median or mode of the column depending on the column type
try:
x[column].fillna(x[column].median(), inplace=True)
except TypeError:
x[column].fillna(x[column].mode(), inplace=True)
# Select the columns with type int and float
if x[column].dtypes == 'int64' or x[column].dtypes == 'float64':
#Calculate mean of the column
mean = x[column].mean()
#Calculate the standard deviation of the column
std = 1.5*x[column].std()
# See for the outliers and impute with median
x[column] = x[column].apply(lambda y: x[column].median() if(abs(y - mean >std)) else y)
# Calculate the number of rows in dataframe
n_rows = len(input_dataframe.index)
#Calculate the percentage of negative values in the column
negative_perc = np.sum((x[column] < 0))/n_rows
#Handle the unreliable values (like negative values in the positive value column)
x[column] = x[column].apply(lambda y: -(y) if (y<0 and negative_perc >= 0.05) else y)
# Encode all strings with numerical equivalents
if str(x[column].values.dtype) == 'object':
column_encoder = LabelEncoder().fit(x[column].values)
x[column] = column_encoder.transform(x[column].values)
print(x[column].dtype)
return x
autoclean(input_dataframe)
|
Python
| 0
|
@@ -2369,16 +2369,20 @@
dtype)%0A%0A
+
return x
|
4003a3adcef9eb32efc4d41e45b9e6a1cdfe47b8
|
Complete basic assignment string1.py
|
basic/string1.py
|
basic/string1.py
|
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Basic string exercises
# Fill in the code for the functions below. main() is already set up
# to call the functions with a few different inputs,
# printing 'OK' when each function is correct.
# The starter code for each function includes a 'return'
# which is just a placeholder for your code.
# It's ok if you do not complete all the functions, and there
# are some additional functions to try in string2.py.
# A. donuts
# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5'
# and donuts(23) returns 'Number of donuts: many'
def donuts(count):
# +++your code here+++
return
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
# +++your code here+++
return
# C. fix_start
# Given a string s, return a string
# where all occurences of its first char have
# been changed to '*', except do not change
# the first char itself.
# e.g. 'babble' yields 'ba**le'
# Assume that the string is length 1 or more.
# Hint: s.replace(stra, strb) returns a version of string s
# where all instances of stra have been replaced by strb.
def fix_start(s):
# +++your code here+++
return
# D. MixUp
# Given strings a and b, return a single string with a and b separated
# by a space '<a> <b>', except swap the first 2 chars of each string.
# e.g.
# 'mix', pod' -> 'pox mid'
# 'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or more.
def mix_up(a, b):
# +++your code here+++
return
# Provided simple test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))
# Provided main() calls the above functions with interesting inputs,
# using test() to check if each result is correct or not.
def main():
print 'donuts'
# Each line calls donuts, compares its result to the expected for that call.
test(donuts(4), 'Number of donuts: 4')
test(donuts(9), 'Number of donuts: 9')
test(donuts(10), 'Number of donuts: many')
test(donuts(99), 'Number of donuts: many')
print
print 'both_ends'
test(both_ends('spring'), 'spng')
test(both_ends('Hello'), 'Helo')
test(both_ends('a'), '')
test(both_ends('xyz'), 'xyyz')
print
print 'fix_start'
test(fix_start('babble'), 'ba**le')
test(fix_start('aardvark'), 'a*rdv*rk')
test(fix_start('google'), 'goo*le')
test(fix_start('donut'), 'donut')
print
print 'mix_up'
test(mix_up('mix', 'pod'), 'pox mid')
test(mix_up('dog', 'dinner'), 'dig donner')
test(mix_up('gnash', 'sport'), 'spash gnort')
test(mix_up('pezzy', 'firm'), 'fizzy perm')
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
main()
|
Python
| 0.999999
|
@@ -1024,30 +1024,112 @@
e here+++%0A
-return
+if count%3C10:%0A return 'Number of donuts: %25d'%25(count)%0A return 'Number of donuts: many'
%0A%0A%0A# B. both
@@ -1388,30 +1388,74 @@
e here+++%0A
-return
+if len(s)%3E=2:%0A return s%5B0:2%5D+s%5B-2:%5D%0A return ''
%0A%0A%0A# C. fix_
@@ -1854,24 +1854,54 @@
+++%0A return
+ s%5B0%5D+s%5B1:%5D.replace(s%5B0%5D, '*')
%0A%0A%0A# D. MixU
@@ -2197,24 +2197,24 @@
here+++%0A
-
return
%0A%0A%0A# Pro
@@ -2205,16 +2205,46 @@
return
+ b%5B0:2%5D+a%5B2:%5D+' '+a%5B0:2%5D+b%5B2:%5D
%0A%0A%0A# Pro
|
b3213feae032032018354548f244a3204f04707f
|
Change compressor.
|
pyncd.py
|
pyncd.py
|
import gzip
x = open('1.png', 'rb').read() # file 1 of any type
y = open('2.png', 'rb').read() # file 2 of the same type as file 1
x_y = x + y # the concatenation of files
x_comp = gzip.compress(x) # compress file 1
y_comp = gzip.compress(y) # compress file 2
x_y_comp = gzip.compress(x_y) # compress file concatenated
# print len() of each file
print(len(x_comp), len(y_comp), len(x_y_comp), sep=' ', end='\n')
# magic happens here
ncd = (len(x_y_comp) - min(len(x_comp), len(y_comp))) / max(len(x_comp), len(y_comp))
print(ncd)
|
Python
| 0
|
@@ -1,19 +1,19 @@
import
-gzip
+lzma
%0A%0Ax = op
@@ -16,17 +16,36 @@
= open('
-1
+examples/imgs/square
.png', '
@@ -87,17 +87,36 @@
= open('
-2
+examples/imgs/circle
.png', '
@@ -206,36 +206,36 @@
files%0A%0Ax_comp =
-gzip
+lzma
.compress(x) # c
@@ -250,36 +250,36 @@
file 1%0Ay_comp =
-gzip
+lzma
.compress(y) # c
@@ -308,12 +308,12 @@
p =
-gzip
+lzma
.com
|
4bca4d85018bcd8f7e86c2b6d576c645674b4693
|
Support indented function (nested function maybe?)
|
resumable.py
|
resumable.py
|
import ast
import inspect
import warnings
import linecache
from uuid import uuid4
from collections import OrderedDict
from astmonkey.transformers import ParentNodeTransformer
from astmonkey.visitors import SourceGeneratorNodeVisitor
def split(func, name=None):
return func, name
def get_sub(lst, pred):
for subnode in lst:
if pred(subnode):
lst.remove(subnode)
return subnode
class ToSource(SourceGeneratorNodeVisitor):
'''
The changes in here are primarily to patch
around differences between python versions
(I've tested with Python 3.5)
'''
@classmethod
def to_source(cls, node):
generator = cls(' ')
generator.visit(node)
return ''.join(generator.result)
def visit_Call(self, node):
node.starargs = get_sub(
node.args,
lambda t: isinstance(t, ast.Starred)
)
node.kwargs = get_sub(
node.keywords,
lambda t: t.arg is None
)
return super().visit_Call(node)
def visit_Lambda(self, node):
# until i can get the ast compiling directly,
# we need to make sure precendence is correct
self.write('(')
super().visit_Lambda(node)
self.write(')')
def signature(self, node):
if node.vararg:
node.vararg = node.vararg.arg
if node.kwarg:
node.kwarg = node.kwarg.arg
return super().signature(node)
class Visitor(ast.NodeVisitor):
def __init__(self):
self.parts = {}
self.current = None
self.name = None
self.last_idx = -1
def visit_FunctionDef(self, node):
self.current = self.parts[node] = OrderedDict()
self.name = node.name
self.args = node.args
return super().generic_visit(node)
def function_from(self, name, args, body, lineno):
func = ast.FunctionDef(
name=name,
args=args,
body=body,
decorator_list=[],
returns=None
)
func.lineno = lineno
return func
def visit_Call(self, node):
if getattr(node.func, 'id', None) == 'split':
# this is the expression that contains the call,
# or basically the value of the assignment/return
expr = node.parent
user = expr.parent # by user we mean user of the value
# it's possible more are actually supported,
# but i'm hesitant to just allow them without
# further testing
if not isinstance(user, (ast.Return, ast.Assign)):
warnings.warn('This is untested')
# sanity checking
assert user.parent_field == 'body', user.parent_field
assert isinstance(user.parent, ast.FunctionDef)
field = getattr(user.parent, user.parent_field)
body = field[self.last_idx + 1:user.parent_field_index]
value = user.value
value.func = value.func.args[0] # remove call to split
body.append(ast.Return(value))
body[-1].lineno = value.lineno
self.current[self.name] = self.function_from(
self.name, self.args, body, value.lineno
)
self.last_idx = user.parent_field_index
name = node.args[1].s if len(node.args) == 2 else None
self.name = name
self.args = self.get_args(user, name)
return super().generic_visit(node)
def get_args(self, user, name):
msg = 'have a name, on line {} of function {}'.format(
user.lineno,
user.parent.name
)
if isinstance(user, ast.Return):
if name is not None:
raise Exception('A closing split cannot {}'.format(msg))
else:
if name is None:
raise Exception('A non-closing split must {}'.format(msg))
args = []
if isinstance(user, ast.Assign):
target = user.targets[0]
names = target.elts if isinstance(target, ast.Tuple) else [target]
args = [ast.arg(name.id, None) for name in names]
return ast.arguments(
args=args,
vararg=None,
kwonlyargs=[],
kw_defaults=[],
kwarg=None,
defaults=[]
)
def cache_code(node):
filename = '<ast_{}>'.format(uuid4().hex)
source = ToSource.to_source(node)
lines = [line + '\n' for line in source.splitlines()]
linecache.cache[filename] = len(source), None, lines, filename
assert filename in linecache.cache
return filename
def extract(env, node, name):
loc = dict(env)
filename = cache_code(node)
node = ast.Module(body=[node])
node = ast.fix_missing_locations(node)
code = compile(node, filename=filename, mode='exec')
exec(code, loc, loc)
return loc[name]
def rebuild(function):
assert callable(function)
lines, lineno = inspect.getsourcelines(function)
lines = ''.join(lines)
lines = '\n' * (lineno - 1) + lines
root, = ast.parse(lines).body
root = ParentNodeTransformer().visit(root)
visitor = Visitor()
visitor.visit(root)
parts = visitor.parts[root]
return OrderedDict(
(name, extract(function.__globals__, node, name))
for name, node in parts.items()
)
|
Python
| 0
|
@@ -75,16 +75,44 @@
t uuid4%0A
+from textwrap import dedent%0A
from col
@@ -5105,16 +5105,42 @@
(lines)%0A
+ lines = dedent(lines)%0A
line
|
033a236767329263d55bd9d0cefd681d030a10bf
|
Separated the SEA goal from the joint goal
|
pysea.py
|
pysea.py
|
from PyDynamixel import *
class Spring(Joint):
''' This class derives from Joint to
implement a Spring feedback board. It
works exactly like joint, except that
we can't set torques or goal angles.
We can only read its current angle.'''
def __init__(self, spring_id, centerValue = 0):
''' The constructor takes the board id
as the argument. Argument centerValue
can be set to calibrate the zero
position of the spring (relaxed pos).
'''
super(Spring, self).__init__(spring_id, centerValue)
def setMaxTorque(self, maxTorque):
''' Not implemented in this class!
'''
pass
def sendMaxTorque(self, maxTorque = None):
''' Not implemented in this class!
'''
pass
def setGoalAngle(self, angle):
''' Not implemented in this class!
'''
pass
def sendGoalAngle(self, goalAngle = None):
''' Not implemented in this class!
'''
pass
def enableTorque(self):
''' Not implemented in this class!
'''
pass
def disableTorque(self):
''' Not implemented in this class!
'''
pass
def receiveAngle(self):
''' Reads the current position of this
servomotor alone. The read position is
stored and can be accessed via method
getAngle()
'''
self.currValue = dxl.read_word(self.socket, self.servo_id, \
GOALPOS_ADDR) - self.centerValue
self.currAngle = pi*float(self.currValue)/4096.0
return self.currAngle
class SEA(object):
''' This class implements the Series Elastic
Actuator. It basically combines a Joint and
a Spring.
'''
spring = None # This will store the spring
joint = None # This will store the servo
# PID controller gains
kp = 1.0
ki = 0.001
kd = 0.0
# PID controller variables
error_before = 0.0
error_sum = 0.0
def __init__(self, joint, spring, \
kp=1.0, ki=0.001, kd=0.0):
''' The constructor receives as argument
the objects joint and spring. Optionally
the PID gains can also be passed.
'''
self.spring = spring
self.joint = joint
self.kp = kp
self.ki = ki
self.kd = kd
def update(self):
''' This method updates the goalValue of
the joint servo according to the spring
displacement
'''
# Calculate the actual position, which is
# the servo position minus the spring
# position
# (here we use joint.goalAngle instead
# of joint.currAngle to avoid having
# to read the actual position of the
# servomotor. We assume the servo has
# moved to the desired position
# immediatelly!)
angle = self.joint.goalAngle - self.spring.currAngle
# Calculate the error
error = self.joint.goalAngle - angle
# Calculate the accumulated error
# (integral)
self.error_sum = self.error_sum + error
# Calculate the difference between the
# current error and the error before
# (derivative)
error_deriv = error - self.error_before
# Saves the error for later calculating
# the diffrerence again
self.error_before = error
# Gets the PID control calculated
p = self.kp*error
i = self.ki*self.error_sum
d = self.kd*error_deriv
# Defines the control signal
c = p + i + d
# Transforms into value and
# sets to the servo goalValue
self.joint.goalValue = \
self.joint.goalValue + int(2048.0*c/pi)
def setGoalAngle(self, goalAngle):
''' Sets the goal angle of the SEA
which is the same as the goal angle
of the servo (goal value will change)
'''
self.joint.setGoalAngle(goalAngle)
|
Python
| 0.999959
|
@@ -1993,24 +1993,77 @@
or_sum = 0.0
+%0A %0A # Goal angle of the SEA%0A goalAngle = 0.0
%0A%0A def __
@@ -3032,38 +3032,32 @@
error = self.
-joint.
goalAngle - angl
@@ -3747,73 +3747,34 @@
goal
-Value = %5C%0A self.joint.goalValue + int(2048.0*c/pi)
+Angle = self.goalValue + c
%0A%0A
@@ -3973,26 +3973,17 @@
elf.
-joint.setG
+g
oalAngle
(goa
@@ -3978,17 +3978,19 @@
oalAngle
-(
+ =
goalAngl
@@ -3990,11 +3990,10 @@
oalAngle
-)
%0A%0A
|
111e1d1b92860a4342c3499ca9eb0e5623b4974c
|
Increase RQ default_timeout to one hour (in case we have very very long running jobs)
|
call_server/extensions.py
|
call_server/extensions.py
|
# define flask extensions in separate file, to resolve import dependencies
from flask_sqlalchemy import SQLAlchemy as _BaseSQLAlchemy
# workaround to enable pool_pre_ping
# per https://github.com/pallets/flask-sqlalchemy/issues/589#issuecomment-361075700
class SQLAlchemy(_BaseSQLAlchemy):
def apply_pool_defaults(self, app, options):
options["pool_pre_ping"] = True
super(SQLAlchemy, self).apply_pool_defaults(app, options)
db = SQLAlchemy()
from flask_caching import Cache
cache = Cache()
from flask_assets import Environment
assets = Environment()
from flask_babel import Babel
babel = Babel()
from flask_mail import Mail
mail = Mail()
from flask_login import LoginManager
login_manager = LoginManager()
from flask_restless import APIManager
rest = APIManager()
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()
from flask_cors import CORS as cors
from flask_store import Store
store = Store()
from flask_rq2 import RQ
rq = RQ()
from flask_talisman import Talisman
CALLPOWER_CSP = {
'default-src':'\'self\'',
'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', # for local scripts
'cdnjs.cloudflare.com', 'ajax.cloudflare.com', 'media.twiliocdn.com', # required for jquery, twilio
'js-agent.newrelic.com', '*.nr-data.net'], # additional analytics platforms
'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'],
'font-src': ['\'self\'', 'data:', 'fonts.gstatic.com'],
'media-src': ['\'self\'', 'blob:', 'media.twiliocdn.com'],
'connect-src': ['\'self\'', 'https://*.twilio.com', 'wss://*.twilio.com', 'media.twiliocdn.com', 'openstates.org'],
'object-src': ['\'self\'', 'blob:'],
'img-src': ['\'self\'', 'data:']
}
# unsafe-inline needed to render <script> tags without nonce
# unsafe-eval needed to run bootstrap templates
talisman = Talisman()
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
|
Python
| 0
|
@@ -964,16 +964,37 @@
rq = RQ(
+default_timeout=60*60
)%0A%0Afrom
|
e8fdbc786b7a8391014199366a71b290b49efb4c
|
Fix views decorators (ref #141)
|
caminae/trekking/views.py
|
caminae/trekking/views.py
|
from caminae.authent.decorators import trekking_manager_required
from caminae.mapentity.views import (MapEntityLayer, MapEntityList, MapEntityJsonList,
MapEntityDetail, MapEntityCreate, MapEntityUpdate, MapEntityDelete)
from .models import Trek, POI
from .filters import TrekFilter, POIFilter
from .forms import TrekForm, POIForm
class TrekLayer(MapEntityLayer):
model = Trek
class TrekList(MapEntityList):
model = Trek
filterform = TrekFilter
columns = ['name', 'departure', 'arrival']
class TrekJsonList(MapEntityJsonList, TrekList):
pass
class TrekDetail(MapEntityDetail):
model = Trek
def can_edit(self):
return self.request.user.profile.is_trekking_manager()
class TrekCreate(MapEntityCreate):
model = Trek
form_class = TrekForm
@trekking_manager_required('trekking:trek_list')
def dispatch(self, *args, **kwargs):
return super(TrekCreate, self).dispatch(*args, **kwargs)
class TrekUpdate(MapEntityUpdate):
model = Trek
form_class = TrekForm
@trekking_manager_required('trekking:trek_detail')
def dispatch(self, *args, **kwargs):
return super(TrekUpdate, self).dispatch(*args, **kwargs)
class TrekDelete(MapEntityDelete):
model = Trek
@trekking_manager_required('trekking:trek_detail')
def dispatch(self, *args, **kwargs):
return super(TrekDelete, self).dispatch(*args, **kwargs)
class POILayer(MapEntityLayer):
model = POI
class POIList(MapEntityList):
model = POI
filterform = POIFilter
columns = ['name', 'type']
class POIJsonList(MapEntityJsonList, POIList):
pass
class POIDetail(MapEntityDetail):
model = POI
def can_edit(self):
return self.request.user.profile.is_trekking_manager()
class POICreate(MapEntityCreate):
model = POI
form_class = POIForm
@trekking_manager_required('trekking:poi_list')
def dispatch(self, *args, **kwargs):
return super(TrekCreate, self).dispatch(*args, **kwargs)
class POIUpdate(MapEntityUpdate):
model = POI
form_class = POIForm
@trekking_manager_required('trekking:poi_detail')
def dispatch(self, *args, **kwargs):
return super(POIUpdate, self).dispatch(*args, **kwargs)
class POIDelete(MapEntityDelete):
model = POI
@trekking_manager_required('trekking:poi_detail')
def dispatch(self, *args, **kwargs):
return super(POIDelete, self).dispatch(*args, **kwargs)
|
Python
| 0
|
@@ -1,20 +1,74 @@
+from django.utils.decorators import method_decorator%0A%0A
from caminae.authent
@@ -867,32 +867,49 @@
TrekForm%0A%0A @
+method_decorator(
trekking_manager
@@ -935,24 +935,25 @@
:trek_list')
+)
%0A def dis
@@ -1125,32 +1125,49 @@
TrekForm%0A%0A @
+method_decorator(
trekking_manager
@@ -1191,32 +1191,33 @@
ng:trek_detail')
+)
%0A def dispatc
@@ -1363,24 +1363,41 @@
Trek%0A%0A @
+method_decorator(
trekking_man
@@ -1425,32 +1425,33 @@
ng:trek_detail')
+)
%0A def dispatc
@@ -1970,32 +1970,49 @@
= POIForm%0A%0A @
+method_decorator(
trekking_manager
@@ -2041,16 +2041,17 @@
i_list')
+)
%0A def
@@ -2097,36 +2097,35 @@
return super(
-Trek
+POI
Create, self).di
@@ -2227,24 +2227,41 @@
IForm%0A%0A @
+method_decorator(
trekking_man
@@ -2288,32 +2288,33 @@
ing:poi_detail')
+)
%0A def dispatc
@@ -2461,16 +2461,33 @@
I%0A%0A @
+method_decorator(
trekking
@@ -2526,16 +2526,17 @@
detail')
+)
%0A def
|
c0c3d63c6124549008a2dc17c1e691e799129444
|
Fix getting unwatched episodes from Plex
|
plex2myshows/modules/plex/plex.py
|
plex2myshows/modules/plex/plex.py
|
class Plex(object):
def __init__(self, plex):
self.plex = plex
def get_watched_episodes(self, section_name):
watched_episodes = set(self.plex.library.section(section_name).searchEpisodes(unwatched=False))
return watched_episodes
|
Python
| 0.000001
|
@@ -150,12 +150,27 @@
s =
-set(
+%5B%5D%0A shows =
self
@@ -215,32 +215,92 @@
arch
-Episodes(un
+Shows()%0A for show in shows:%0A watched_episodes.extend(show.
watched
-=False
+(
))%0A
|
d8da358042e6b02426804783b20e256398c6c467
|
Remove decimals from y-axis percentage label
|
capstone/rl/utils/plot.py
|
capstone/rl/utils/plot.py
|
from __future__ import division
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from .callbacks import Callback
from ...game.players import GreedyQ, RandPlayer
from ...game.utils import play_series
class EpisodicWLDPlotter(Callback):
'''
Plots the episodic win, loss and draws of a learner
against a fixed opponent
'''
def __init__(self, game, opp_player=None, n_matches=1000,
period=1, filename='test.pdf'):
self.game = game
self.opp_player = opp_player
self.n_matches = n_matches
self.period = period
self.filename = filename
self.x = []
self.y_wins = []
self.y_draws = []
self.y_losses = []
def on_episode_end(self, episode, qf):
if episode % self.period != 0:
return
self._plot(episode, qf)
def _plot(self, episode, qf):
results = play_series(
game=self.game.copy(),
players=[GreedyQ(qf), self.opp_player],
n_matches=self.n_matches,
verbose=False
)
self.x.append(episode)
self.y_wins.append(results['W'] / self.n_matches)
self.y_draws.append(results['D'] / self.n_matches)
self.y_losses.append(results['L'] / self.n_matches)
def on_train_end(self, qf):
n_episodes = len(self.x) * self.period
self._plot(n_episodes - 1, qf)
fig = plt.figure()
ax = fig.add_subplot(111)
w_line, = ax.plot(self.x, self.y_wins, label='Win')
l_line, = ax.plot(self.x, self.y_losses, label='Loss')
d_line, = ax.plot(self.x, self.y_draws, label='Draw')
ax.set_xlim([0, n_episodes])
ax.set_ylim([0, 1.0])
plt.xlabel('Episodes')
formatter = FuncFormatter(lambda y, pos: '{}%'.format(y * 100))
plt.gca().yaxis.set_major_formatter(formatter)
plt.legend(handles=[w_line, l_line, d_line], loc=7)
plt.savefig(self.filename)
|
Python
| 0.998577
|
@@ -1847,15 +1847,15 @@
y,
-pos
+_
: '%7B
+:d
%7D%25'.
@@ -1861,16 +1861,20 @@
.format(
+int(
y * 100)
@@ -1874,16 +1874,17 @@
* 100))
+)
%0A
|
b77685c442fcc769727c443a59ac2bb620d90bdc
|
update copyright year
|
casingSimulations/info.py
|
casingSimulations/info.py
|
__version__ = '0.1.0b0'
__author__ = 'Lindsey Heagy'
__license__ = 'MIT'
__copyright__ = 'Copyright 2018 Lindsey Heagy'
|
Python
| 0.000001
|
@@ -104,16 +104,21 @@
ght 2018
+-2019
Lindsey
|
bed15fe0680277cefb0c02fddfe566a73e0dc2ba
|
refresh_token is bac
|
keystoneauth_oidc_refreshtoken/tests/unit/test_oidc.py
|
keystoneauth_oidc_refreshtoken/tests/unit/test_oidc.py
|
# coding=utf-8
# Copyright 2017 JOSÉ JOAQUÍN ESCOBAR GÓMEZ
# File: test_oidc.py
# Description:
#
# 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.
import uuid
from keystoneauth1.tests.unit.identity import test_identity_v3_oidc
from keystoneauth1.tests.unit import oidc_fixtures
from keystoneauth1.tests.unit import utils
from keystoneauth_oidc_refreshtoken import plugin as oidc
class OIDCRefreshTokenTests(test_identity_v3_oidc.BaseOIDCTests,
utils.TestCase):
def setUp(self):
super(OIDCRefreshTokenTests, self).setUp()
self.GRANT_TYPE = 'refresh_token'
self.AUTHORIZATION_ENDPOINT = ''
self.plugin = oidc.OidcRefreshToken(
self.AUTH_URL,
self.IDENTITY_PROVIDER,
self.PROTOCOL,
client_id = self.CLIENT_ID,
client_secret = self.CLIENT_SECRET,
access_token_endpoint = self.ACCESS_TOKEN_ENDPOINT,
project_name = self.PROJECT_NAME)
|
Python
| 0.999995
|
@@ -1169,16 +1169,48 @@
OINT = '
+https://localhost:8020/oidc/auth
'%0D%0A%0D%0A
@@ -1496,24 +1496,73 @@
_ENDPOINT,%0D%0A
+ refresh_token = self.REFRESH_TOKEN,%0D%0A
|
ff93b501d489f182617e7f8f497747f26e91f39e
|
add older experiments
|
kid_readout/analysis/resources/starcryo_experiments.py
|
kid_readout/analysis/resources/starcryo_experiments.py
|
import bisect
from kid_readout.utils.time_tools import date_to_unix_time
by_unix_time_table = [('2014-04-28', 'STAR Cryo 4x5 0813f12 Al horn package, AR chip, LPF, copper shield', 'light'),
('2014-04-16', 'STAR Cryo 4x5 0813f12 Al horn package, AR chip, fully taped', 'dark'),
('2014-04-10', 'STAR Cryo 4x5 0813f12 Al horn package, AR chip, Al tape over horns, copper shield', 'dark'),
('2014-04-04', 'STAR Cryo 4x5 0813f12 Al horn package, AR chip, LPF, Al tape over horns', 'dark'),
('2014-03-28', 'STAR Cryo 4x5 0813f12 Al horn package, AR chip, LPF, Al tape over a few horns', 'light'),
('2014-03-19', 'STAR Cryo 4x5 0813f12 Al horn package, AR chip, LPF, broken connection', 'light'),
('2014-02-27', 'STAR Cryo 4x5 0813f10 Cu horn package, LPF', 'light'),
]
by_unix_time_table.sort(key = lambda x: date_to_unix_time(x[0]))
_unix_time_index = [date_to_unix_time(x[0]) for x in by_unix_time_table]
|
Python
| 0.000654
|
@@ -89,16 +89,158 @@
able = %5B
+%0A ('2014-07-03', 'STAR Cryo 4x5 0813f12 Al horn package, AR chip, LPF, copper shield, IR LED fiber', 'light'),%0A
('2014-0
@@ -985,32 +985,122 @@
LPF', 'light'),%0A
+ ('2014-01-28', 'STAR Cryo 4x5 0813f10 Cu horn package, no LPF', 'light'),%0A
|
8f13dedde762edc6b1b02e7dc2b4675a7fc13514
|
Fix problem with watcher failing. Resolve issue #36
|
hamlpy/hamlpy_watcher.py
|
hamlpy/hamlpy_watcher.py
|
# haml-watcher.py
# Author: Christian Stefanescu (st.chris@gmail.com)
#
# Watch a folder for files with the given extensions and call the HamlPy
# compiler if the modified time has changed since the last check.
import sys
import codecs
import os
import os.path
import time
from hamlpy import Compiler
EXTENSIONS = ['.haml'] # watched extensions
CHECK_INTERVAL = 3 # in seconds
DEBUG = False # print file paths when a file is compiled
# dict of compiled files [fullpath : timestamp]
compiled = dict()
def watched_extension(extension):
"""Return True if the given extension is one of the watched extensions"""
for ext in EXTENSIONS:
if extension.endswith(ext):
return True
return False
def watch_folder():
"""Main entry point. Expects one or two arguments (the watch folder + optional destination folder)."""
argv_len = len(sys.argv)
if argv_len in (2, 3):
folder = os.path.realpath(sys.argv[1])
destination = os.path.realpath(argv_len == 3 and os.path.realpath(sys.argv[2]) or folder)
print "Watching %s at refresh interval %s seconds" % (folder,CHECK_INTERVAL)
while True:
try:
_watch_folder(folder, destination)
time.sleep(CHECK_INTERVAL)
except KeyboardInterrupt:
# allow graceful exit (no stacktrace output)
sys.exit(0)
pass
else:
print "Usage: haml-watcher.py <watch_folder> [destination_folder]"
def _watch_folder(folder, destination):
"""Compares "modified" timestamps against the "compiled" dict, calls compiler
if necessary."""
for dirpath, dirnames, filenames in os.walk(folder):
for filename in filenames:
if watched_extension(filename):
fullpath = os.path.join(dirpath, filename)
mtime = os.stat(fullpath).st_mtime
compiled_path = _compiled_path(destination, filename)
if (not fullpath in compiled or
compiled[fullpath] < mtime or
not os.path.isfile(compiled_path)):
compile_file(fullpath, compiled_path)
compiled[fullpath] = mtime
def _compiled_path(destination, filename):
return os.path.join(destination, filename[:filename.rfind('.')] + '.html')
def compile_file(fullpath, outfile_name):
"""Calls HamlPy compiler."""
try:
if DEBUG:
print "Compiling %s -> %s" % (fullpath, outfile_name)
haml_lines = codecs.open(fullpath, 'r', encoding='utf-8').read().splitlines()
compiler = Compiler()
output = compiler.process_lines(haml_lines)
outfile = codecs.open(outfile_name, 'w', encoding='utf-8')
outfile.write(output)
except Exception, e:
# import traceback
print "Failed to compile %s -> %s\nReason:\n%s" % (fullpath, outfile_name, e)
# print traceback.print_exc()
if __name__ == '__main__':
watch_folder()
|
Python
| 0
|
@@ -317,16 +317,27 @@
%5B'.haml'
+, '.hamlpy'
%5D # w
@@ -1875,18 +1875,21 @@
ilename)
-
%0A
+
@@ -1931,32 +1931,36 @@
ime%0A
+
+
compiled_path =
@@ -2009,16 +2009,20 @@
+
if (not
@@ -2053,32 +2053,36 @@
+
+
compiled%5Bfullpat
@@ -2091,24 +2091,28 @@
%3C mtime or%0A
+
@@ -2163,24 +2163,28 @@
+
+
compile_file
@@ -2209,16 +2209,20 @@
d_path)%0A
+
|
691880274cc2082de54c0c7d0c561d720ce28ae1
|
Fix crash when bed is not preheated before printing starts
|
OctoPrintOutputController.py
|
OctoPrintOutputController.py
|
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from cura.PrinterOutput.PrinterOutputController import PrinterOutputController
from PyQt5.QtCore import QTimer
MYPY = False
if MYPY:
from cura.PrinterOutput.PrintJobOutputModel import PrintJobOutputModel
from cura.PrinterOutput.PrinterOutputModel import PrinterOutputModel
class OctoPrintOutputController(PrinterOutputController):
def __init__(self, output_device):
super().__init__(output_device)
self._preheat_bed_timer = QTimer()
self._preheat_bed_timer.setSingleShot(True)
self._preheat_bed_timer.timeout.connect(self._onPreheatBedTimerFinished)
self._preheat_printer = None
self._preheat_hotends_timer = QTimer()
self._preheat_hotends_timer.setSingleShot(True)
self._preheat_hotends_timer.timeout.connect(self._onPreheatHotendsTimerFinished)
self._preheat_hotends = set()
self._output_device.printersChanged.connect(self._onPrintersChanged)
self._active_printer = None
def _onPrintersChanged(self):
if self._active_printer:
self._active_printer.stateChanged.disconnect(self._onPrinterStateChanged)
self._active_printer.targetBedTemperatureChanged.disconnect(self._onTargetBedTemperatureChanged)
for extruder in self._active_printer.extruders:
extruder.targetHotendTemperatureChanged.disconnect(self._onTargetHotendTemperatureChanged)
self._active_printer = self._output_device.activePrinter
if self._active_printer:
self._active_printer.stateChanged.connect(self._onPrinterStateChanged)
self._active_printer.targetBedTemperatureChanged.connect(self._onTargetBedTemperatureChanged)
for extruder in self._active_printer.extruders:
extruder.targetHotendTemperatureChanged.connect(self._onTargetHotendTemperatureChanged)
def _onPrinterStateChanged(self):
self._active_printer_state = self._output_device.activePrinter.state
if self._active_printer_state != "idle":
if self._preheat_bed_timer.isActive():
self._preheat_bed_timer.stop()
self._preheat_printer.updateIsPreheating(False)
if self._preheat_hotends_timer.isActive():
self._preheat_hotends_timer.stop()
for extruder in self._preheat_hotends:
extruder.updateIsPreheating(False)
self._preheat_hotends = set()
def moveHead(self, printer: "PrinterOutputModel", x, y, z, speed):
self._output_device.sendCommand("G91")
self._output_device.sendCommand("G0 X%s Y%s Z%s F%s" % (x, y, z, speed))
self._output_device.sendCommand("G90")
def homeHead(self, printer):
self._output_device.sendCommand("G28 X")
self._output_device.sendCommand("G28 Y")
def homeBed(self, printer):
self._output_device.sendCommand("G28 Z")
def setJobState(self, job: "PrintJobOutputModel", state: str):
if state == "pause":
self._output_device.pausePrint()
job.updateState("paused")
elif state == "print":
self._output_device.resumePrint()
job.updateState("printing")
elif state == "abort":
self._output_device.cancelPrint()
pass
def setTargetBedTemperature(self, printer: "PrinterOutputModel", temperature: int):
self._output_device.sendCommand("M140 S%s" % temperature)
def _onTargetBedTemperatureChanged(self):
if self._preheat_printer.targetBedTemperature == 0 and self._preheat_bed_timer.isActive():
self._preheat_bed_timer.stop()
self._preheat_printer.updateIsPreheating(False)
def preheatBed(self, printer: "PrinterOutputModel", temperature, duration):
try:
temperature = round(temperature) # The API doesn't allow floating point.
duration = round(duration)
except ValueError:
return # Got invalid values, can't pre-heat.
self.setTargetBedTemperature(printer, temperature=temperature)
self._preheat_bed_timer.setInterval(duration * 1000)
self._preheat_bed_timer.start()
self._preheat_printer = printer
printer.updateIsPreheating(True)
def cancelPreheatBed(self, printer: "PrinterOutputModel"):
self.setTargetBedTemperature(printer, temperature=0)
self._preheat_bed_timer.stop()
printer.updateIsPreheating(False)
def _onPreheatBedTimerFinished(self):
self.setTargetBedTemperature(self._preheat_printer, 0)
self._preheat_printer.updateIsPreheating(False)
def setTargetHotendTemperature(self, printer: "PrinterOutputModel", position: int, temperature: int):
self._output_device.sendCommand("M104 S%s T%s" % (temperature, position))
def _onTargetHotendTemperatureChanged(self):
if not self._preheat_hotends_timer.isActive():
return
for extruder in self._active_printer.extruders:
if extruder in self._preheat_hotends and extruder.targetHotendTemperature == 0:
extruder.updateIsPreheating(False)
self._preheat_hotends.remove(extruder)
if not self._preheat_hotends:
self._preheat_hotends_timer.stop()
def preheatHotend(self, extruder: "ExtruderOutputModel", temperature, duration):
position = extruder.getPosition()
number_of_extruders = len(extruder.getPrinter().extruders)
if position >= number_of_extruders:
return # Got invalid extruder nr, can't pre-heat.
try:
temperature = round(temperature) # The API doesn't allow floating point.
duration = round(duration)
except ValueError:
return # Got invalid values, can't pre-heat.
self.setTargetHotendTemperature(extruder.getPrinter(), position, temperature=temperature)
self._preheat_hotends_timer.setInterval(duration * 1000)
self._preheat_hotends_timer.start()
self._preheat_hotends.add(extruder)
extruder.updateIsPreheating(True)
def cancelPreheatHotend(self, extruder: "ExtruderOutputModel"):
self.setTargetHotendTemperature(extruder.getPrinter(), extruder.getPosition(), temperature=0)
if extruder in self._preheat_hotends:
extruder.updateIsPreheating(False)
self._preheat_hotends.remove(extruder)
if not self._preheat_hotends and self._preheat_hotends_timer.isActive():
self._preheat_hotends_timer.stop()
def _onPreheatHotendsTimerFinished(self):
for extruder in self._preheat_hotends:
self.setTargetHotendTemperature(extruder.getPrinter(), extruder.getPosition(), 0)
self._preheat_hotends = set()
|
Python
| 0.000001
|
@@ -1995,86 +1995,8 @@
f):%0A
- self._active_printer_state = self._output_device.activePrinter.state%0A%0A
@@ -2022,17 +2022,17 @@
_printer
-_
+.
state !=
@@ -3549,80 +3549,80 @@
eat_
-printer.targetBedTemperature == 0 and self._preheat_bed_timer.isActive()
+bed_timer.isActive() and self._preheat_printer.targetBedTemperature == 0
:%0A
|
a21b87c92295fe650222ee27910efba1e912fa6c
|
Add TODO comment for a unit test failure due to timezone changes
|
Test/test_Format.py
|
Test/test_Format.py
|
import unittest
from NanoPcap import Format
class FormatTest(unittest.TestCase):
def setUp(self):
self._initialHeader = (1234, 5678, 9102, -1, 3456, 7890, 4321)
self._initialRecordHeader = (1463179445, 10 * 1000 * 1000, 9102, 3456)
def test_header(self):
self.assertEqual(Format.PCAP_HEADER_STRUCT.size, 24)
initial = self._initialHeader
packed = Format.PCAP_HEADER_STRUCT.pack(*initial)
unpacked = Format.PCAP_HEADER_STRUCT.unpack(packed)
self.assertEqual(unpacked, initial)
header = Format.PcapHeader(*initial)
self.assertEqual(header.magicNumber(), initial[0])
self.assertEqual(header.timeResolution(), 1000 * 1000)
self.assertEqual(header.versionMajor(), initial[1])
self.assertEqual(header.versionMinor(), initial[2])
self.assertEqual(header.tzOffset(), initial[3])
self.assertEqual(header.sigfigs(), initial[4])
self.assertEqual(header.snaplen(), initial[5])
self.assertEqual(header.network(), initial[6])
self.assertFalse(header.isMagicValid())
byteValue = header.asBytes()
self.assertEqual(byteValue, packed)
def test_headerMagic(self):
correctMagicInitial = list(self._initialHeader)
correctMagicInitial[0] = Format.PCAP_MAGIC_NUMBER
correctHeader = Format.PcapHeader(*correctMagicInitial)
self.assertEqual(correctHeader.magicNumber(), Format.PCAP_MAGIC_NUMBER)
self.assertEqual(correctHeader.timeResolution(), 1000 * 1000)
self.assertTrue(correctHeader.isMagicValid())
def test_headerMagicNs(self):
correctMagicInitial = list(self._initialHeader)
correctMagicInitial[0] = Format.PCAP_NS_MAGIC_NUMBER
correctHeaderNs = Format.PcapHeader(*correctMagicInitial)
self.assertEqual(correctHeaderNs.magicNumber(), Format.PCAP_NS_MAGIC_NUMBER)
self.assertEqual(correctHeaderNs.timeResolution(), 1000 * 1000 * 1000)
self.assertTrue(correctHeaderNs.isMagicValid())
def testRecord(self):
self.assertEqual(Format.PCAP_RECORD_HEADER_STRUCT.size, 16)
initial = self._initialRecordHeader
packed = Format.PCAP_RECORD_HEADER_STRUCT.pack(*initial)
unpacked = Format.PCAP_RECORD_HEADER_STRUCT.unpack(packed)
self.assertEqual(unpacked, initial)
recordHeader = Format.PcapRecordHeader(*initial)
self.assertEqual(recordHeader.tsSec(), initial[0])
self.assertEqual(recordHeader.tsFrac(), initial[1])
self.assertEqual(recordHeader.epochNanos(), initial[0] * 1000 * 1000 * 1000 + initial[1])
self.assertEqual(recordHeader.epochSecondsFloat(), 1463179445.010)
byteValue = recordHeader.asBytes()
self.assertEqual(byteValue, packed)
d = recordHeader.timestampDatetime()
self.assertEqual(d.year, 2016)
self.assertEqual(d.month, 5)
self.assertEqual(d.day, 13)
self.assertEqual(d.hour, 17)
self.assertEqual(d.minute, 44)
self.assertEqual(d.second, 5)
self.assertEqual(d.microsecond, 10 * 1000)
self.assertEqual(recordHeader.includedLength(), initial[2])
self.assertEqual(recordHeader.originalLength(), initial[3])
|
Python
| 0
|
@@ -2943,32 +2943,68 @@
ay, 13)%0A
+#TODO: make this time-zone agnostic
self.assertEqual
|
225413d811f5449d1973b475c474225e343a1a09
|
Remove unused code for course platforms platforms
|
studygroups/models/course.py
|
studygroups/models/course.py
|
from django.db import models
from django.db.models import Count, Max, Q, Sum, Case, When, IntegerField, Value
from django.urls import reverse # TODO ideally this shouldn't be in the model
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models import F
from django.utils.translation import ugettext_lazy as _
from django.core.paginator import Paginator
from django.utils.translation import get_language_info
from .base import LifeTimeTrackingModel
import json
KNOWN_COURSE_PLATFORMS = {
"www.edx.org/": "edX",
"www.futurelearn.com/": "FutureLearn",
"ocw.mit.edu/": "MIT OpenCourseWare",
"www.coursera.org/": "Coursera",
"www.khanacademy.org/": "Khan Academy",
"www.lynda.com/": "Lynda",
"oli.cmu.edu/": "Open Learning Initiative",
"www.udemy.com/": "Udemy",
"www.udacity.com/": "Udacity",
"course.oeru.org/": "OERu",
"www.open.edu/openlearn/": "OpenLearn",
"www.codecademy.com/": "CodeAcademy",
}
def course_platform_from_url(url):
platform = ""
for domain in KNOWN_COURSE_PLATFORMS.keys():
if domain in url:
platform = KNOWN_COURSE_PLATFORMS[domain]
return platform
class TopicGuide(models.Model):
title = models.CharField(max_length=64)
slug = models.SlugField(max_length=64) # start out by matching slug to old topics/keywords
url = models.URLField()
def __str__(self):
return self.title
class Course(LifeTimeTrackingModel):
RESOURCE_FORMATS = [
('course', 'Online Course'),
('book', 'Book'),
('video', 'Video'),
('article', 'Article'),
('group', 'Interest Group'),
('other', 'Other'),
] # TODO not sure I want to make this a enum/choice field ?
OER_LICENSES = ['CC-BY', 'CC-BY-SA', 'CC-BY-NC', 'CC-BY-NC-SA', 'Public Domain']
title = models.CharField(max_length=128)
provider = models.CharField(max_length=256) # changed to creator in UI
link = models.URLField()
resource_format = models.CharField(max_length=128, choices=RESOURCE_FORMATS)
caption = models.CharField(max_length=500)
on_demand = models.BooleanField(default=False)
keywords = models.CharField(max_length=500, blank=True)
topic_guides = models.ManyToManyField(TopicGuide, blank=True, null=True)
language = models.CharField(max_length=6) # ISO language code
created_by = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) # TODO maybe rename to added_by
unlisted = models.BooleanField(default=False)
archived = models.BooleanField(default=False)
license = models.CharField(max_length=128, default="Not sure")
platform = models.CharField(max_length=256, blank=True) # this field is deprecated, but kept for the API
overall_rating = models.FloatField(default=0) # TODO
total_ratings = models.SmallIntegerField(default=0) # TODO
rating_step_counts = models.TextField(default="{}") # JSON value # TODO
discourse_topic_url = models.URLField(blank=True)
def __str__(self):
return self.title
def keyword_list(self):
return self.keywords.split(',')
def rating_step_counts_json(self):
return json.loads(self.rating_step_counts)
def star_max(self):
""" return the number of ratings attributed to the most popular rating """
steps = self.rating_step_counts_json()
return max(steps.values())
def similar_courses(self):
keywords = self.keywords.split(',')
query = Q(keywords__icontains=keywords[0])
for keyword in keywords[1:]:
query = Q(keywords__icontains=keyword) | query
courses = Course.objects.filter(unlisted=False, deleted_at__isnull=True).filter(query).exclude(id=self.id).annotate(
num_learning_circles=Sum(
Case(
When(
studygroup__deleted_at__isnull=True, then=Value(1),
studygroup__course__id=F('id')
),
default=Value(0), output_field=models.IntegerField()
)
)
)[:3]
return courses
def discourse_topic_default_body(self):
return _("<p>What recommendations do you have for other facilitators who are using \"{}\"? Consider sharing additional resources you found helpful, activities that worked particularly well, and some reflections on who this course is best suited for. For more information, see this course on <a href='https://learningcircles.p2pu.org{}'>P2PU’s course page</a>.</p>".format(self.title, reverse('studygroups_course_page', args=(self.id,))))
def get_course_reviews(self):
from studygroups.models import StudyGroup
from surveys.models import FacilitatorSurveyResponse
from surveys.models import facilitator_survey_summary
facilitator_surveys = FacilitatorSurveyResponse.objects.filter(study_group__course=self)
all_surveys = map(facilitator_survey_summary, facilitator_surveys)
all_surveys = filter(lambda s: s.get('course_rating_reason'), all_surveys)
return list(all_surveys)
def get_num_of_facilitator_reviews(self):
from studygroups.models import StudyGroup
from surveys.models import FacilitatorSurveyResponse
from surveys.models import facilitator_survey_summary
studygroup_ids = StudyGroup.objects.filter(course=self.id).distinct().values_list("id", flat=True)
facilitator_surveys = FacilitatorSurveyResponse.objects.filter(study_group__in=studygroup_ids)
all_surveys = list(map(facilitator_survey_summary, facilitator_surveys))
return len(all_surveys)
def get_num_of_learner_reviews(self):
from studygroups.models import StudyGroup
from surveys.models import LearnerSurveyResponse
from surveys.models import learner_survey_summary
studygroup_ids = StudyGroup.objects.filter(course=self.id).distinct().values_list("id", flat=True)
learner_surveys = LearnerSurveyResponse.objects.filter(study_group__in=studygroup_ids)
all_surveys = list(map(learner_survey_summary, learner_surveys))
return len(all_surveys)
def get_language_display(self):
language_info = get_language_info(self.language)
return language_info.get('name_translated')
def get_format_display(self):
f = ( i[1] for i in Course.RESOURCE_FORMATS if i[0] == self.resource_format )
value = next(f, 'Unknown')
return value
|
Python
| 0.000001
|
@@ -447,17 +447,16 @@
e_info%0A%0A
-%0A
from .ba
@@ -505,701 +505,8 @@
on%0A%0A
-KNOWN_COURSE_PLATFORMS = %7B%0A %22www.edx.org/%22: %22edX%22,%0A %22www.futurelearn.com/%22: %22FutureLearn%22,%0A %22ocw.mit.edu/%22: %22MIT OpenCourseWare%22,%0A %22www.coursera.org/%22: %22Coursera%22,%0A %22www.khanacademy.org/%22: %22Khan Academy%22,%0A %22www.lynda.com/%22: %22Lynda%22,%0A %22oli.cmu.edu/%22: %22Open Learning Initiative%22,%0A %22www.udemy.com/%22: %22Udemy%22,%0A %22www.udacity.com/%22: %22Udacity%22,%0A %22course.oeru.org/%22: %22OERu%22,%0A %22www.open.edu/openlearn/%22: %22OpenLearn%22,%0A %22www.codecademy.com/%22: %22CodeAcademy%22,%0A%7D%0A%0A%0A%0Adef course_platform_from_url(url):%0A platform = %22%22%0A%0A for domain in KNOWN_COURSE_PLATFORMS.keys():%0A if domain in url:%0A platform = KNOWN_COURSE_PLATFORMS%5Bdomain%5D%0A%0A return platform%0A%0A
%0Acla
|
89dae839a950bc0e45a7e94d142eafcb45cf2a43
|
Resolve pylint warning about executable without the executable bit.
|
tests/external/py2/testfixture_test.py
|
tests/external/py2/testfixture_test.py
|
#!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
Unit tests for our dependencies in the pytest package; at the time of this
writing, we were using an unreleased version of pytest that added support for
the unittest setUpModule fixture and friends. Some of our tests rely on
setUpModule. Once, there was a conflict with pytest installation in our build
system, and an older version of pytest was installed that didn't support
setUpModule, which resulted in suble side-effects in some of these tests.
"""
import unittest2 as unittest
g_setUpModuleCalled = False
def setUpModule():
global g_setUpModuleCalled
g_setUpModuleCalled = True
class TestPytest(unittest.TestCase):
def testSetUpModuleCalled(self):
self.assertTrue(g_setUpModuleCalled)
if __name__ == '__main__':
unittest.main()
|
Python
| 0
| |
957d31218e44c12dc56dd64a98e62b851c683bf9
|
update static root
|
cfbets/cfbets/settings.py
|
cfbets/cfbets/settings.py
|
"""
Django settings for cfbets project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
from django.contrib.messages import constants as messages
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# moved to local_settings.py
# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG moved to local_settings.py
# allowed_hosts moved to local_settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mailer',
'bets',
]
EMAIL_BACKEND = 'mailer.backend.DbBackend'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'cfbets.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'bets.context_processors.place_bets_form_context_processor',
],
},
},
]
WSGI_APPLICATION = 'cfbets.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
# moved to local_settings.py
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
# moved to local_settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
LOGIN_REDIRECT_URL = '/bets/my_bets'
# override django message tags for bootstrap
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
# import local_settings.py
try:
from local_settings import *
except ImportError:
pass
|
Python
| 0.000001
|
@@ -3193,16 +3193,23 @@
E_DIR, %22
+cfbets_
static%22)
@@ -3213,16 +3213,64 @@
c%22),%0A%5D%0A%0A
+STATIC_ROOT = os.path.join(BASE_DIR, 'static')%0A%0A
LOGIN_RE
|
c91a593507cea9c6ba2777eff741b9e7ec7fdf0f
|
Fix test to give more data on failure
|
tests/integration/cli/custom_module.py
|
tests/integration/cli/custom_module.py
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Daniel Mizyrycki (mzdaniel@glidelink.net)`
tests.integration.cli.custom_module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test salt-ssh sls with a custom module work.
$ cat srv/custom_module.sls
custom-module:
module.run:
- name: test.recho
- text: hello
$ cat srv/_modules/override_test.py
__virtualname__ = 'test'
def __virtual__():
return __virtualname__
def recho(text):
return text[::-1]
$ salt-ssh localhost state.sls custom_module
localhost:
olleh
This test can be run in a small test suite with:
$ python tests/runtests.py -C --ssh
'''
# Import Salt Libs
import integration
class SSHCustomModuleTest(integration.SSHCase):
'''
Test sls with custom module functionality using ssh
'''
def test_ssh_regular_module(self):
'''
Test regular module work using SSHCase environment
'''
expected = 'hello'
cmd = self.run_function('test.echo', arg=['hello'])
self.assertEqual(expected, cmd)
def test_ssh_custom_module(self):
'''
Test custom module work using SSHCase environment
'''
expected = 'hello'[::-1]
cmd = self.run_function('test.recho', arg=['hello'])
self.assertEqual(expected, cmd)
def test_ssh_sls_with_custom_module(self):
'''
Test sls with custom module work using SSHCase environment
'''
expected = {
"module_|-regular-module_|-test.echo_|-run": 'hello',
"module_|-custom-module_|-test.recho_|-run": 'olleh'}
cmd = self.run_function('state.sls', arg=['custom_module'])
for key in cmd:
if not cmd[key]['result']:
raise AssertionError(cmd[key]['comment'])
cmd_ret = cmd[key]['changes'].get('ret', None)
self.assertEqual(cmd_ret, expected[key])
if __name__ == '__main__':
from integration import run_tests
run_tests(SSHCustomModuleTest)
|
Python
| 0.000001
|
@@ -1763,16 +1763,217 @@
if not
+isinstance(cmd, dict) or not isinstance(cmd%5Bkey%5D, dict):%0A raise AssertionError('%7B0%7D is not a proper state return'%0A .format(cmd))%0A elif not
cmd%5Bkey%5D
|
32b33885a42a005fa4e37134e156e149bef1673d
|
make binaries use the new retry for requests
|
chacractl/api/binaries.py
|
chacractl/api/binaries.py
|
import logging
import sys
import os
from textwrap import dedent
from hashlib import sha512
import requests
from tambo import Transport
import chacractl
logger = logging.getLogger(__name__)
class Binary(object):
_help = dedent("""
Operate binaries on a remote chacra instance.
Creating a new binary::
chacractl binary create project/ref/distro/distro_version/arch /path/to/binary
Options:
create Creates a new binary at a given distro version architecture
delete Deletes an existing binary from chacra
--force If the resource exists, force the upload
""")
help_menu = "create, update metadata, or delete binaries"
options = ['create', '--force', 'delete']
def __init__(self, argv):
self.argv = argv
@property
def base_url(self):
return os.path.join(
chacractl.config['url'], 'binaries'
)
def sanitize_filename(self, line):
"""
lines may come with newlines and leading slashes make sure
they are clean so that they can be processed
"""
line = line.strip('\n')
if os.path.isfile(line):
return os.path.abspath(line)
def sanitize_url(self, url_part):
# get rid of the leading slash to prevent issues when joining
url = url_part.lstrip('/')
# and add a trailing slash so that the request is done at the correct
# canonical url
if not url.endswith('/'):
url = "%s/" % url
return url
def load_file(self, filepath):
chsum = sha512()
binary = open(filepath, 'rb')
for chunk in iter(lambda: binary.read(4096), b''):
chsum.update(chunk)
binary.seek(0)
return binary, chsum.hexdigest()
def upload_is_verified(self, arch_url, filename, digest):
r = requests.get(arch_url, verify=chacractl.config['ssl_verify'])
r.raise_for_status()
arch_data = r.json()
remote_digest = arch_data[filename]['checksum']
verified = remote_digest == digest
if not verified:
logging.error(
'Checksum mismatch: server has wrong checksum for %s',
filename)
logging.error('local checksum: %s', digest)
logging.error('remote checksum: %s', remote_digest)
return verified
def post(self, url, filepath):
filename = os.path.basename(filepath)
file_url = os.path.join(url, filename) + '/'
exists = requests.head(file_url, verify=chacractl.config['ssl_verify'])
if exists.status_code == 200:
if not self.force:
logger.warning(
'resource exists and --force was not used, will not upload'
)
logger.warning('SKIP %s', file_url)
return
return self.put(file_url, filepath)
elif exists.status_code == 404:
logger.info('POSTing file: %s', filepath)
binary, digest = self.load_file(filepath)
with binary:
response = requests.post(
url,
files={'file': binary},
auth=chacractl.config['credentials'],
verify=chacractl.config['ssl_verify'])
if response.status_code > 201:
logger.warning("%s -> %s", response.status_code, response.text)
response.raise_for_status()
if not self.upload_is_verified(url, filename, digest):
# Since this is a new file, attempt to delete it
logging.error('Deleting corrupted file from server...')
self.delete(file_url)
raise SystemExit(
'Checksum mismatch: remote server has wrong checksum for %s'
% filepath)
def put(self, url, filepath):
filename = os.path.basename(filepath)
logger.info('resource exists and --force was used, will re-upload')
logger.info('PUTing file: %s', filepath)
binary, digest = self.load_file(filepath)
with binary:
response = requests.put(
url,
files={'file': binary},
auth=chacractl.config['credentials'],
verify=chacractl.config['ssl_verify'])
if response.status_code > 201:
logger.warning("%s -> %s", response.status_code, response.text)
# trim off binary filename
url = url.rsplit('/', 2)[0] + "/"
if not self.upload_is_verified(url, filename, digest):
# Maybe the old file with a different digest is still there, so
# don't delete it
raise SystemExit(
'Checksum mismatch: server has wrong checksum for %s!'
% filepath)
def delete(self, url):
exists = requests.head(url, verify=chacractl.config['ssl_verify'])
if exists.status_code == 404:
logger.warning('resource already deleted')
logger.warning('SKIP %s', url)
return
logger.info('DELETE file: %s', url)
response = requests.delete(
url,
auth=chacractl.config['credentials'],
verify=chacractl.config['ssl_verify'])
if response.status_code < 200 or response.status_code > 299:
logger.warning("%s -> %s", response.status_code, response.text)
def main(self):
self.parser = Transport(self.argv, options=self.options)
self.parser.catch_help = self._help
self.parser.parse_args()
self.force = self.parser.has('--force')
# handle posting binaries:
if self.parser.has('create'):
url_part = self.sanitize_url(self.parser.get('create'))
if not sys.stdin.isatty():
# read from stdin
logger.info('reading input from stdin')
for line in sys.stdin.readlines():
filename = self.sanitize_filename(line)
if not filename:
continue
url = os.path.join(self.base_url, url_part)
self.post(url, filename)
else:
filepath = self.sanitize_filename(self.argv[-1])
if not filepath:
logger.warning(
'provided path does not exist: %s', self.argv[-1]
)
return
url = os.path.join(self.base_url, url_part)
self.post(url, filepath)
elif self.parser.has('delete'):
if self.parser.get('delete') is None:
raise SystemExit('Specify a URL to delete a binary.')
url_part = self.sanitize_url(self.parser.get('delete'))
url = os.path.join(self.base_url, url_part)
self.delete(url)
|
Python
| 0
|
@@ -101,16 +101,17 @@
equests%0A
+%0A
from tam
@@ -147,16 +147,49 @@
hacractl
+%0Afrom chacractl.util import retry
%0A%0Alogger
@@ -1816,16 +1816,29 @@
gest()%0A%0A
+ @retry()%0A
def
@@ -2424,16 +2424,29 @@
rified%0A%0A
+ @retry()%0A
def
@@ -3931,33 +3931,45 @@
%25 filepath)%0A
+ @retry()
%0A
-
def put(self
@@ -4945,24 +4945,36 @@
%25 filepath)%0A
+ @retry()
%0A def del
|
ccc8c0d885c9eaafeba2e91e248bf3febc484ab5
|
change default port to IANA and allow to change peer port
|
pifpaf/drivers/etcd.py
|
pifpaf/drivers/etcd.py
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under 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 pifpaf import drivers
class EtcdDriver(drivers.Driver):
DEFAULT_PORT = 4001
def __init__(self, port=DEFAULT_PORT,
**kwargs):
super(EtcdDriver, self).__init__(**kwargs)
self.port = port
@classmethod
def get_parser(cls, parser):
parser.add_argument("--port",
type=int,
default=cls.DEFAULT_PORT,
help="port to use for etcd")
return parser
def _setUp(self):
super(EtcdDriver, self)._setUp()
http_url = "http://localhost:%d" % self.port
c, _ = self._exec(["etcd",
"--data-dir=" + self.tempdir,
"--listen-client-urls=" + http_url,
"--advertise-client-urls=" + http_url],
wait_for_line="listening for client requests on")
self.addCleanup(self._kill, c.pid)
self.putenv("ETCD_PORT", str(self.port))
self.putenv("URL", "etcd://localhost:%d" % self.port)
|
Python
| 0
|
@@ -626,12 +626,41 @@
T =
-4001
+2379%0A DEFAULT_PEER_PORT = 2380
%0A%0A
@@ -691,32 +691,78 @@
t=DEFAULT_PORT,%0A
+ peer_port=DEFAULT_PEER_PORT,%0A
@@ -848,16 +848,51 @@
t = port
+%0A self.peer_port = peer_port
%0A%0A @c
@@ -1122,16 +1122,219 @@
etcd%22)%0A
+ parser.add_argument(%22--peer-port%22,%0A type=int,%0A default=cls.DEFAULT_PEER_PORT,%0A help=%22port to use for etcd peers%22)%0A
@@ -1419,20 +1419,75 @@
-http
+client_url = %22http://localhost:%25d%22 %25 self.port%0A peer
_url = %22
@@ -1506,32 +1506,37 @@
host:%25d%22 %25 self.
+peer_
port%0A c,
@@ -1597,20 +1597,18 @@
data-dir
-=%22 +
+%22,
self.te
@@ -1614,16 +1614,75 @@
empdir,%0A
+ %22--listen-peer-urls%22, peer_url,%0A
@@ -1717,33 +1717,33 @@
-client-urls
-=%22 + http
+%22, client
_url,%0A
@@ -1791,17 +1791,17 @@
urls
-=%22 + http
+%22, client
_url
@@ -1973,16 +1973,142 @@
.port))%0A
+ self.putenv(%22ETCD_PEER_PORT%22, str(self.peer_port))%0A self.putenv(%22HTTP_URL%22, %22etcd://localhost:%25d%22 %25 self.port)%0A
|
9044657473e949138343132bbfb4c96b137c6abb
|
Use NotImplementedError
|
chainerrl/agents/sarsa.py
|
chainerrl/agents/sarsa.py
|
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
from chainerrl.agents import dqn
class SARSA(dqn.DQN):
"""SARSA.
Unlike DQN, this agent uses actions that have been actually taken to
compute target Q values, thus is an on-policy algorithm.
"""
def _compute_target_values(self, exp_batch, gamma):
batch_next_state = exp_batch['next_state']
batch_next_action = exp_batch['next_action']
next_target_action_value = self.target_q_function(
batch_next_state)
next_q = next_target_action_value.evaluate_actions(
batch_next_action)
batch_rewards = exp_batch['reward']
batch_terminal = exp_batch['is_state_terminal']
return batch_rewards + self.gamma * (1.0 - batch_terminal) * next_q
def batch_act_and_train(self, batch_obs):
raise RuntimeError('SARSA does not support batch training')
def batch_observe_and_train(self, batch_obs, batch_reward,
batch_done, batch_reset):
raise RuntimeError('SARSA does not support batch training')
|
Python
| 0.000002
|
@@ -1041,39 +1041,46 @@
:%0A raise
-Runtime
+NotImplemented
Error('SARSA doe
@@ -1250,15 +1250,22 @@
ise
-Runtime
+NotImplemented
Erro
|
b7108e818316a91d9b2b761af450faa1b99887d1
|
Fix Python functions state which is completely broken (#4027)
|
pulsar-functions/instance/src/main/python/state_context.py
|
pulsar-functions/instance/src/main/python/state_context.py
|
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
# -*- encoding: utf-8 -*-
"""state_context.py: state context for accessing managed state
"""
from abc import abstractmethod
from bookkeeper import admin, kv
from bookkeeper.common.exceptions import NamespaceNotFoundError, StreamNotFoundError, KeyNotFoundError
from bookkeeper.proto import stream_pb2
from bookkeeper.proto.stream_pb2 import HASH
from bookkeeper.proto.stream_pb2 import TABLE
from bookkeeper.types import StorageClientSettings
def new_bk_table_conf(num_ranges):
"""Create a table configuration with the specified `num_ranges`"""
return stream_pb2.StreamConfiguration(
key_type=HASH,
min_num_ranges=num_ranges,
initial_num_ranges=num_ranges,
split_policy=stream_pb2.SplitPolicy(
type=stream_pb2.SplitPolicyType.values()[0],
fixed_range_policy=stream_pb2.FixedRangeSplitPolicy(
num_ranges=2
)
),
rolling_policy=stream_pb2.SegmentRollingPolicy(
size_policy=stream_pb2.SizeBasedSegmentRollingPolicy(
max_segment_size=128 * 1024 * 1024
)
),
retention_policy=stream_pb2.RetentionPolicy(
time_policy=stream_pb2.TimeBasedRetentionPolicy(
retention_minutes=-1
)
),
storage_type=TABLE
)
def create_state_context(state_storage_serviceurl, table_ns, table_name):
"""Create the state context based on state storage serviceurl"""
if state_storage_serviceurl is None:
return NullStateContext()
else:
return BKManagedStateContext(state_storage_serviceurl, table_ns, table_name)
class StateContext(object):
"""Interface defining operations on managed state"""
@abstractmethod
def incr(self, key, amount):
pass
@abstractmethod
def put(self, key, value):
pass
@abstractmethod
def get_value(self, key):
pass
@abstractmethod
def get_amount(self, key):
pass
class NullStateContext(StateContext):
"""A state context that does nothing"""
def incr(self, key, amount):
return
def put(self, key, value):
return
def get_value(self, key):
return None
def get_amount(self, key):
return None
class BKManagedStateContext(StateContext):
"""A state context that access bookkeeper managed state"""
def __init__(self, state_storage_serviceurl, table_ns, table_name):
client_settings = StorageClientSettings(
service_uri=state_storage_serviceurl)
admin_client = admin.client.Client(
storage_client_settings=client_settings)
# create namespace and table if needed
ns = admin_client.namespace(table_ns)
try:
ns.get(stream_name=table_name)
except NamespaceNotFoundError:
admin_client.namespaces().create(namespace=table_ns)
# TODO: make number of table ranges configurable
table_conf = new_bk_table_conf(1)
ns.create(
stream_name=table_name,
stream_config=table_conf)
except StreamNotFoundError:
# TODO: make number of table ranges configurable
table_conf = new_bk_table_conf(1)
ns.create(
stream_name=table_name,
stream_config=table_conf)
self.__client__ = kv.Client(namespace=table_ns)
self.__table__ = self.__client__.table(table_name=table_name)
def incr(self, key, amount):
return self.__table__.incr_str(key, amount)
def get_amount(self, key):
try:
kv = self.__table__.get_str(key)
if kv is not None:
return kv.number_value
else:
return None
except KeyNotFoundError:
return None
def get_value(self, key):
try:
kv = self.__table__.get_str(key)
if kv is not None:
return kv.value
else:
return None
except KeyNotFoundError:
return None
def put(self, key, value):
return self.__table__.put_str(key, value)
def delete_key(self, key):
return self.__table__.delete_str(key)
|
Python
| 0
|
@@ -4196,16 +4196,93 @@
.Client(
+storage_client_settings=client_settings,%0A
namespac
|
85891287a312ea2ff40a67f0ceea45ae7143bec6
|
Update target offices
|
openelex/us/fl/load.py
|
openelex/us/fl/load.py
|
import unicodecsv
from openelex.base.load import BaseLoader
from openelex.lib.text import slugify
from openelex.models import RawResult
from .datasource import Datasource
class LoadResults(BaseLoader):
"""
Loads Florida election results.
Florida results are provided in tab-delimited text files.
A description of fields is available at
https://doe.dos.state.fl.us/elections/resultsarchive/downloadresults.asp?ElectionDate=11/6/2012
Notes:
Some elections appear to have multiple rows representing the same data
e.g. ``20120814__fl__primary.tsv``.
Results with an ``OfficeDesc`` value of "U.S. President by Congressional
District" are by county and congressional district. The county is in
the ``CountyName`` field and the district is in the ``Jurs1num`` field.
The ``CanNameMiddle`` field also includes nicknames, but not in a standard
format. Examples include "Anne 'Libby'" and "(Doc)".
Name suffixes are in the ``CanNameLast`` field, e.g. "Braynon,, II"
Write-in candidates are identified by a value of "Write-In" in the
``PartyName`` field.
"No Party Affiliation" is also a possibility. This is different than
"Independent Party".
Some contests force the last names of the governor and lieutenant
governor into the ``CanNameLast`` and ``CanNameFirst`` fields.
For these records, the value of ``CanNameMiddle`` is '/'.
"""
datasource = Datasource()
target_offices = set([
"U.S. President by Congressional District",
"President of the United States",
"United States Senator",
"United States Representative",
"State Representative",
"State Senate",
"State Senator",
"Governor",
"Governor and Lieutenant Governor",
"Attorney General",
"Chief Financial Officer",
])
district_offices = set([
"United States Representative",
"State Representative",
])
def load(self):
with self._file_handle as csvfile:
results = []
seen = set()
self._common_kwargs = self._build_common_election_kwargs()
reader = unicodecsv.DictReader(csvfile, delimiter='\t',
encoding='latin-1')
for row in reader:
# Skip non-target offices
if not self._skip_row(row):
result = self._prep_result(row)
# Only add non-duplicate results. This is needed because
# there are duplicate results in some data files, e.g.
# 20120814__fl__primary.tsv
key = self._key(result)
if not key in seen:
results.append(result)
seen.add(key)
RawResult.objects.insert(results)
def _skip_row(self, row):
return row['OfficeDesc'].strip() not in self.target_offices
def _prep_result(self, row):
"""
Creates a RawResult model instance for a row of data.
"""
# Copy fields that are common to this source file
result_kwargs = self._common_kwargs.copy()
# Extract remaining fields from the row of data
result_kwargs.update(self._build_contest_kwargs(row))
result_kwargs.update(self._build_candidate_kwargs(row))
result_kwargs.update(self._build_result_kwargs(row))
return RawResult(**result_kwargs)
def _build_contest_kwargs(self, row):
kwargs = {
'office': row['OfficeDesc'].strip(),
}
if kwargs['office'] in self.district_offices:
kwargs['district'] = row['Juris1num'].strip()
return kwargs
def _build_candidate_kwargs(self, row):
# TODO: Figure out how/if suffix is stored
return {
'family_name': row['CanNameLast'].strip(),
'given_name': row['CanNameFirst'].strip(),
'additional_name': row['CanNameMiddle'].strip(),
}
def _build_result_kwargs(self, row):
kwargs = {
'party': row['PartyName'].strip(),
'jurisdiction': row['CountyName'].strip(),
'votes': row['CanVotes'].strip()
}
if row['OfficeDesc'].strip() == "U.S. President by Congressional District":
# Primary results for some contests provide the results
# by congressional district in each county
kwargs['reporting_level'] = 'congressional_district_by_county'
kwargs['reporting_district'] = row['Juris1num'].strip()
else:
kwargs['reporting_level'] = 'county'
return kwargs
def _key(self, rawresult):
"""
Returns a string that uniquely identifies a raw result from a particular
source.
"""
bits = [rawresult.contest_slug, rawresult.candidate_slug,
slugify(rawresult.jurisdiction)]
if rawresult.district:
bits.append(rawresult.district)
try:
bits.append(rawresult.reporting_district)
except AttributeError:
pass
return '-'.join(bits)
|
Python
| 0
|
@@ -1,12 +1,27 @@
+import logging%0A
import unico
@@ -1879,23 +1879,62 @@
ficer%22,%0A
+ %22Commissioner of Agriculture%22,%0A
%5D)%0A
-
%0A dis
@@ -2023,24 +2023,73 @@
sentative%22,%0A
+ %22State Senate%22,%0A %22State Senator%22,%0A
%5D)%0A%0A
@@ -2464,20 +2464,16 @@
if
-not
self._sk
@@ -2486,24 +2486,551 @@
(row): %0A
+ office_name = row%5B'OfficeDesc'%5D.strip()%0A # Log skipped office names in case we forgot to add them%0A # to our list of target offices. Ignore long office names%0A # because these are probably ballot initiatives that we%0A # definitely want to ignore%0A if len(office_name) %3C 100:%0A logging.info(%22Skipping result for office '%25s'%22 %25%0A office_name)%0A continue%0A%0A
@@ -3081,20 +3081,16 @@
-
-
# Only a
@@ -3155,20 +3155,16 @@
-
# there
@@ -3226,20 +3226,16 @@
-
-
# 201208
@@ -3270,20 +3270,16 @@
-
key = se
@@ -3286,36 +3286,32 @@
lf._key(result)%0A
-
@@ -3346,28 +3346,24 @@
-
results.appe
@@ -3365,36 +3365,32 @@
.append(result)%0A
-
|
787d2482e424f0a6bb5fd30bb19a35e852131ac8
|
Remove leading 0s from Jersey stop codes, fix service casing
|
busstops/management/commands/import_guernsey.py
|
busstops/management/commands/import_guernsey.py
|
import os
import json
import requests
from time import sleep
from datetime import date
from bs4 import BeautifulSoup
from django.conf import settings
from django.contrib.gis.geos import Point, LineString, MultiLineString
from django.core.management.base import BaseCommand
from ...models import Region, StopPoint, Service, StopUsage, Operator
def import_stops(region):
with open(os.path.join(settings.DATA_DIR, '{}.json'.format(region.name.lower()))) as open_file:
records = json.load(open_file)
for zoom_level in records:
for place in zoom_level['places']:
assert place['icon'] == ['stop', 'flag-shadow']
name, stop_code = place['name'].split('\n')
assert stop_code.startswith('Bus stop code - ')
_, stop_code = stop_code.split(' - ')
if not stop_code:
continue
defaults = {
'common_name': name,
'naptan_code': int(stop_code),
'latlong': Point(*place['posn'][::-1]),
'locality_centre': False,
'active': True,
}
if ', ' in name:
defaults['common_name'], defaults['indicator'] = name.split(', ')
StopPoint.objects.update_or_create(defaults, atco_code='{}-{}'.format(region.id.lower(), int(stop_code)))
def import_routes(region, operator, url, session):
today = date.today()
res = session.get(url)
soup = BeautifulSoup(res.text, 'lxml')
for li in soup.find(id='main-timetable-list').find_all('li'):
line_name = li.find(class_='tt-key').text.strip()
service = Service.objects.update_or_create(service_code='{}-{}'.format(region.id.lower(), line_name), defaults={
'date': today,
'line_name': line_name,
'description': li.find(class_='tt-text').text.strip(),
'region': region,
'mode': 'bus',
'operator': [operator],
})[0]
import_route_stops(region, service, url, session)
if region.id == 'GG':
import_kml(service, session)
sleep(1)
def import_route_stops(region, service, url, session):
StopUsage.objects.filter(service=service).delete()
res = session.get('{}/{}/FALSE'.format(url, service.line_name))
soup = BeautifulSoup(res.text, 'lxml')
for table in soup.find_all('table', class_='headers'):
i = 0
for tr in table.find_all('tr'):
stop_code = BeautifulSoup(tr.th.previous_element.previous_element, 'lxml').text.strip()
atco_code = '{}-{}'.format(region.id.lower(), stop_code)
if not StopPoint.objects.filter(atco_code=atco_code).exists():
defaults = {
'naptan_code': stop_code,
'locality_centre': False,
'active': True,
}
defaults['common_name'] = tr.th.text.strip()
if ' - ' in defaults['common_name']:
defaults['common_name'], defaults['indicator'] = defaults['common_name'].split(' - ')
doppelganger = StopPoint.objects.filter(
atco_code__startswith=region.id.lower() + '-',
common_name__iexact=defaults['common_name'],
latlong__isnull=False
).first()
if doppelganger:
defaults['latlong'] = doppelganger.latlong
StopPoint.objects.create(atco_code=atco_code, **defaults)
StopUsage.objects.update_or_create(
{
'order': i,
'timing_status': 'OTH'
},
direction=tr.td.get('class')[0].lower(),
stop_id=atco_code,
service=service
)
i += 1
# mark major stops as major
res = session.get('{}/{}/TRUE'.format(url, service.line_name))
soup = BeautifulSoup(res.text, 'lxml')
stop_ids = set()
for table in soup.find_all('table', class_='headers'):
i = 0
for tr in table.find_all('tr'):
stop_code = BeautifulSoup(tr.th.previous_element.previous_element, 'lxml').text.strip()
stop_ids.add('{}-{}'.format(region.id.lower(), stop_code))
StopUsage.objects.filter(service=service, stop_id__in=stop_ids).update(timing_status='PTP')
def import_kml(service, session):
res = session.get('http://buses.gg/kmls/' + service.line_name + '.kml')
kml = BeautifulSoup(res.text, 'lxml')
line_strings = []
for line_string in kml.find_all('coordinates'):
points = [point.split(',') for point in line_string.text.split()]
line_strings.append(LineString(*[Point(float(point[0]), float(point[1])) for point in points]))
service.geometry = MultiLineString(*line_strings)
service.save()
class Command(BaseCommand):
def handle(self, *args, **options):
region = Region.objects.update_or_create(id='GG', defaults={'name': 'Guernsey'})[0]
operator = Operator.objects.update_or_create(id='guernsey', name='Guernsey Buses', region=region)[0]
session = requests.Session()
import_stops(region)
import_routes(region, operator, 'http://buses.gg/routes_and_times/timetables', session)
|
Python
| 0
|
@@ -858,16 +858,55 @@
ontinue%0A
+ stop_code = int(stop_code)%0A
@@ -990,20 +990,16 @@
_code':
-int(
stop_cod
@@ -999,17 +999,16 @@
top_code
-)
,%0A
@@ -1357,20 +1357,16 @@
ower(),
-int(
stop_cod
@@ -1368,17 +1368,16 @@
p_code))
-)
%0A%0A%0Adef i
@@ -1632,32 +1632,40 @@
y').text.strip()
+.upper()
%0A service
@@ -2505,32 +2505,36 @@
stop_code =
+int(
BeautifulSoup(tr
@@ -2584,32 +2584,33 @@
l').text.strip()
+)
%0A atc
@@ -4177,16 +4177,20 @@
_code =
+int(
Beautifu
@@ -4248,32 +4248,33 @@
l').text.strip()
+)
%0A sto
|
8adc911641e301682068393e2a88b0061031c1d9
|
switch to nose.run_exit to see if it will propagate exit code to hudson
|
run_tests.py
|
run_tests.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Testing with Nose
=================
This test runner uses Nose for test discovery and running. It uses the argument
spec of Nose, but with some options pre-set. To begin with, make sure you have
Nose installed, e.g.:
$ sudo easy_install nose
For daily test runs, use:
$ ./run_tests.py
If you supply attributes, the default ones defined in ``DEFAULT_ATTRS`` will be
ignored. So to run e.g. all tests marked ``slowtest`` or ``non_standard_dep``,
do:
$ ./run_tests.py -a slowtest,non_standard_dep
See <http://code.google.com/p/python-nose/> for furher details. An excellent
article is also available at <http://ivory.idyll.org/articles/nose-intro.html>.
Note that this is just a convenience script. You can use ``nosetests`` directly
if it's on $PATH, with the difference that you have to supply the options
pre-set here manually.
Coverage
========
If ``coverage.py`` is placed in $PYTHONPATH, it can be used to create coverage
information (using the built-in coverage plugin of Nose) if the default
option "--with-coverage" is supplied (which also enables some additional
coverage options).
See <http://nedbatchelder.com/code/modules/coverage.html> for details.
"""
NOSE_ARGS = [
'--where=./',
'--with-doctest',
'--doctest-extension=.doctest',
'--doctest-tests',
# '--with-EARL',
]
COVERAGE_EXTRA_ARGS = [
'--cover-package=rdflib',
'--cover-inclusive',
]
DEFAULT_ATTRS = ['!slowtest', '!unstable', '!non_standard_dep', '!manual', '!non_core', '!sparql']
DEFAULT_DIRS = ['test', 'rdflib']
if __name__ == '__main__':
from sys import argv, exit, stderr
try: import nose
except ImportError:
print >>stderr, """\
Requires Nose. Try:
$ sudo easy_install nose
Exiting. """; exit(1)
if '--with-coverage' in argv:
try: import coverage
except ImportError:
print >>stderr, "No coverage module found, skipping code coverage."
argv.remove('--with-coverage')
else:
NOSE_ARGS += COVERAGE_EXTRA_ARGS
if True not in [a.startswith('-a') or a.startswith('--attr=') for a in argv]:
argv.append('--attr=' + ','.join(DEFAULT_ATTRS))
if not [a for a in argv[1:] if not a.startswith('-')]:
argv += DEFAULT_DIRS # since nose doesn't look here by default..
finalArgs = argv + NOSE_ARGS
print "Running nose with:", " ".join(finalArgs[1:])
nose.run(argv=finalArgs)
# TODO: anything from the following we've left behind?
old_run_tests = """
import logging
_logger = logging.getLogger()
_logger.setLevel(logging.ERROR)
_formatter = logging.Formatter('%(name)s %(levelname)s %(message)s')
_handler = logging.StreamHandler()
_handler.setFormatter(_formatter)
_logger.addHandler(_handler)
import unittest, inspect
import rdflib
quick = True
verbose = True
from test.IdentifierEquality import IdentifierEquality
from test.sparql.QueryTestCase import QueryTestCase
from test.graph import *
from test.triple_store import *
from test.context import *
# # Graph no longer has the type checking at the moment. Do we want to
# # put it back? Should we?
# #
# # from test.type_check import *
from test.parser import *
if not quick:
from test import parser_rdfcore
if verbose:
parser_rdfcore.verbose = 1
from test.parser_rdfcore import *
from test.Sleepycat import *
from test.rdf import * # how does this manage to be 9 tests?
from test.n3 import *
from test.n3_quoting import *
from test.nt import *
from test.trix import *
from test.util import *
from test.seq import SeqTestCase
#from test.store_performace import *
from test.rules import *
from test.n3Test import *
from test.JSON import JSON
import test.rdfa
from test.events import *
def run():
# TODO: Fix failed test and comment back in.
# test.rdfa.main()
if verbose:
ts = unittest.makeSuite
tests = [
c for c in vars().values()
if inspect.isclass(c)
and not isinstance(c, rdflib.Namespace)
and issubclass(c, unittest.TestCase)
]
suite = unittest.TestSuite(map(ts, tests))
unittest.TextTestRunner(verbosity=2).run(suite)
else:
unittest.main()
"""
|
Python
| 0.000003
|
@@ -2501,16 +2501,21 @@
nose.run
+_exit
(argv=fi
|
fe77a38380aa9bb1b3e1c72b445c0a23f4deae3f
|
Fix tests
|
tests.py
|
tests.py
|
import re
import unittest
from django.template import Template, Context
from django.template import TemplateSyntaxError as DjangoTemplateSyntaxError
from django.conf import settings
from jinja2 import TemplateSyntaxError as Jinja2TemplateSyntaxError
from jinja2 import Environment
from jinja2 import FileSystemLoader
import chartkick
# python 2.6 support
if not hasattr(unittest.TestCase, 'assertIn'):
import unittest2 as unittest
settings.configure()
settings.INSTALLED_APPS = ('chartkick',)
settings.STATICFILES_DIRS = (chartkick.js(),)
settings.STATIC_URL = ''
class TestsBase(object):
TemplateSyntaxError = None
def render(self, template, context=None):
raise NotImplementedError
def test_missing_vaiable(self):
self.assertRaises(self.TemplateSyntaxError,
self.render, '{% line_chart %}')
def test_empty(self):
chart = self.render('{% line_chart data %}', dict(data={}))
self.assertIn('Chartkick.LineChart', chart)
self.assertIn('id', chart)
self.assertIn('height', chart)
def test_line_chart(self):
chart = self.render('{% line_chart data %}', dict(data={}))
self.assertIn('Chartkick.LineChart', chart)
self.assertNotIn('Chartkick.PieChart', chart)
self.assertNotIn('Chartkick.ColumnChart', chart)
self.assertNotIn('Chartkick.BarChart', chart)
self.assertNotIn('Chartkick.AreaChart', chart)
def test_pie_chart(self):
chart = self.render('{% pie_chart data %}', dict(data={}))
self.assertNotIn('Chartkick.LineChart', chart)
self.assertIn('Chartkick.PieChart', chart)
self.assertNotIn('Chartkick.ColumnChart', chart)
self.assertNotIn('Chartkick.BarChart', chart)
self.assertNotIn('Chartkick.AreaChart', chart)
def test_column_chart(self):
chart = self.render('{% column_chart data %}', dict(data={}))
self.assertNotIn('Chartkick.LineChart', chart)
self.assertNotIn('Chartkick.PieChart', chart)
self.assertIn('Chartkick.ColumnChart', chart)
self.assertNotIn('Chartkick.BarChart', chart)
self.assertNotIn('Chartkick.AreaChart', chart)
def test_bar_chart(self):
chart = self.render('{% bar_chart data %}', dict(data={}))
self.assertNotIn('Chartkick.LineChart', chart)
self.assertNotIn('Chartkick.PieChart', chart)
self.assertNotIn('Chartkick.ColumnChart', chart)
self.assertIn('Chartkick.BarChart', chart)
self.assertNotIn('Chartkick.AreaChart', chart)
def test_area_chart(self):
chart = self.render('{% area_chart data %}', dict(data={}))
self.assertNotIn('Chartkick.LineChart', chart)
self.assertNotIn('Chartkick.PieChart', chart)
self.assertNotIn('Chartkick.ColumnChart', chart)
self.assertNotIn('Chartkick.BarChart', chart)
self.assertIn('Chartkick.AreaChart', chart)
def test_all_charts(self):
template = """{% line_chart data %}
{% pie_chart data %}
{% column_chart data %}
{% bar_chart data %}
{% area_chart data %}"""
chart = self.render(template, dict(data={}))
self.assertIn('Chartkick.LineChart', chart)
self.assertIn('Chartkick.PieChart', chart)
self.assertIn('Chartkick.ColumnChart', chart)
self.assertIn('Chartkick.BarChart', chart)
self.assertIn('Chartkick.AreaChart', chart)
@unittest.skip('Embedded data is not implemented yet')
def test_data_embeded(self):
chart = self.render('{% line_chart {"foo":35,"bar":12} %}')
self.assertIn('foo', chart)
self.assertIn('bar', chart)
def test_data_context(self):
chart = self.render('{% line_chart foo %}', dict(foo='bar'))
self.assertNotIn('foo', chart)
self.assertIn('bar', chart)
def test_missing_with(self):
self.assertRaises(self.TemplateSyntaxError,
self.render, '{% line_chart data x=y %}')
def test_options_embeded(self):
chart = self.render('{% line_chart foo with library={"title": "eltit"} %}',
dict(foo='bar'))
self.assertNotIn('foo', chart)
self.assertIn('bar', chart)
self.assertIn('library', chart)
self.assertIn('title', chart)
self.assertIn('eltit', chart)
def test_options_context(self):
chart = self.render('{% line_chart "" with foo=bar %}',
dict(bar=123))
self.assertNotIn('data', chart)
self.assertIn('foo', chart)
self.assertNotIn('bar', chart)
self.assertIn('123', chart)
def test_spaces(self):
templates = ('{%line_chart data %}', '{% line_chart data %}',
'{% line_chart data %}', '{% line_chart data%}',
'{% line_chart data with x="foo bar" %}',
'{% line_chart data with x=1%}')
for template in templates:
chart = self.render(template, dict(data='foo'))
self.assertIn('Chartkick.LineChart', chart)
self.assertNotIn('data', chart)
self.assertIn('foo', chart)
def test_id(self):
chart1 = self.render('{% line_chart "" with id=123 %}')
chart2 = self.render('{% line_chart "" %}{% line_chart "" %}')
ids = re.findall('id=\"(.*?)\"', chart2)
self.assertIn('123', chart1)
self.assertIn('id', chart1)
self.assertNotEqual(ids[0], ids[1])
def test_invalid_options(self):
self.assertRaises(self.TemplateSyntaxError, self.render,
'{% line_chart "" with library= %}')
self.assertRaises(self.TemplateSyntaxError, self.render,
'{% line_chart "" with library={"title":"test" %}')
self.assertRaises(self.TemplateSyntaxError, self.render,
'{% line_chart "" with library="title":"test" %}')
self.assertRaises(self.TemplateSyntaxError, self.render,
'{% line_chart "" with library={"title: "test"} %}')
self.assertRaises(self.TemplateSyntaxError, self.render,
'{% line_chart "" with library={"title": "test} %}')
self.assertRaises(self.TemplateSyntaxError, self.render,
'{% line_chart "" with library={"title": } %}')
class DjangoTests(unittest.TestCase, TestsBase):
TemplateSyntaxError = DjangoTemplateSyntaxError
def render(self, template, context=None):
context = context or {}
template = '{% load chartkick %}' + template
t = Template(template)
c = Context(context)
return t.render(c)
class Jinja2Tests(unittest.TestCase, TestsBase):
TemplateSyntaxError = Jinja2TemplateSyntaxError
def render(self, template, context=None):
context = context or {}
env = Environment(extensions=['chartkick.ext.charts'])
env.loader = FileSystemLoader('.')
return env.from_string(template).render(context)
if __name__ == '__main__':
unittest.main()
|
Python
| 0.000003
|
@@ -331,16 +331,17 @@
rtkick%0A%0A
+%0A
# python
@@ -570,16 +570,47 @@
= ''%0A%0A%0A
+import django%0Adjango.setup()%0A%0A%0A
class Te
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.