text stringlengths 0 1.05M | meta dict |
|---|---|
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/Rambatino/Kruskals
"""
import re
from os import path
from setuptools import setup, find_packages
def get_version():
"""
Read version from __init__.py
"""
version_regex = re.compile(
'__version__\\s*=\\s*(?P<q>[\'"])(?P<version>\\d+(\\.\\d+)*)(?P=q)'
)
here = path.abspath(path.dirname(__file__))
init_location = path.join(here, "Kruskals/__init__.py")
with open(init_location) as init_file:
for line in init_file:
match = version_regex.search(line)
if not match:
raise Exception(
"Couldn't read version information from '%s'" % init_location
)
return match.group('version')
setup(
name='Kruskals',
version=get_version(),
description='Calculation of Kruskals Distance Measure',
long_description="This package provides a python implementation of Kruskals Distance measure",
url='https://github.com/Rambatino/Kruskals',
author='Mark Ramotowski',
author_email='mark.tint.ramotowski@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
python_requires='>3.5',
keywords='Kruskals pandas numpy scipy statistics statistical analysis',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=['numpy>1.17', 'scipy', 'pandas'],
extras_require={
'dev': ['check-manifest'],
'test': ['codecov', 'pytest', 'pytest-cov'],
}
)
| {
"repo_name": "Rambatino/Kruskals",
"path": "setup.py",
"copies": "1",
"size": "1864",
"license": "mit",
"hash": -7372612379810100000,
"line_mean": 30.593220339,
"line_max": 98,
"alpha_frac": 0.6201716738,
"autogenerated": false,
"ratio": 3.7354709418837677,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4855642615683768,
"avg_score": null,
"num_lines": null
} |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
import os
import re
ROOT = os.path.dirname(__file__)
VERSION_RE = re.compile(r'''__version__ = ['"]([0-9.]+)['"]''')
requires = [
'numpy>=1.12.1',
'tensorflow>=1.0.0',
'nose',
]
# Define package version
def get_version():
init = open(os.path.join(ROOT, 'facefinder', '__init__.py')).read()
return VERSION_RE.search(init).group(1)
# Get the long description from the README file
def readme():
open('README.rst').read()
setup(
name='facefinder',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version=get_version(),
description='Face Detection using deep learning',
long_description=readme(),
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Natural Language :: English',
'Topic :: Software Development :: Libraries :: Python Modules',
'Environment :: Plugins',
],
keywords=['face detection', 'machine learning', 'deep learning', 'facefinder', 'akkefa'],
url='https://github.com/akkefa/facefinder',
author='Ikram Ali',
author_email='mrikram1989@gmail.com',
license='Apache License 2.0',
packages=find_packages(),
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=requires,
test_suite='nose.collector',
tests_require=['nose', ],
entry_points={
'console_scripts': [
'facefinder = facefinder.commands.dev:print_development'
],
},
include_package_data=True,
zip_safe=False
)
| {
"repo_name": "akkefa/facefinder",
"path": "setup.py",
"copies": "1",
"size": "2784",
"license": "apache-2.0",
"hash": -3479578462949787600,
"line_mean": 26.2941176471,
"line_max": 93,
"alpha_frac": 0.6447557471,
"autogenerated": false,
"ratio": 3.988538681948424,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5133294429048424,
"avg_score": null,
"num_lines": null
} |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html """
from setuptools import setup, find_packages
from codecs import open
from os import path
from apt_select import __version__
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='apt-select',
version=__version__,
description='Ubuntu Archive Mirror reporting tool for apt sources configuration',
long_description=long_description,
url='https://github.com/jblakeman/apt-select',
author='John Blakeman',
author_email='john@johnblakeman.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: System :: Installation/Setup',
'Topic :: System :: Networking',
'Topic :: System :: Software Distribution',
'Topic :: System :: Systems Administration',
'Topic :: Utilities',
],
keywords='latency status rank reporting apt configuration',
packages=find_packages(exclude=['tests']),
install_requires=['requests', 'beautifulsoup4'],
entry_points = {
'console_scripts': [
'apt-select = apt_select.__main__:main'
]
}
)
| {
"repo_name": "jblakeman/apt-select",
"path": "setup.py",
"copies": "1",
"size": "1832",
"license": "mit",
"hash": 1431426399645122800,
"line_mean": 34.2307692308,
"line_max": 85,
"alpha_frac": 0.6239082969,
"autogenerated": false,
"ratio": 4.211494252873563,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00205511542720845,
"num_lines": 52
} |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='ezhost',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.5.2',
description='Let server install became simple and easy.',
long_description=long_description,
# The project's main homepage.
url='https://github.com/zhexiao/ezhost.git',
# Author details
author='Zhe Xiao',
author_email='zhexiao@163.com',
# Choose your license
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 5 - Production/Stable',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
# What does your project relate to?
keywords='server install',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(exclude=['docs']),
# Alternatively, if you want to distribute just a my_module.py, uncomment
# this:
# py_modules=["my_module"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['Fabric3'],
# List additional groups of dependencies here (e.g. development
# dependencies). You can install these using the following syntax,
# for example:
# $ pip install -e .[dev,test]
extras_require={
# 'dev': ['check-manifest'],
# 'test': ['coverage'],
},
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
package_data={
# 'sample': ['package_data.dat'],
},
# Although 'package_data' is the preferred approach, in some case you may
# need to place data files outside of your packages. See:
# http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa
# In this case, 'data_file' will be installed into '<sys.prefix>/my_data'
data_files=[
# ('my_data', ['data/data_file'])
],
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
entry_points={
'console_scripts': [
'ezhost=ezhost.main:main',
],
},
)
| {
"repo_name": "zhexiao/ezhost",
"path": "setup.py",
"copies": "1",
"size": "3909",
"license": "mit",
"hash": -5762647620827655000,
"line_mean": 33.9017857143,
"line_max": 94,
"alpha_frac": 0.6566896905,
"autogenerated": false,
"ratio": 4.071875,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 112
} |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
"""
# To use a consistent encoding
from codecs import open
from os import path
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
# with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
# long_description = f.read()
setup(
name='StackItDecklist',
version='1.4.0',
description='Generates visual decklists for various TCGs',
url='https://github.com/poppu-mtg/StackIt',
author='Guillaume Robert-Demolaize & Katelyn Gigante',
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Topic :: Games/Entertainment :: Board Games',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
],
keywords='mtg tcg',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
# https://packaging.python.org/en/latest/requirements.html
install_requires=[
'lxml',
'pillow',
'requests',
'pyYAML',
'watchdog',
'cachecontrol[filecache]',
'appdirs'
],
# extras_require={
# 'dev': ['check-manifest'],
# 'test': ['coverage'],
# },
package_data={
'StackIt': [
'resources/StackIt-Logo.png'
'resources/*/*.ttf',
'resources/*/*.otf',
'resources/*/*.png',
'resources/*/*.dat',
],
},
scripts=['StackIt.py'],
)
| {
"repo_name": "silasary/StackIt",
"path": "setup.py",
"copies": "1",
"size": "1948",
"license": "mit",
"hash": -862048998801612400,
"line_mean": 26.0555555556,
"line_max": 66,
"alpha_frac": 0.59137577,
"autogenerated": false,
"ratio": 3.842209072978304,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9933584842978304,
"avg_score": 0,
"num_lines": 72
} |
"""A setuptools based setup module.
See:
https://packaging.python.org/guides/distributing-packages-using-setuptools/
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
# Arguments marked as "Required" below must be included for upload to PyPI.
# Fields marked as "Optional" may be commented out.
setup(
# This is the name of your project. The first time you publish this
# package, this name will be registered for you. It will determine how
# users can install this project, e.g.:
#
# $ pip install sampleproject
#
# And where it will live on PyPI: https://pypi.org/project/sampleproject/
#
# There are some restrictions on what makes a valid project name
# specification here:
# https://packaging.python.org/specifications/core-metadata/#name
name='verdict', # Required
# Versions should comply with PEP 440:
# https://www.python.org/dev/peps/pep-0440/
#
# For a discussion on single-sourcing the version across setup.py and the
# project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='0.6.1', # Required
# This is a one-line description or tagline of what your project does. This
# corresponds to the "Summary" metadata field:
# https://packaging.python.org/specifications/core-metadata/#summary
description='Data analytics in a new dimension', # Optional
# This is an optional longer description of your project that represents
# the body of text which users will see when they visit PyPI.
#
# Often, this is the same as your README, so you can just read it in from
# that file directly (as we have already done above)
#
# This field corresponds to the "Description" metadata field:
# https://packaging.python.org/specifications/core-metadata/#description-optional
long_description=long_description, # Optional
# Denotes that our long_description is in Markdown; valid values are
# text/plain, text/x-rst, and text/markdown
#
# Optional if long_description is written in reStructuredText (rst) but
# required for plain-text or Markdown; if unspecified, "applications should
# attempt to render [the long_description] as text/x-rst; charset=UTF-8 and
# fall back to text/plain if it is not valid rst" (see link below)
#
# This field corresponds to the "Description-Content-Type" metadata field:
# https://packaging.python.org/specifications/core-metadata/#description-content-type-optional
long_description_content_type='text/markdown', # Optional (see note above)
# This should be a valid link to your project's main homepage.
#
# This field corresponds to the "Home-Page" metadata field:
# https://packaging.python.org/specifications/core-metadata/#home-page-optional
url='https://verdict.readthedocs.io/en/latest/', # Optional
# This should be your name or the name of the organization which owns the
# project.
author='Verdict Team', # Optional
# This should be a valid email address corresponding to the author listed
# above.
author_email='pyongjoo@umich.edu', # Optional
# This field adds keywords for your project which will appear on the
# project page. What does your project relate to?
#
# Note that this is a string of words separated by whitespace, not a list.
# keywords='sample setuptools development', # Optional
# You can just specify package directories manually here if your project is
# simple. Or you can use find_packages().
#
# Alternatively, if you just want to distribute a single Python file, use
# the `py_modules` argument instead as follows, which will expect a file
# called `my_module.py` to exist:
#
# py_modules=["my_module"],
#
packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Required
# Specify which Python versions you support. In contrast to the
# 'Programming Language' classifiers above, 'pip install' will check this
# and refuse to install the project if the version does not match. If you
# do not support Python 2, you can simplify this to '>=3.5' or similar, see
# https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires
python_requires='>=3.5',
# This field lists other packages that your project depends on to run.
# Any package you put here will be installed by pip when your project is
# installed, so they must be valid existing projects.
#
# For an analysis of "install_requires" vs pip's requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['redis', 'pandas', 'moz_sql_parser', 'presto-python-client', 'psutil'], # Optional
license='APACHE LICENSE, VERSION 2.0',
# List additional groups of dependencies here (e.g. development
# dependencies). Users will be able to install these using the "extras"
# syntax, for example:
#
# $ pip install sampleproject[dev]
#
# Similar to `install_requires` above, these must be valid existing
# projects.
# extras_require={ # Optional
# 'dev': ['check-manifest'],
# 'test': ['coverage'],
# },
# If there are data files included in your packages that need to be
# installed, specify them here.
#
# If using Python 2.6 or earlier, then these have to be included in
# MANIFEST.in as well.
# package_data={ # Optional
# 'sample': ['package_data.dat'],
# },
# Although 'package_data' is the preferred approach, in some case you may
# need to place data files outside of your packages. See:
# http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files
#
# In this case, 'data_file' will be installed into '<sys.prefix>/my_data'
# data_files=[('my_data', ['data/data_file'])], # Optional
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# `pip` to create the appropriate form of executable for the target
# platform.
#
# For example, the following would provide a command called `sample` which
# executes the function `main` from this package when invoked:
entry_points = { # Optional
'console_scripts': [
# 'verdict-server=verdict.server:main',
'pandas-sql-server=verdict.pandas_sql.pandas_sql_server:main',
],
},
# List additional URLs that are relevant to your project as a dict.
#
# This field corresponds to the "Project-URL" metadata fields:
# https://packaging.python.org/specifications/core-metadata/#project-url-multiple-use
#
# Examples listed include a pattern for specifying where the package tracks
# issues, where the source is hosted, where to say thanks to the package
# maintainers, and where to support the project financially. The key is
# what's used to render the link text on PyPI.
# project_urls={ # Optional
# 'Bug Reports': 'https://github.com/pypa/sampleproject/issues',
# 'Funding': 'https://donate.pypi.org',
# 'Say Thanks!': 'http://saythanks.io/to/example',
# 'Source': 'https://github.com/pypa/sampleproject/',
# },
)
| {
"repo_name": "mozafari/verdict",
"path": "setup.py",
"copies": "1",
"size": "7619",
"license": "apache-2.0",
"hash": -868457036131767300,
"line_mean": 42.5371428571,
"line_max": 105,
"alpha_frac": 0.6905105657,
"autogenerated": false,
"ratio": 4.005783385909569,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0004002287021154946,
"num_lines": 175
} |
"""A setuptools based setup module.
See:
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='random_matrix_factorization',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='0.1.dev',
description='random_matrix_factorization is a Python library for randomized linear algebra.',
long_description=long_description,
# The project's main homepage.
url='https://github.com/AyoubBelhadji/random_matrix_factorization',
# Author details
author='Ayoub Belhadji',
author_email='ayoub.belhadji@gmail.com',
# Choose your license
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
#'Programming Language :: Python :: 2',
#'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
# What does your project relate to?
keywords='Random linear algebra',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
# packages=find_packages(exclude=['contrib', 'docs', 'tests']),
# Alternatively, if you want to distribute just a my_module.py, uncomment
# this:
# py_modules=["my_module"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['numpy','matplotlib'],
# List additional groups of dependencies here (e.g. development
# dependencies). You can install these using the following syntax,
# for example:
# $ pip install -e .[dev,test]
# extras_require={
# 'dev': ['check-manifest'],
# 'test': ['coverage'],
# },
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
# package_data={
# 'sample': ['package_data.dat'],
# },
# Although 'package_data' is the preferred approach, in some case you may
# need to place data files outside of your packages. See:
# http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa
# In this case, 'data_file' will be installed into '<sys.prefix>/my_data'
# data_files=[('my_data', ['data/data_file'])],
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
# entry_points={
# 'console_scripts': [
# 'sample=sample:main',
# ],
# },
)
| {
"repo_name": "AyoubBelhadji/random_matrix_factorization",
"path": "setup.py",
"copies": "1",
"size": "4025",
"license": "mit",
"hash": 4173264214940590600,
"line_mean": 35.2612612613,
"line_max": 97,
"alpha_frac": 0.6571428571,
"autogenerated": false,
"ratio": 4.045226130653266,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5202368987753266,
"avg_score": null,
"num_lines": null
} |
"""A setuptools based setup module.
Template taken from: https://raw.githubusercontent.com/pypa/sampleproject/master/setup.py
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='rnr-debugging-scripts',
version='0.1.3',
description='A Project with Retrieve and Rank helper scripts and examples',
long_description=long_description,
url='https://github.ibm.com/rchakravarti/rnr-debugging-scripts',
author='rchakravarti',
author_email='rchakravarti@us.ibm.com',
license='Apache 2.0',
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Bluemix :: Retrieve and Rank',
'License :: OSI Approved :: Apache License',
'Programming Language :: Python :: 3.5',
],
keywords='retrieve and rank RnR discovery bluemix evaluation information retrieval sample example debugging scripts',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=[line for line in open('requirements.txt').read().splitlines() if not line.startswith('--')],
# for example:
# $ pip install -e .[examples]
extras_require={
'examples': [line for line in open('requirements-examples.txt').read().splitlines() if not line.startswith('--')],
},
)
| {
"repo_name": "rchaks/retrieve-and-rank-tuning",
"path": "setup.py",
"copies": "1",
"size": "1840",
"license": "apache-2.0",
"hash": -6946175415349479000,
"line_mean": 33.0740740741,
"line_max": 122,
"alpha_frac": 0.6777173913,
"autogenerated": false,
"ratio": 3.923240938166311,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5100958329466311,
"avg_score": null,
"num_lines": null
} |
"""A setuptools based setup module"""
from setuptools import setup, find_packages
from codecs import open # To use a consistent encoding
from os import path
current_path = path.abspath(path.dirname(__file__))
# Can read description from README.rst
with open(path.join(current_path, 'README.rst'), encoding='utf-8') as f:
project_description = f.read()
# Calling global setup function
setup(
name='lflask',
version='1.0.0',
description='Learning how to integrate kerberos and tornado with Flask',
long_description=project_description,
url='git url here',
author='Rishi Mishra',
author_email='rishi.x.mishra@gmail.com',
license='Free for use',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Web Servers',
'License :: Free for use',
'Programming Language :: Python :: 2.7',
],
keywords='flask tornado kerberos integration sample',
packages=find_packages(exclude=['tests']),
install_requires=['flask', 'tornado'],
extras_require={
'dev': ['check-manifest'],
'test': ['coverage'],
},
# package_data
# data_files
# entry_points
test_suite='nose.collector',
tests_require=['nose'],
) | {
"repo_name": "rishimishra/flask_tornado",
"path": "setup.py",
"copies": "1",
"size": "1228",
"license": "mit",
"hash": 7499243996641499,
"line_mean": 27.2857142857,
"line_max": 73,
"alpha_frac": 0.6840390879,
"autogenerated": false,
"ratio": 3.449438202247191,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46334772901471916,
"avg_score": null,
"num_lines": null
} |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='rfmt',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.0.0',
description='rfmt',
long_description=long_description,
# The project's main homepage.
url='https://github.com/pypa/sampleproject',
# Author details
author='Phillip Yelland',
author_email='phillip.yelland@gmail.com',
# Choose your license
license='Apache',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: Apache Software License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
],
# What does your project relate to?
keywords='linter development format',
packages=['rfmt'],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['ply'],
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
entry_points={
'console_scripts': [
'rfmt = rfmt.rfmt:main',
],
},
) | {
"repo_name": "google/rfmt",
"path": "inst/python/setup.py",
"copies": "1",
"size": "2578",
"license": "apache-2.0",
"hash": 2708655374710695400,
"line_mean": 30.25,
"line_max": 79,
"alpha_frac": 0.6505042669,
"autogenerated": false,
"ratio": 4.191869918699187,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0125,
"num_lines": 80
} |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
import glob
import sys
from setuptools import setup, find_packages
# To use a consistent encoding
if 'py2exe' in sys.argv:
import py2exe
setup(
name='steam_vr_wheel',
# Choose your license
license='MIT',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
#install_requires=['openvr==1.0.301', 'numpy'],
install_requires=['openvr', 'numpy', 'wxPython==4.0.0a3' ],
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
include_package_data=True,
zip_safe=False,
package_data={
'steam_vr_wheel': ['steam_vr_wheel/pyvjoy/vJoyInterface.dll', 'steam_vr_wheel/pyvjoy/vJoyInterface.lib'],
},
data_files=[('.', glob.glob('*.dll')),
('.', glob.glob('*.pyd'))],
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
entry_points={
'console_scripts': [
'vrwheel=steam_vr_wheel.wheel:main',
'vrjoystick=steam_vr_wheel.joystick:main_j',
'vrdoublejoystick=steam_vr_wheel.doublejoystick:main_dj',
'vrpad=steam_vr_wheel.pad:main_p',
'vrpadconfig=steam_vr_wheel.configurator:run',
],
},
)
| {
"repo_name": "mdovgialo/steam-vr-wheel",
"path": "setup.py",
"copies": "1",
"size": "1714",
"license": "mit",
"hash": 6484324630380514000,
"line_mean": 29.1636363636,
"line_max": 113,
"alpha_frac": 0.6341890315,
"autogenerated": false,
"ratio": 3.5267489711934155,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4660938002693415,
"avg_score": null,
"num_lines": null
} |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
from composite_plate import __version__
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='composite-plate',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version=__version__,
description='A library to perform basic composite plate theory calculations',
long_description=long_description,
# The project's main homepage.
url='https://github.com/johnrbnsn/Composite-Plate',
# Author details
author='John M. Robinson',
author_email='john.rbnsn@gmail.com',
# Choose your license
license="MIT",
# What does your project relate to?
keywords='composite mechanics engineering',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['numpy']
)
| {
"repo_name": "johnrbnsn/Composite-Plate",
"path": "setup.py",
"copies": "1",
"size": "1795",
"license": "mit",
"hash": -4926776480214546000,
"line_mean": 31.8679245283,
"line_max": 81,
"alpha_frac": 0.6874651811,
"autogenerated": false,
"ratio": 4.033707865168539,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.019095248920209137,
"num_lines": 53
} |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distripip install buting.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='ixnetwork-rest',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='0.55a57',
description='IxNetwork REST API Client',
long_description=long_description,
# The project's main homepage.
url='https://github.com/ajbalogh/ixnetwork_client_python',
# Author details
author='andrey.balogh@gmail.com',
author_email='andrey.balogh@gmail.com',
# Choose your license
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
# What does your project relate to?
keywords='ixnetwork rest automation development',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(exclude=['contrib', 'docs', 'tests', 'utils', 'samples']),
package_data={'ixnetwork': [
'samples/*.py',
'samples/create/*.py',
'samples/sessions/*.py',
'samples/global/*.py',
'samples/emulation_host/*.py',
'samples/emulation_host/*.ixncfg',
'samples/query/*.py'
]
},
# If your project only runs on certain Python versions,
# setting the python_requires argument to the appropriate
# PEP 440 version specifier string will prevent pip from installing
# the project on other Python versions.
python_requires='>=2.7, <4',
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=[
'requests'
],
)
| {
"repo_name": "OpenIxia/ixnetwork_client_python",
"path": "setup.py",
"copies": "1",
"size": "3141",
"license": "mit",
"hash": 2014105984992166000,
"line_mean": 32.5164835165,
"line_max": 85,
"alpha_frac": 0.6453358803,
"autogenerated": false,
"ratio": 4.127463863337714,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5272799743637714,
"avg_score": null,
"num_lines": null
} |
"""A setuptools module for the Saliency library.
See:
https://packaging.python.org/en/latest/distributing.html
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='saliency',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='0.1.3',
description='Framework-agnostic saliency methods',
long_description=long_description,
long_description_content_type='text/markdown',
# The project's main homepage.
url='https://github.com/pair-code/saliency',
# Author details
author='The saliency authors',
author_email='tf-saliency-dev@google.com',
# Choose your license
license='Apache 2.0',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
# What does your project relate to?
keywords='saliency mask neural network deep learning',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(),
#package_dir={'': '.'},
#packages=[''],
# Alternatively, if you want to distribute just a my_module.py, uncomment
# this:
#py_modules=['saliency'],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['numpy', 'scikit-image'],
# List additional groups of dependencies here (e.g. development
# dependencies). You can install these using the following syntax,
# for example:
# $ pip install -e .[full,tf1]
# $ pip install -e ".[full,tf1]" (if using zsh)
extras_require={
"full": ['tensorflow>=1.15'],
"tf1": ['tensorflow>=1.15'],
}
)
| {
"repo_name": "PAIR-code/saliency",
"path": "setup.py",
"copies": "1",
"size": "2996",
"license": "apache-2.0",
"hash": 3943907822039059500,
"line_mean": 32.2888888889,
"line_max": 79,
"alpha_frac": 0.6578771696,
"autogenerated": false,
"ratio": 3.9525065963060686,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001322751322751323,
"num_lines": 90
} |
# as example only
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
try:
next = int(raw_input("> "))
how_much = int(next)
except:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door"
print "How are you going to move the bear?"
bear_moved = False
while True:
next = raw_input("> ")
if next == "take honey":
dead("The bear looks at you then slap your face off.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
def cthulhu_room():
print "Here you see the great evil Cthulu."
print "He, it whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input(":> ")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty")
else:
cthulhu_room()
def dead(why):
print why, "Good job!"
exit(0)
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
next = raw_input("> ")
if next == "left":
bear_room()
elif next == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()
| {
"repo_name": "reschaap/ex38",
"path": "ex35.py",
"copies": "1",
"size": "1967",
"license": "mit",
"hash": 2835826968724338700,
"line_mean": 23.9113924051,
"line_max": 80,
"alpha_frac": 0.5561769192,
"autogenerated": false,
"ratio": 3.5441441441441444,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46003210633441444,
"avg_score": null,
"num_lines": null
} |
"""ASF Parser Plugin."""
#
# Copyright (c) 2007 Michael van Tellingen <michaelvantellingen@gmail.com>
# 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. The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
#
# Built-in modules
import datetime
__all__ = ['Parser']
# Project modules
import videoparser.plugins as plugins
import videoparser.streams as streams
# Only implement required information to retrieve video and audio information
guid_list = {
'D2D0A440-E307-11D2-97F0-00A0C95EA850':
'ASF_Extended_Content_Description_Object',
'75B22630-668E-11CF-A6D9-00AA0062CE6C': 'ASF_Header_Object',
'75B22633-668E-11CF-A6D9-00AA0062CE6C': 'ASF_Content_Description_Object',
'8CABDCA1-A947-11CF-8EE4-00C00C205365': 'ASF_File_Properties_Object',
'5FBF03B5-A92E-11CF-8EE3-00C00C205365': 'ASF_Header_Extension_Object',
'86D15240-311D-11D0-A3A4-00A0C90348F6': 'ASF_Codec_List_Object',
'B7DC0791-A9B7-11CF-8EE6-00C00C205365': 'ASF_Stream_Properties_Object',
'7BF875CE-468D-11D1-8D82-006097C9A2B2':
'ASF_Stream_Bitrate_Properties_Object',
'F8699E40-5B4D-11CF-A8FD-00805F5C442B': 'ASF_Audio_Media',
'BC19EFC0-5B4D-11CF-A8FD-00805F5C442B': 'ASF_Video_Media',
'BFC3CD50-618F-11CF-8BB2-00AA00B4E220': 'ASF_Audio_Spread',
'20FB5700-5B55-11CF-A8FD-00805F5C442B': 'ASF_No_Error_Correction',
'7C4346A9-EFE0-4BFC-B229-393EDE415C85': 'ASF_Language_List_Object',
'ABD3D211-A9BA-11cf-8EE6-00C00C205365': 'ASF_Reserved_1',
'C5F8CBEA-5BAF-4877-8467-AA8C44FA4CCA': 'ASF_Metadata_Object',
'14E6A5CB-C672-4332-8399-A96952065B5A':
'ASF_Extended_Stream_Properties_Object',
'D6E229DF-35DA-11D1-9034-00A0C90349BE': 'ASF_Index_Parameters_Object',
'D4FED15B-88D3-454F-81F0-ED5C45999E24': 'ASF_Stream_Prioritization_Object',
'1806D474-CADF-4509-A4BA-9AABCB96AAE8': 'ASF_Padding_Object',
}
class Parser(plugins.BaseParser):
_endianess = streams.endian.little
_file_types = ['wmv']
def __init__(self):
plugins.BaseParser.__init__(self)
def parse(self, filename, video):
stream = streams.factory.create_filestream(filename,
endianess=self._endianess)
object_id = stream.read_guid()
if guid_list.get(object_id) != 'ASF_Header_Object':
return False
try:
header = self.parse_header(stream)
except AssertionError:
return False
self.extract_information(header, video)
return True
def extract_information(self, header, video):
#print header
#print
#print
framerates = {}
video.set_container('ASF')
# Loop over all objects in the header, first search for the
# StreamProperties
for object in header.objects:
if isinstance(object, self.StreamProperties):
stream = video.get_stream(object.index)
type_data = object.type_data
if object.type == 'ASF_Audio_Media':
if not stream:
stream = video.new_audio_stream(object.index)
stream.set_channels(type_data.channels)
stream.set_sample_rate(type_data.sample_rate)
stream.set_codec(type_data.codec_ids.get(
type_data.codec_id, type_data.codec_id))
stream.set_bit_per_sample(type_data.bits_per_sample)
if object.type == 'ASF_Video_Media':
if not stream:
stream = video.new_video_stream(object.index)
stream.set_width(type_data.width)
stream.set_height(type_data.height)
stream.set_codec(type_data.format_data.compression_id)
for object in header.objects:
if isinstance(object, self.FileProperties):
for stream in video.video_streams:
stream.set_duration(seconds=object.play_duration.seconds,
microseconds= \
object.play_duration.microseconds)
# Extract additional information from the HeaderExtension
if isinstance(object, self.HeaderExtension):
for sub_object in object.extension_data:
if isinstance(sub_object, self.ExtendedStreamProperties):
# Framerate (required for video)
stream = video.get_stream(sub_object.stream_number)
if stream.type == 'Video':
stream.set_framerate(1 / (
sub_object.avg_time_per_frame / 10000000.0))
return video
def parse_header(self, stream):
# Read the header information
header = self.Header()
header.size = stream.read_uint64()
header.num_objects = stream.read_uint32()
header.reserved_1 = stream.read_uint8()
header.reserved_2 = stream.read_uint8()
header.objects = []
if header.reserved_2 != 0x02:
raise AssertionError('Reserved2 in Header Object should be 0x02')
# Loop through all objects contained in the header
for i in range(0, header.num_objects):
guid = stream.read_guid()
size = stream.read_uint64()
obj = None
try:
object_type = guid_list[guid]
except:
# Unrecognized object, skip over it
raise AssertionError("Unregognized object: %s" % guid)
stream.skip(size - 24)
continue
data = stream.read_subsegment(size - 24)
if object_type == 'ASF_Content_Description_Object':
obj = 'ASF_Content_Description_Object (TODO)'
elif object_type == 'ASF_Extended_Content_Description_Object':
obj = 'ASF_Extended_Content_Description_Object (TODO)'
elif object_type == 'ASF_File_Properties_Object':
obj = self.parse_file_properties(data)
elif object_type == 'ASF_Header_Extension_Object':
obj = self.parse_header_extension(data)
elif object_type == 'ASF_Codec_List_Object':
obj = self.parse_codec_list(data)
elif object_type == 'ASF_Stream_Properties_Object':
obj = self.parse_stream_properties(data)
elif object_type == 'ASF_Stream_Bitrate_Properties_Object':
obj = self.parse_stream_bitrate_properties(data)
else:
print "Warning: unhandled object: %s" % object_type
header.objects.append(obj)
data.close()
#print guid_list[guid], size
return header
# mandatory, one only
def parse_file_properties(self, data):
fileprop = self.FileProperties()
fileprop.id = data.read_guid()
fileprop.size = data.read_uint64()
fileprop.create_date = data.read_timestamp_win()
fileprop.packet_count = data.read_uint64()
fileprop.play_duration = datetime.timedelta(
microseconds=data.read_uint64()/10)
fileprop.send_duration = datetime.timedelta(
microseconds=data.read_uint64()/10)
fileprop.preroll = data.read_uint64()
# Flags
flags = data.read_uint32()
fileprop.broadcast_flag = flags & 0x01
fileprop.seekable_flag = (flags >> 1) & 0x01
fileprop.reserved = flags >> 2
fileprop.min_packet_size = data.read_uint32()
fileprop.max_packet_size = data.read_uint32()
fileprop.max_bitrate = data.read_uint32()
return fileprop
# mandatory, one only
def parse_stream_properties(self, data):
stream = self.StreamProperties()
stream.type = guid_list[data.read_guid()]
stream.ecc_type = guid_list[data.read_guid()]
stream.time_offset = data.read_uint64()
stream.type_length = data.read_uint32()
stream.ecc_length = data.read_uint32()
flags = data.read(2)
stream.index = ord(flags[0]) & 0x7f
stream.reserved = data.read(4)
type_data = data.read_subsegment(stream.type_length)
if stream.type == 'ASF_Audio_Media':
obj = type_data.read_waveformatex()
elif stream.type == 'ASF_Video_Media':
obj = self.VideoMedia()
obj.width = type_data.read_uint32()
obj.height = type_data.read_uint32()
obj.reserved_flags = type_data.read_byte()
obj.format_data_size = type_data.read_uint16()
obj.format_data = type_data.read_bitmapinfoheader()
else:
obj = None
stream.type_data = obj
stream.ecc_data = repr(data.read(stream.ecc_length))
return stream
# mandatory, one only
def parse_header_extension(self, data):
header = self.HeaderExtension()
header.reserved_1 = data.read_guid() # should be ASF_Reserved_1
header.reserved_2 = data.read_uint16() # should be 6
header.size = data.read_uint32()
header.extension_data = []
# Check reserved_1
bytes = header.size
while bytes > 0:
object_id = data.read_guid()
object_size = data.read_uint64()
bytes -= object_size
if object_size == 0:
continue
sub_data = data.read_subsegment(object_size - 24)
try:
object_type = guid_list[object_id]
except KeyError:
# Skip unknown guid's, since authors are allowed to create
# there own
#
#print "WARNING: object_id '%s' not found in guid_list" % \
# object_id
#header.extension_data.append(object_id)
continue
if object_type == 'ASF_Language_List_Object':
obj = self.parse_language_list(sub_data)
elif object_type == 'ASF_Metadata_Object':
obj = self.parse_metadata(sub_data)
elif object_type == 'ASF_Extended_Stream_Properties_Object':
obj = self.parse_extended_stream_properties(sub_data)
elif object_type == 'ASF_Stream_Prioritization_Object':
obj = self.parse_stream_prioritization(sub_data)
elif object_type == 'ASF_Padding_Object':
# Ignore the padding object, since it contains no information
continue
elif object_type == 'ASF_Index_Parameters_Object':
obj = 'ASF_Index_Parameters_Object (TODO)'
else:
raise AssertionError("object_type '%s' not processed in " +
"header_extension" % object_type)
#if obj is None:
# raise AssertionError("obj is None: %s" % object_type)
header.extension_data.append(obj)
return header
def parse_language_list(self, data):
obj = self.LanguageList()
obj.num_records = data.read_uint16()
obj.records = []
for i in range(0, obj.num_records):
language_id_length = data.read_uint8()
language_id = data.read_wchars(language_id_length / 2)
obj.records.append(language_id)
return obj
def parse_metadata(self, data):
return None
def parse_extended_stream_properties(self, data):
obj = self.ExtendedStreamProperties()
obj.start_time = data.read_uint64()
obj.end_time = data.read_uint64()
obj.data_bitrate = data.read_uint32()
obj.buffer_size = data.read_uint32()
obj.initial_buffer_fullness = data.read_uint32()
obj.alt_data_bitrate = data.read_uint32()
obj.alt_buffer_size = data.read_uint32()
obj.alt_initial_buffer_fullness = data.read_uint32()
obj.max_object_size = data.read_uint32()
# Parse flags
flags = data.read_uint32()
obj.reliable_flag = flags & 0x01
obj.seekable_flag = (flags >> 1) & 0x01
obj.no_cleanpoints_flag = (flags >> 2) & 0x01
obj.resend_cleanpoints_flag = (flags >> 3) & 0x01
obj.reserved_flags = flags >> 4
obj.stream_number = data.read_uint16()
obj.stream_language_id = data.read_uint16()
obj.avg_time_per_frame = data.read_uint64()
obj.stream_name_length = data.read_uint16()
obj.payload_extension_length = data.read_uint16()
obj.stream_names = None
obj.payload_extensions = None
obj.stream_properties_object = None
return obj
def parse_stream_prioritization(self, data):
return None
# Optional, one only
def parse_codec_list(self, data):
codeclist = self.CodecList()
codeclist.reserved = data.read_guid()
codeclist.num_codecs = data.read_uint32()
codeclist.codec_entries = []
for i in range(0, codeclist.num_codecs):
entry = self.CodecEntry()
entry.type = data.read_uint16()
entry.name_length = data.read_uint16()
entry.name = data.read_wchars(entry.name_length,
null_terminated=True)
entry.description_length = data.read_uint16()
entry.description = data.read_wchars(entry.description_length,
null_terminated=True)
entry.information_length = data.read_uint16()
entry.information = repr(data.read(entry.information_length))
codeclist.codec_entries.append(entry)
return codeclist
# Optional but recommended, one only
def parse_stream_bitrate_properties(self, data):
bitratelist = self.StreamBitrateProperties()
bitratelist.num_records = data.read_uint16()
bitratelist.records = []
for i in range(0, bitratelist.num_records):
entry = self.StreamBitrateRecord()
flags = data.read(2)
entry.stream_index = ord(flags[0]) & 0x7f
entry.reserved = chr(ord(flags[0]) & 0x80) + flags[1]
entry.avg_bitrate = data.read_uint32()
bitratelist.records.append(entry)
return bitratelist
#
# Objects to represent internal structure of the ASF File for debuging
#
class Structure(object):
def repr_childs(self, obj):
buffer = ""
for entry in obj:
buffer += "\n".join([" %s" % line for line
in repr(entry).split('\n')])
buffer += "\n"
return buffer
class Header(Structure):
__slots__ = ['size', 'num_objects', 'reserved_1', 'reserved_2',
'objects']
def __repr__(self):
buffer = "ASF_Header_Object Structure: \n"
buffer += " %-30s: %s\n" % ('Object Size', self.size)
buffer += " %-30s: %s\n" % ('Number of Header Objects',
self.num_objects)
buffer += " %-30s: %s\n" % ('Reserved1', repr(self.reserved_1))
buffer += " %-30s: %s\n" % ('Reserved2', repr(self.reserved_2))
buffer += self.repr_childs(self.objects)
return buffer
class VideoMedia(Structure):
__slots__ = ['width', 'height', 'reserved_flags', 'format_data_size',
'format_data']
def __repr__(self):
buffer = "ASF_Video_Media Structure: \n"
buffer += " %-30s: %s\n" % ('Encoded Image Width', self.width)
buffer += " %-30s: %s\n" % ('Encoded Image Height', self.height)
buffer += " %-30s: %s\n" % ('Reserved Flags',
repr(self.reserved_flags))
buffer += " %-30s: %s\n" % ('Format Data Size',
self.format_data_size)
buffer += " %-30s\n" % ('Format Data')
buffer += self.repr_childs([self.format_data])
return buffer
class LanguageList(Structure):
__slots__ = ['num_records', 'records']
def __repr__(self):
buffer = "ASF_Language_List_Object: \n"
buffer += " %-30s: %s\n" % ('Language ID Records Count',
self.num_records)
buffer += self.repr_childs([self.records])
return buffer
class FileProperties(Structure):
__slots__ = ['id', 'size', 'create_data', 'packet_count',
'play_duration', 'send_duration', 'preroll',
'broadcast_flag', 'seekable_flag', 'reserved',
'min_packet_size', 'max_packet_size', 'max_bitrate']
def __repr__(self):
buffer = "FileProperties Structure: \n"
buffer += " %-30s: %s\n" % ('File ID', self.id)
buffer += " %-30s: %s\n" % ('File Size', self.size)
buffer += " %-30s: %s\n" % ('Creation Date', self.create_date)
buffer += " %-30s: %s\n" % ('Data Packets Count',
self.packet_count)
buffer += " %-30s: %s\n" % ('Play Duration', self.play_duration)
buffer += " %-30s: %s\n" % ('Send Duration', self.send_duration)
buffer += " %-30s: %s\n" % ('Preroll', repr(self.preroll))
buffer += " %-30s: %s\n" % ('Broadcast Flag', self.broadcast_flag)
buffer += " %-30s: %s\n" % ('Seekable Flag', self.seekable_flag)
buffer += " %-30s: %s\n" % ('Reserved', repr(self.reserved))
buffer += " %-30s: %s\n" % ('Minimum Data Packet Size',
self.min_packet_size)
buffer += " %-30s: %s\n" % ('Maximum Data Packet Size',
self.max_packet_size)
buffer += " %-30s: %s\n" % ('Maximum Bitrate',
self.max_bitrate)
return buffer
class HeaderExtension(Structure):
def __repr__(self):
buffer = "HeaderExtension Structure: \n"
buffer += " %-30s: %s\n" % ('Reserved_1', self.reserved_1)
buffer += " %-30s: %s\n" % ('Reserved_2', self.reserved_2)
buffer += " %-30s: %s\n" % ('Header Extension Data Size',
self.size)
buffer += " %-30s\n" % ('Header Extension Data')
buffer += self.repr_childs(self.extension_data)
return buffer
class StreamProperties(Structure):
__slots__ = ['type', 'ecc_type', 'time_offset', 'type_length',
'ecc_length', 'index', 'reserved', 'type_data',
'ecc_data']
def __repr__(self):
buffer = "StreamProperties Structure: \n"
buffer += " %-30s: %s\n" % ('Stream Type', self.type)
buffer += " %-30s: %s\n" % ('Error Correction Type', self.ecc_type)
buffer += " %-30s: %s\n" % ('Time Offset', self.time_offset)
buffer += " %-30s: %s\n" % ('Type-Specific Data Length',
self.type_length)
buffer += " %-30s: %s\n" % ('Error Correction Data Length',
self.ecc_length)
buffer += " %-30s: %s\n" % ('Stream Index', self.index)
buffer += " %-30s: %s\n" % ('Reserved', repr(self.reserved))
buffer += " %-30s\n" % ('Type-Specific Data')
buffer += self.repr_childs([self.type_data])
buffer += " %-30s: %s\n" % ('Error Correction Data', self.ecc_data)
return buffer
class StreamBitrateRecord(Structure):
__slots__ = ['stream_index', 'reserved', 'avg_bitrate']
def __repr__(self):
buffer = "StreamBitrateRecord Structure: \n"
buffer += " %-30s: %s\n" % ('Stream number', self.stream_index)
buffer += " %-30s: %r\n" % ('Reserved', self.reserved)
buffer += " %-30s: %s\n" % ('Average Bitrate', self.avg_bitrate)
return buffer
class StreamBitrateProperties(Structure):
__slots__ = ['num_records', 'records']
def __repr__(self):
buffer = "StreamBitrateProperties Structure: \n"
buffer += " %-30s: %s\n" % ('Bitrate Entries Count',
self.num_records)
buffer += " %-30s\n" % ('Codec Entries')
buffer += self.repr_childs(self.records)
return buffer
class CodecList(Structure):
__slots__ = ['reserved', 'num_codecs', 'codec_entries']
def __repr__(self):
buffer = "CodecList Structure: \n"
buffer += " %-30s: %s\n" % ('Reserved', self.reserved)
buffer += " %-30s: %s\n" % ('Codec Entries Count', self.num_codecs)
buffer += " %-30s\n" % ('Codec Entries')
buffer += self.repr_childs(self.codec_entries)
return buffer
class CodecEntry(Structure):
__slots__ = ['type', 'name_length', 'name', 'description_length',
'description', 'information_length', 'information']
def __repr__(self):
buffer = "CodecEntry Structure: \n"
buffer += " %-30s: %s\n" % ('Type', self.type)
buffer += " %-30s: %s\n" % ('Codec Name Length', self.name_length)
buffer += " %-30s: %s\n" % ('Codecx Name', repr(self.name))
buffer += " %-30s: %s\n" % ('Codec Description Length',
self.description_length)
buffer += " %-30s: %s\n" % ('Codec Description',
repr(self.description))
buffer += " %-30s: %s\n" % ('Codec Information Length',
self.information_length)
buffer += " %-30s: %s\n" % ('Codec Information', self.information)
return buffer
class ExtendedStreamProperties(Structure):
__slots__ = ['start_time', 'end_time', 'data_bitrate', 'buffer_size',
'initial_buffer_fullness', 'alt_data_bitrate',
'alt_buffer_size', 'alt_initial_buffer_fullness',
'max_object_size', 'reliable_flag', 'seekable_flag',
'no_cleanpoints_flag', 'resend_cleanpoints_flag',
'reserved_flags', 'stream_number', 'stream_language_id',
'avg_time_per_frame', 'stream_name_length',
'payload_extension_length', 'stream_names',
'payload_extensions', 'stream_properties_object']
def __repr__(self):
buffer = "ExtendedStreamProperties Structure: \n"
buffer += " %-30s: %s\n" % ('Start Time', self.start_time)
buffer += " %-30s: %s\n" % ('End Time', self.end_time)
buffer += " %-30s: %s\n" % ('Data Bitrate', self.data_bitrate)
buffer += " %-30s: %s\n" % ('Buffer Size', self.buffer_size)
buffer += " %-30s: %s\n" % ('Initial Buffer Fullness',
self.initial_buffer_fullness)
buffer += " %-30s: %s\n" % ('Alternate Data Bitrate',
self.alt_data_bitrate)
buffer += " %-30s: %s\n" % ('Alternate Buffer Size',
self.alt_buffer_size)
buffer += " %-30s: %s\n" % ('Alternate Initial Buffer Fullness',
self.alt_initial_buffer_fullness)
buffer += " %-30s: %s\n" % ('Maximum Object Size',
self.max_object_size)
buffer += " %-30s: %s\n" % ('Reliable Flag', self.reliable_flag)
buffer += " %-30s: %s\n" % ('Seekable Flag',
self.seekable_flag)
buffer += " %-30s: %s\n" % ('No Cleanpoints Flag',
self.no_cleanpoints_flag)
buffer += " %-30s: %s\n" % ('Resend Live Cleanpoints Flag',
self.resend_cleanpoints_flag)
buffer += " %-30s: %s\n" % ('Reserved Flags', self.reserved_flags)
buffer += " %-30s: %s\n" % ('Stream Number', self.stream_number)
buffer += " %-30s: %s\n" % ('Stream Language ID Index',
self.stream_language_id)
buffer += " %-30s: %s\n" % ('Average Time Per Frame',
self.avg_time_per_frame)
buffer += " %-30s: %s\n" % ('Stream Name Count',
self.stream_name_length)
buffer += " %-30s: %s\n" % ('Payload Extension System Count',
self.payload_extension_length)
buffer += " %-30s: %s\n" % ('Stream Names', self.stream_names)
buffer += " %-30s: %s\n" % ('Payload Extension Systems',
self.payload_extensions)
buffer += " %-30s: %s\n" % ('Stream Properties Object',
self.stream_properties_object)
return buffer
| {
"repo_name": "kevdes/videoparser",
"path": "plugins/asf.py",
"copies": "1",
"size": "27701",
"license": "cc0-1.0",
"hash": -43504554830759816,
"line_mean": 41.5514592934,
"line_max": 79,
"alpha_frac": 0.51803184,
"autogenerated": false,
"ratio": 3.9989894615273567,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9899304909991218,
"avg_score": 0.023543278307227654,
"num_lines": 651
} |
# as_GPS.py Asynchronous device driver for GPS devices using a UART.
# Sentence parsing based on MicropyGPS by Michael Calvin McCoy
# https://github.com/inmcm/micropyGPS
# http://www.gpsinformation.org/dale/nmea.htm
# Docstrings removed because of question marks over their use in resource
# constrained systems e.g. https://github.com/micropython/micropython/pull/3748
# Copyright (c) 2018-2020 Peter Hinch
# Released under the MIT License (MIT) - see LICENSE file
# astests.py runs under CPython but not MicroPython because mktime is missing
# from Unix build of utime
# Ported to uasyncio V3 OK.
try:
import uasyncio as asyncio
except ImportError:
import asyncio
try:
from micropython import const
except ImportError:
const = lambda x : x
from math import modf
# Float conversion tolerant of empty field
# gfloat = lambda x : float(x) if x else 0.0
# Angle formats
DD = const(1)
DMS = const(2)
DM = const(3)
KML = const(4)
# Speed units
KPH = const(10)
MPH = const(11)
KNOT = const(12)
# Date formats
MDY = const(20)
DMY = const(21)
LONG = const(22)
# Sentence types
RMC = const(1)
GLL = const(2)
VTG = const(4)
GGA = const(8)
GSA = const(16)
GSV = const(32)
# Messages carrying data
POSITION = const(RMC | GLL | GGA)
ALTITUDE = const(GGA)
DATE = const(RMC)
COURSE = const(RMC | VTG)
class AS_GPS(object):
# Can omit time consuming checks: CRC 6ms Bad char and line length 9ms
FULL_CHECK = True
_SENTENCE_LIMIT = 76 # Max sentence length (based on GGA sentence)
_NO_FIX = 1
# Return day of week from date. Pyboard RTC format: 1-7 for Monday through Sunday.
# https://stackoverflow.com/questions/9847213/how-do-i-get-the-day-of-week-given-a-date-in-python?noredirect=1&lq=1
# Adapted for Python 3 and Pyboard RTC format.
@staticmethod
def _week_day(year, month, day, offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]):
aux = year - 1700 - (1 if month <= 2 else 0)
# day_of_week for 1700/1/1 = 5, Friday
day_of_week = 5
# partial sum of days betweem current date and 1700/1/1
day_of_week += (aux + (1 if month <= 2 else 0)) * 365
# leap year correction
day_of_week += aux // 4 - aux // 100 + (aux + 100) // 400
# sum monthly and day offsets
day_of_week += offset[month - 1] + (day - 1)
day_of_week %= 7
day_of_week = day_of_week if day_of_week else 7
return day_of_week
# 8-bit xor of characters between "$" and "*". Takes 6ms on Pyboard!
@staticmethod
def _crc_check(res, ascii_crc):
try:
crc = int(ascii_crc, 16)
except ValueError:
return False
x = 1
crc_xor = 0
while res[x] != '*':
crc_xor ^= ord(res[x])
x += 1
return crc_xor == crc
def __init__(self, sreader, local_offset=0, fix_cb=lambda *_ : None, cb_mask=RMC, fix_cb_args=()):
self._sreader = sreader # If None testing: update is called with simulated data
self._fix_cb = fix_cb
self.cb_mask = cb_mask
self._fix_cb_args = fix_cb_args
self.battery = False # Assume no backup battery
# CPython compatibility. Import utime or time for fix time handling.
try:
import utime
self._get_time = utime.ticks_ms
self._time_diff = utime.ticks_diff
self._localtime = utime.localtime
self._mktime = utime.mktime
except ImportError:
# Otherwise default to time module for non-embedded implementations
# Should still support millisecond resolution.
import time
self._get_time = time.time
self._time_diff = lambda start, end: 1000 * (start - end)
self._localtime = time.localtime
self._mktime = time.mktime
# Key: currently supported NMEA sentences. Value: parse method.
self.supported_sentences = {'RMC': self._gprmc,
'GGA': self._gpgga,
'VTG': self._gpvtg,
'GSA': self._gpgsa,
'GSV': self._gpgsv,
'GLL': self._gpgll,
}
#####################
# Object Status Flags
self._fix_time = None
#####################
# Sentence Statistics
self.crc_fails = 0
self.clean_sentences = 0
self.parsed_sentences = 0
self.unsupported_sentences = 0
#####################
# Data From Sentences
# Time. http://www.gpsinformation.org/dale/nmea.htm indicates seconds
# is an integer. However hardware returns a float, but the fractional
# part is always zero. So treat seconds value as an integer. For
# precise timing use PPS signal and as_tGPS library.
self.local_offset = local_offset # hrs
self.epoch_time = 0 # Integer secs since epoch (Y2K under MicroPython)
# Add ms if supplied by device. Only used by timing drivers.
self.msecs = 0
# Position/Motion
self._latitude = [0, 0.0, 'N'] # (°, mins, N/S)
self._longitude = [0, 0.0, 'W'] # (°, mins, E/W)
self._speed = 0.0 # Knot
self.course = 0.0 # ° clockwise from N
self.altitude = 0.0 # Metres
self.geoid_height = 0.0 # Metres
self.magvar = 0.0 # Magnetic variation (°, -ve == west)
# State variables
self._last_sv_sentence = 0 # for GSV parsing
self._total_sv_sentences = 0
self._satellite_data = dict() # for get_satellite_data()
self._update_ms = 1000 # Update rate for timing drivers. Default 1 sec.
# GPS Info
self.satellites_in_view = 0
self.satellites_in_use = 0
self.satellites_used = []
self.hdop = 0.0
self.pdop = 0.0
self.vdop = 0.0
# Received status
self._valid = 0 # Bitfield of received sentences
if sreader is not None: # Running with UART data
asyncio.create_task(self._run())
##########################################
# Data Stream Handler Functions
##########################################
async def _run(self):
while True:
res = await self._sreader.readline()
try:
res = res.decode('utf8')
except UnicodeError: # Garbage: can happen e.g. on baudrate change
continue
asyncio.create_task(self._update(res))
await asyncio.sleep(0) # Ensure task runs and res is copied
# Update takes a line of text
async def _update(self, line):
line = line.rstrip() # Copy line
# Basic integrity check: may have received partial line e.g on power up
if not line.startswith('$') or not '*' in line or len(line) > self._SENTENCE_LIMIT:
return
# 2.4ms on Pyboard:
if self.FULL_CHECK and not all(10 <= ord(c) <= 126 for c in line):
return # Bad character received
a = line.split(',')
segs = a[:-1] + a[-1].split('*')
await asyncio.sleep(0)
if self.FULL_CHECK: # 6ms on Pyboard
if not self._crc_check(line, segs[-1]):
self.crc_fails += 1 # Update statistics
return
await asyncio.sleep(0)
self.clean_sentences += 1 # Sentence is good but unparsed.
segs[0] = segs[0][1:] # discard $
segs = segs[:-1] # and checksum
seg0 = segs[0] # e.g. GPGLL
segx = seg0[2:] # e.g. GLL
if seg0.startswith('G') and segx in self.supported_sentences:
try:
s_type = self.supported_sentences[segx](segs) # Parse
except ValueError:
s_type = False
await asyncio.sleep(0)
if isinstance(s_type, int) and (s_type & self.cb_mask):
# Successfully parsed, data was valid and mask matches sentence type
self._fix_cb(self, s_type, *self._fix_cb_args) # Run the callback
if s_type: # Successfully parsed
if self.reparse(segs): # Subclass hook
self.parsed_sentences += 1
return seg0 # For test programs
else:
if self.parse(segs): # Subclass hook
self.parsed_sentences += 1
self.unsupported_sentences += 1
return seg0 # For test programs
# Optional hooks for subclass
def parse(self, segs): # Parse unsupported sentences
return True
def reparse(self, segs): # Re-parse supported sentences
return True
########################################
# Fix and Time Functions
########################################
# Caller traps ValueError
def _fix(self, gps_segments, idx_lat, idx_long):
# Latitude
l_string = gps_segments[idx_lat]
lat_degs = int(l_string[0:2])
lat_mins = float(l_string[2:])
lat_hemi = gps_segments[idx_lat + 1]
# Longitude
l_string = gps_segments[idx_long]
lon_degs = int(l_string[0:3])
lon_mins = float(l_string[3:])
lon_hemi = gps_segments[idx_long + 1]
if lat_hemi not in 'NS'or lon_hemi not in 'EW':
raise ValueError
self._latitude[0] = lat_degs # In-place to avoid allocation
self._latitude[1] = lat_mins
self._latitude[2] = lat_hemi
self._longitude[0] = lon_degs
self._longitude[1] = lon_mins
self._longitude[2] = lon_hemi
self._fix_time = self._get_time()
def _dtset(self, _): # For subclass
pass
# A local offset may exist so check for date rollover. Local offsets can
# include fractions of an hour but not seconds (AFAIK).
# Caller traps ValueError
def _set_date_time(self, utc_string, date_string):
if not date_string or not utc_string:
raise ValueError
hrs = int(utc_string[0:2]) # h
mins = int(utc_string[2:4]) # mins
# Secs from MTK3339 chip is a float but others may return only 2 chars
# for integer secs. If a float keep epoch as integer seconds and store
# the fractional part as integer ms (ms since midnight fits 32 bits).
fss, fsecs = modf(float(utc_string[4:]))
secs = int(fsecs)
self.msecs = int(fss * 1000)
d = int(date_string[0:2]) # day
m = int(date_string[2:4]) # month
y = int(date_string[4:6]) + 2000 # year
wday = self._week_day(y, m, d)
t = int(self._mktime((y, m, d, hrs, mins, int(secs), wday - 1, 0, 0)))
self.epoch_time = t # This is the fundamental datetime reference.
self._dtset(wday) # Subclass may override
########################################
# Sentence Parsers
########################################
# For all parsers:
# Initially the ._valid bit for the sentence type is cleared.
# On error a ValueError is raised: trapped by the caller.
# On successful parsing the ._valid bit is set.
# The ._valid mechanism enables the data_received coro to determine what
# sentence types have been received.
# Chip sends rubbish RMC messages before first PPS pulse, but these have
# data valid set to 'V' (void)
def _gprmc(self, gps_segments): # Parse RMC sentence
self._valid &= ~RMC
# Check Receiver Data Valid Flag ('A' active)
if not self.battery:
if gps_segments[2] != 'A':
raise ValueError
# UTC Timestamp and date. Can raise ValueError.
self._set_date_time(gps_segments[1], gps_segments[9])
# Check Receiver Data Valid Flag ('A' active)
if gps_segments[2] != 'A':
raise ValueError
# Data from Receiver is Valid/Has Fix. Longitude / Latitude
# Can raise ValueError.
self._fix(gps_segments, 3, 5)
# Speed
spd_knt = float(gps_segments[7])
# Course
course = float(gps_segments[8])
# Add Magnetic Variation if firmware supplies it
if gps_segments[10]:
mv = float(gps_segments[10]) # Float conversions can throw ValueError, caught by caller.
if gps_segments[11] not in ('EW'):
raise ValueError
self.magvar = mv if gps_segments[11] == 'E' else -mv
# Update Object Data
self._speed = spd_knt
self.course = course
self._valid |= RMC
return RMC
def _gpgll(self, gps_segments): # Parse GLL sentence
self._valid &= ~GLL
# Check Receiver Data Valid Flag
if gps_segments[6] != 'A': # Invalid. Don't update data
raise ValueError
# Data from Receiver is Valid/Has Fix. Longitude / Latitude
self._fix(gps_segments, 1, 3)
# Update Last Fix Time
self._valid |= GLL
return GLL
# Chip sends VTG messages with meaningless data before getting a fix.
def _gpvtg(self, gps_segments): # Parse VTG sentence
self._valid &= ~VTG
course = float(gps_segments[1])
spd_knt = float(gps_segments[5])
self._speed = spd_knt
self.course = course
self._valid |= VTG
return VTG
def _gpgga(self, gps_segments): # Parse GGA sentence
self._valid &= ~GGA
# Number of Satellites in Use
satellites_in_use = int(gps_segments[7])
# Horizontal Dilution of Precision
hdop = float(gps_segments[8])
# Get Fix Status
fix_stat = int(gps_segments[6])
# Process Location and Altitude if Fix is GOOD
if fix_stat:
# Longitude / Latitude
self._fix(gps_segments, 2, 4)
# Altitude / Height Above Geoid
altitude = float(gps_segments[9])
geoid_height = float(gps_segments[11])
# Update Object Data
self.altitude = altitude
self.geoid_height = geoid_height
self._valid |= GGA
# Update Object Data
self.satellites_in_use = satellites_in_use
self.hdop = hdop
return GGA
def _gpgsa(self, gps_segments): # Parse GSA sentence
self._valid &= ~GSA
# Fix Type (None,2D or 3D)
fix_type = int(gps_segments[2])
# Read All (up to 12) Available PRN Satellite Numbers
sats_used = []
for sats in range(12):
sat_number_str = gps_segments[3 + sats]
if sat_number_str:
sat_number = int(sat_number_str)
sats_used.append(sat_number)
else:
break
# PDOP,HDOP,VDOP
pdop = float(gps_segments[15])
hdop = float(gps_segments[16])
vdop = float(gps_segments[17])
# If Fix is GOOD, update fix timestamp
if fix_type <= self._NO_FIX: # Deviation from Michael McCoy's logic. Is this right?
raise ValueError
self.satellites_used = sats_used
self.hdop = hdop
self.vdop = vdop
self.pdop = pdop
self._valid |= GSA
return GSA
def _gpgsv(self, gps_segments):
# Parse Satellites in View (GSV) sentence. Updates no. of SV sentences,
# the no. of the last SV sentence parsed, and data on each satellite
# present in the sentence.
self._valid &= ~GSV
num_sv_sentences = int(gps_segments[1])
current_sv_sentence = int(gps_segments[2])
sats_in_view = int(gps_segments[3])
# Create a blank dict to store all the satellite data from this sentence in:
# satellite PRN is key, tuple containing telemetry is value
satellite_dict = dict()
# Calculate Number of Satelites to pull data for and thus how many segment positions to read
if num_sv_sentences == current_sv_sentence:
sat_segment_limit = ((sats_in_view % 4) * 4) + 4 # Last sentence may have 1-4 satellites
else:
sat_segment_limit = 20 # Non-last sentences have 4 satellites and thus read up to position 20
# Try to recover data for up to 4 satellites in sentence
for sats in range(4, sat_segment_limit, 4):
# If a PRN is present, grab satellite data
if gps_segments[sats]:
try:
sat_id = int(gps_segments[sats])
except IndexError:
raise ValueError # Abandon
try: # elevation can be null (no value) when not tracking
elevation = int(gps_segments[sats+1])
except (ValueError,IndexError):
elevation = None
try: # azimuth can be null (no value) when not tracking
azimuth = int(gps_segments[sats+2])
except (ValueError,IndexError):
azimuth = None
try: # SNR can be null (no value) when not tracking
snr = int(gps_segments[sats+3])
except (ValueError,IndexError):
snr = None
# If no PRN is found, then the sentence has no more satellites to read
else:
break
# Add Satellite Data to Sentence Dict
satellite_dict[sat_id] = (elevation, azimuth, snr)
# Update Object Data
self._total_sv_sentences = num_sv_sentences
self._last_sv_sentence = current_sv_sentence
self.satellites_in_view = sats_in_view
# For a new set of sentences, we either clear out the existing sat data or
# update it as additional SV sentences are parsed
if current_sv_sentence == 1:
self._satellite_data = satellite_dict
else:
self._satellite_data.update(satellite_dict)
# Flag that a msg has been received. Does not mean a full set of data is ready.
self._valid |= GSV
return GSV
#########################################
# User Interface Methods
#########################################
# Data Validity. On startup data may be invalid. During an outage it will be absent.
async def data_received(self, position=False, course=False, date=False,
altitude=False):
self._valid = 0 # Assume no messages at start
result = False
while not result:
result = True
await asyncio.sleep(1) # Successfully parsed messages set ._valid bits
if position and not self._valid & POSITION:
result = False
if date and not self._valid & DATE:
result = False
# After a hard reset the chip sends course messages even though no fix
# was received. Ignore this garbage until a fix is received.
if course:
if self._valid & COURSE:
if not self._valid & POSITION:
result = False
else:
result = False
if altitude and not self._valid & ALTITUDE:
result = False
def latitude(self, coord_format=DD):
# Format Latitude Data Correctly
if coord_format == DD:
decimal_degrees = self._latitude[0] + (self._latitude[1] / 60)
return [decimal_degrees, self._latitude[2]]
elif coord_format == DMS:
mins = int(self._latitude[1])
seconds = round((self._latitude[1] - mins) * 60)
return [self._latitude[0], mins, seconds, self._latitude[2]]
elif coord_format == DM:
return self._latitude
raise ValueError('Unknown latitude format.')
def longitude(self, coord_format=DD):
# Format Longitude Data Correctly
if coord_format == DD:
decimal_degrees = self._longitude[0] + (self._longitude[1] / 60)
return [decimal_degrees, self._longitude[2]]
elif coord_format == DMS:
mins = int(self._longitude[1])
seconds = round((self._longitude[1] - mins) * 60)
return [self._longitude[0], mins, seconds, self._longitude[2]]
elif coord_format == DM:
return self._longitude
raise ValueError('Unknown longitude format.')
def speed(self, units=KNOT):
if units == KNOT:
return self._speed
if units == KPH:
return self._speed * 1.852
if units == MPH:
return self._speed * 1.151
raise ValueError('Unknown speed units.')
async def get_satellite_data(self):
self._total_sv_sentences = 0
while self._total_sv_sentences == 0:
await asyncio.sleep(0)
while self._total_sv_sentences > self._last_sv_sentence:
await asyncio.sleep(0)
return self._satellite_data
def time_since_fix(self): # ms since last valid fix
if self._fix_time is None:
return -1 # No fix yet found
return self._time_diff(self._get_time(), self._fix_time)
def compass_direction(self): # Return cardinal point as string.
from .as_GPS_utils import compass_direction
return compass_direction(self)
def latitude_string(self, coord_format=DM):
if coord_format == DD:
return '{:3.6f}° {:s}'.format(*self.latitude(DD))
if coord_format == DMS:
return """{:3d}° {:2d}' {:2d}" {:s}""".format(*self.latitude(DMS))
if coord_format == KML:
form_lat = self.latitude(DD)
return '{:4.6f}'.format(form_lat[0] if form_lat[1] == 'N' else -form_lat[0])
return "{:3d}° {:3.4f}' {:s}".format(*self.latitude(coord_format))
def longitude_string(self, coord_format=DM):
if coord_format == DD:
return '{:3.6f}° {:s}'.format(*self.longitude(DD))
if coord_format == DMS:
return """{:3d}° {:2d}' {:2d}" {:s}""".format(*self.longitude(DMS))
if coord_format == KML:
form_long = self.longitude(DD)
return '{:4.6f}'.format(form_long[0] if form_long[1] == 'E' else -form_long[0])
return "{:3d}° {:3.4f}' {:s}".format(*self.longitude(coord_format))
def speed_string(self, unit=KPH):
sform = '{:3.2f} {:s}'
speed = self.speed(unit)
if unit == MPH:
return sform.format(speed, 'mph')
elif unit == KNOT:
return sform.format(speed, 'knots')
return sform.format(speed, 'km/h')
# Return local time (hrs: int, mins: int, secs:float)
@property
def local_time(self):
t = self.epoch_time + int(3600 * self.local_offset)
_, _, _, hrs, mins, secs, *_ = self._localtime(t)
return hrs, mins, secs
@property
def date(self):
t = self.epoch_time + int(3600 * self.local_offset)
y, m, d, *_ = self._localtime(t)
return d, m, y - 2000
@property
def utc(self):
t = self.epoch_time
_, _, _, hrs, mins, secs, *_ = self._localtime(t)
return hrs, mins, secs
def time_string(self, local=True):
hrs, mins, secs = self.local_time if local else self.utc
return '{:02d}:{:02d}:{:02d}'.format(hrs, mins, secs)
def date_string(self, formatting=MDY):
from .as_GPS_utils import date_string
return date_string(self, formatting)
| {
"repo_name": "peterhinch/micropython-async",
"path": "v3/as_drivers/as_GPS/as_GPS.py",
"copies": "1",
"size": "23446",
"license": "mit",
"hash": -5766145383878785000,
"line_mean": 37.1073170732,
"line_max": 119,
"alpha_frac": 0.5601638505,
"autogenerated": false,
"ratio": 3.720590569931735,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47807544204317354,
"avg_score": null,
"num_lines": null
} |
# Copyright (c) 2018 Peter Hinch
# Released under the MIT License (MIT) - see LICENSE file
from as_GPS import MDY, DMY, LONG
_DIRECTIONS = ('N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW',
'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW')
def compass_direction(gps): # Return cardinal point as string.
# Calculate the offset for a rotated compass
if gps.course >= 348.75:
offset_course = 360 - gps.course
else:
offset_course = gps.course + 11.25
# Each compass point is separated by 22.5°, divide to find lookup value
return _DIRECTIONS[int(offset_course // 22.5)]
_MONTHS = ('January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October',
'November', 'December')
def date_string(gps, formatting=MDY):
day, month, year = gps.date
# Long Format January 1st, 2014
if formatting == LONG:
dform = '{:s} {:2d}{:s}, 20{:2d}'
# Retrieve Month string from private set
month = _MONTHS[month - 1]
# Determine Date Suffix
if day in (1, 21, 31):
suffix = 'st'
elif day in (2, 22):
suffix = 'nd'
elif day in (3, 23):
suffix = 'rd'
else:
suffix = 'th'
return dform.format(month, day, suffix, year)
dform = '{:02d}/{:02d}/{:02d}'
if formatting == DMY:
return dform.format(day, month, year)
elif formatting == MDY: # Default date format
return dform.format(month, day, year)
raise ValueError('Unknown date format.')
| {
"repo_name": "peterhinch/micropython-async",
"path": "v2/gps/as_GPS_utils.py",
"copies": "1",
"size": "1724",
"license": "mit",
"hash": 3116404175285445600,
"line_mean": 34.8958333333,
"line_max": 77,
"alpha_frac": 0.5803830528,
"autogenerated": false,
"ratio": 3.257088846880907,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4337471899680907,
"avg_score": null,
"num_lines": null
} |
# Copyright (c) 2018 Peter Hinch
# Released under the MIT License (MIT) - see LICENSE file
from .as_GPS import MDY, DMY, LONG
_DIRECTIONS = ('N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW',
'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW')
def compass_direction(gps): # Return cardinal point as string.
# Calculate the offset for a rotated compass
if gps.course >= 348.75:
offset_course = 360 - gps.course
else:
offset_course = gps.course + 11.25
# Each compass point is separated by 22.5°, divide to find lookup value
return _DIRECTIONS[int(offset_course // 22.5)]
_MONTHS = ('January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October',
'November', 'December')
def date_string(gps, formatting=MDY):
day, month, year = gps.date
# Long Format January 1st, 2014
if formatting == LONG:
dform = '{:s} {:2d}{:s}, 20{:2d}'
# Retrieve Month string from private set
month = _MONTHS[month - 1]
# Determine Date Suffix
if day in (1, 21, 31):
suffix = 'st'
elif day in (2, 22):
suffix = 'nd'
elif day in (3, 23):
suffix = 'rd'
else:
suffix = 'th'
return dform.format(month, day, suffix, year)
dform = '{:02d}/{:02d}/{:02d}'
if formatting == DMY:
return dform.format(day, month, year)
elif formatting == MDY: # Default date format
return dform.format(month, day, year)
raise ValueError('Unknown date format.')
| {
"repo_name": "peterhinch/micropython-async",
"path": "v3/as_drivers/as_GPS/as_GPS_utils.py",
"copies": "1",
"size": "1725",
"license": "mit",
"hash": -4883992240282068000,
"line_mean": 34.9166666667,
"line_max": 77,
"alpha_frac": 0.5800464037,
"autogenerated": false,
"ratio": 3.2528301886792454,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9325062115892357,
"avg_score": 0.0015628952973775333,
"num_lines": 48
} |
"""A shallow water model of the ENSO
The model comprises of two coupled shallow water systems representing the
atmosphere and Pacific ocean.
- The ocean component is the mixed-layer: down to the thermocline.
- The atmosphere is the lower part of the troposphere.
The two layers interact: The ocean heats the atmosphere inducing a flow, which,
in turn, forces the ocean through a stress forcing.
The linearised shallow water equations are used, linearised about height H
determined by the Kelvin wave speed in the two layers.
c^2 = gH
* In the atmosphere: g = 10.0 m/s^2, c = 24 m/s => H ~= 58m
* In the ocean: g' = 0.1m/s^2, c = 4 m/s => H = 160m
"""
import numpy as np
import matplotlib.pyplot as plt
from shallowwater import PeriodicLinearShallowWater, WalledLinearShallowWater
np.set_printoptions(precision=2, suppress=True) # 2 dp and hide floating point error
nx = 128
ny = 129
Lx = 1.5e7
Ly = 1.0e7
def gauss(grid, cx, cy, sigma):
return np.exp(- (((grid.phix-cx)/grid.Lx)**2 + ((grid.phiy-cy)/grid.Ly)**2) / sigma )
def gaussu(grid, cx, cy, sigma):
return np.exp(- (((grid.ux-cx)/grid.Lx)**2 + ((grid.uy-cy)/grid.Ly)**2) / sigma )
# Equatorial Beta-Plane
f0 = 0.0 # /s
beta = 2.0e-11 # /m.s
# Kelvin Wave speed in the atmosphere and ocean
c_atmos = 24.0 # m/s
c_ocean = 4.0 # m/s
g_atmos = 10.0 # m/s^2
H_atmos = c_atmos**2 / g_atmos
print('H atmosphere: %.2f' % H_atmos)
g_ocean = 0.1 # m/s^2
H_ocean = c_ocean**2 / g_ocean
print('H ocean: %.2f' % H_ocean)
alpha = 1e-6 # ocean -> atmos heating coefficient
gamma = 5e-7 # wind -> ocean wind stress coefficient
tau = 1e8 # timescale of radiative cooling
# Dissipation coefficients
nu_ocean = 1.0e4
nu_atmos = 1.0e4
# due to the order of magnitude difference in wave speeds in the two fluids
# the atmosphere is integrated over a smaller timestep and more often than
# the ocean.
dt_ocean = 5000.0
dt_atmos = dt_ocean / 10
# `atmos` represents the first baroclinic mode of the atmosphere.
# Localised heating below results in convection: convergence
# at the bottom of the troposphere and divergence at the top.
# We want to simulate the wind in the lower part of the
# troposphere => heating is represented as a *thinning* of the atmosphere layer.
atmos = PeriodicLinearShallowWater(nx, ny, Lx, Ly,
beta=beta, f0=f0,
g=g_atmos, H=H_atmos,
dt=dt_atmos, nu=nu_atmos, r=1e-4)
# add steady trade winds in the tropics
#atmos.u[:] = -0.1*np.cos(np.pi*atmos.uy/Ly)**8
# `ocean` represents the mixed-layer of the ocean; height `h` is the depth
# of the thermocline.
# Where the thermocline is deeper = warmer water. When the layer thins, the
# mixed-layer is cooler due to upwelling from the abyssal ocean.
ocean = WalledLinearShallowWater(nx, ny, Lx, Ly,
beta=beta, f0=f0,
g=g_ocean, H=H_ocean,
dt=dt_ocean, nu=nu_ocean, r=1e-6)
#ocean.phi[:] = gauss(atmos, 0, 0, 0.05)
ocean.phi[:] = np.cos(np.pi*ocean.phiy/Ly)**8*(-2*ocean.phix/Lx)
print("CFL ocean: {}".format(c_ocean * dt_ocean / ocean.dx))
print("CFL atmos: {}".format(c_atmos * dt_atmos / atmos.dx))
@atmos.add_forcing
def heating(a):
global alpha, ocean, atmos
dstate = np.zeros_like(atmos.state)
dstate[2] = -alpha*ocean.h # thicker ocean layer = hotter. hotter atmos => thinner atmos
dstate[2] += -atmos.h / tau # radiative cooling
return dstate
@ocean.add_forcing
def wind_stress(o):
global gamma, ocean, atmos
dstate = np.zeros_like(ocean.state)
dstate[0] = gamma*atmos.u
#dstate[1] = gamma*atmos.v
return dstate
# @atmos.add_forcing
# def trade_winds(a):
# global gust, ocean, atmos
# dstate = np.zeros_like(atmos.state)
# gust = np.zeros_like(atmos.u)
# if np.random.random() < 0.01:
# print('gust!')
# x = (np.random.random()-0.5)*atmos.Lx
# #y = max(np.random.randn()/8.0, 1.0)*atmos.Ly / 2
# y=0
# gust = -gaussu(atmos, x, y, 0.01)*0.1
# dstate[0] = gust
# return dstate
# Initial Condition
d = 25
#ocean.h[10:20, ny//2-10:ny//2+10] = 0.1
#ocean.h[nx//2-d:nx//2+d, ny//2-d:ny//2+d] = H_ocean * 0.01 * (np.sin(np.linspace(0, np.pi, 2*d))**2)[np.newaxis, :] * (np.sin(np.linspace(0, np.pi, 2*d))**2)[:, np.newaxis]
#atmos.h[nx//2-d:nx//2+d, ny//2-d:ny//2+d] = H_atmos * 0.01 * (np.sin(np.linspace(0, np.pi, 2*d))**2)[np.newaxis, :] * (np.sin(np.linspace(0, np.pi, 2*d))**2)[:, np.newaxis]
#atmos.u[nx//2-d:nx//2+d, ny//2-d:ny//2+d] = H_atmos * 0.01 * (np.sin(np.linspace(0, np.pi, 2*d))**2)[np.newaxis, :] * (np.sin(np.linspace(0, np.pi, 2*d))**2)[:, np.newaxis]
#ocean.h[:] = np.random.random((nx, ny)) -0.5
plt.figure(figsize=(18, 6))
plt.ion()
num_levels = 24
colorlevels = np.concatenate([np.linspace(-1, -.05, num_levels//2), np.linspace(.05, 1, num_levels//2)])
cmap = plt.cm.get_cmap('RdBu_r', 13)
cmapr = plt.cm.get_cmap('RdBu', 13)
def absmax(x):
return np.max(np.abs(x))
def velmag(sw):
"""Velocity magnitude."""
u, v = sw.uvath()
return np.sqrt(u**2 + v**2)
hx, hy = np.meshgrid(atmos.hx, atmos.hy)
arrow_spacing = slice(ny // 16, None, ny // 9), slice(nx // 12, None, nx // 12)
avg_thermocline = ocean.h.copy()
ema_multiplier = 2.0 / (20 + 1)
equator_zonal_winds = []
minpoint = []
plt.show()
for i in range(1000000):
ocean.step()
while atmos.t <= ocean.t:
atmos.step()
if i % 20 == 0:
print('Time: %.3f days' % (ocean.t / 86400.0))
mini = np.argmax(ocean.h[:, ny//2])
minpoint.append(mini)
if (ocean.t / 86400.0) > 0:
if i % 10 == 0:
avg_thermocline = avg_thermocline + (ocean.h - avg_thermocline)*ema_multiplier
equator_zonal_winds.append((avg_thermocline - ocean.h)[:, ny//2].copy())
if i % 10 == 0:
print('Time: %.3f days' % (ocean.t / 86400.0))
u, v = atmos.uvath()/absmax(atmos.u)
vel = np.sqrt(u**2 + v**2)
print('Ocean Velocity: %.3f' % absmax(velmag(ocean)))
print('Atmos Velocity: %.3f\n' % absmax(velmag(atmos)))
plt.clf()
plt.subplot(221)
scaled_h = ocean.h.T * 1
#plt.contourf(hx, hy, scaled_h, cmap=plt.cm.RdBu_r, levels=colorlevels*absmax(scaled_h))
plt.title('Thermocline perturbation')
plt.imshow(scaled_h, cmap=cmap)
amax = absmax(scaled_h)
plt.clim(-amax, amax)
plt.colorbar()
plt.subplot(222)
#plt.contourf(hx, hy, atmos.h.T, cmap=plt.cm.RdBu, levels=colorlevels*H_atmos*0.1)#absmax(atmos.h))
scaled_h = atmos.h.T * 1
#plt.contourf(hx, hy, scaled_h, cmap=plt.cm.RdBu_r, levels=colorlevels*absmax(scaled_h))
plt.title('Thermocline perturbation')
plt.imshow(scaled_h, cmap=cmapr)
amax = absmax(scaled_h)
plt.clim(-amax, amax)
plt.colorbar()
plt.title('Atmosphere')
# plt.quiver(hx[arrow_spacing], hy[arrow_spacing],
# np.ma.masked_where(vel.T < 0.1, u.T)[arrow_spacing],
# np.ma.masked_where(vel.T < 0.1, v.T)[arrow_spacing], pivot='mid', scale=15, width=0.005)
# plt.subplot(223)
# plt.contourf(hx, hy, avg_thermocline.T, cmap=plt.cm.RdBu, levels=colorlevels*absmax(avg_thermocline))
plt.subplot(223)
plt.plot(minpoint)
# plt.subplot(223)
# delta = ocean.h - avg_thermocline
# plt.contourf(hx, hy, delta.T, cmap=plt.cm.RdBu, levels=colorlevels*absmax(delta))
# plt.colorbar()
plt.subplot(224)
plt.plot(-ocean.h[:, ny//2], label='thermocline')
plt.plot(-avg_thermocline[:, ny//2], label='moving avg.')
plt.title('Equatorial Thermocline')
plt.legend(loc='lower right')
# # if len(equator_zonal_winds) % 2 == 1:
# # power = np.log(np.abs(np.fft.fft2(np.array(equator_zonal_winds))**2))
# # else:
# # power = np.log(np.abs(np.fft.fft2(np.array(equator_zonal_winds[:-1]))**2))
# power = np.log(np.abs(np.fft.fft2(np.array(equator_zonal_winds))**2))
# # khat = np.fft.fftshift(np.fft.fftfreq(power.shape[1], 1.0/nx))
# # k = khat / Ly
# # omega = np.fft.fftshift(np.fft.fftfreq(power.shape[0], np.diff(timestamps)[-1]))
# # w = omega / np.sqrt(beta*c)
# plt.pcolormesh(np.fft.fftshift(power)[::-1], cmap=plt.cm.gray)
# plt.pcolormesh(np.array(equator_zonal_winds))
plt.pause(0.01)
plt.draw() | {
"repo_name": "jamesp/shallowwater",
"path": "beta_plane/elnino.py",
"copies": "1",
"size": "8641",
"license": "mit",
"hash": -6678961622696163000,
"line_mean": 34.8589211618,
"line_max": 173,
"alpha_frac": 0.5998148362,
"autogenerated": false,
"ratio": 2.6408924205378974,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.37407072567378974,
"avg_score": null,
"num_lines": null
} |
"""A shared variable container for true scalars - for internal use.
Why does this file exist?
-------------------------
Scalars are used to index subtensors. Subtensor indexing is the heart of what
looks like the new scan mechanism. This little file made it possible to catch
up to the Python interpreter in benchmarking tests.
We don't want to encourage people to use scalars (rather than 0-d tensors), but
the reason is just to keep the docs simple, not because scalars are bad. If we
just don't register this shared variable constructor to handle any values by
default when calling theano.shared(value) then users must really go out of their
way (as scan does) to create a shared variable of this kind.
"""
import numpy
from theano.compile import SharedVariable
from .basic import Scalar, _scalar_py_operators
__authors__ = "James Bergstra"
__copyright__ = "(c) 2010, Universite de Montreal"
__license__ = "3-clause BSD License"
__contact__ = "theano-dev <theano-dev@googlegroups.com>"
__docformat__ = "restructuredtext en"
class ScalarSharedVariable(_scalar_py_operators, SharedVariable):
pass
# this is not installed in the default shared variable registry so that
# scalars are typically 0-d tensors.
# still, in case you need a shared variable scalar, you can get one
# by calling this function directly.
def shared(value, name=None, strict=False, allow_downcast=None):
"""SharedVariable constructor for scalar values. Default: int64 or float64.
:note: We implement this using 0-d tensors for now.
"""
if not isinstance(value, (numpy.number, float, int, complex)):
raise TypeError()
try:
dtype = value.dtype
except AttributeError:
dtype = numpy.asarray(value).dtype
dtype = str(dtype)
value = getattr(numpy, dtype)(value)
scalar_type = Scalar(dtype=dtype)
rval = ScalarSharedVariable(
type=scalar_type,
value=value,
name=name,
strict=strict,
allow_downcast=allow_downcast)
return rval
| {
"repo_name": "nke001/attention-lvcsr",
"path": "libs/Theano/theano/scalar/sharedvar.py",
"copies": "1",
"size": "2022",
"license": "mit",
"hash": 8739740340580658000,
"line_mean": 32.1475409836,
"line_max": 80,
"alpha_frac": 0.7131552918,
"autogenerated": false,
"ratio": 3.9724950884086443,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00020238818053025702,
"num_lines": 61
} |
"""A shim module for deprecated imports
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
import types
from importlib import import_module
from .importstring import import_item
class ShimWarning(Warning):
"""A warning to show when a module has moved, and a shim is in its place."""
class ShimImporter(object):
"""Import hook for a shim.
This ensures that submodule imports return the real target module,
not a clone that will confuse `is` and `isinstance` checks.
"""
def __init__(self, src, mirror):
self.src = src
self.mirror = mirror
def _mirror_name(self, fullname):
"""get the name of the mirrored module"""
return self.mirror + fullname[len(self.src):]
def find_module(self, fullname, path=None):
"""Return self if we should be used to import the module."""
if fullname.startswith(self.src + '.'):
mirror_name = self._mirror_name(fullname)
try:
mod = import_item(mirror_name)
except ImportError:
return
else:
if not isinstance(mod, types.ModuleType):
# not a module
return None
return self
def load_module(self, fullname):
"""Import the mirrored module, and insert it into sys.modules"""
mirror_name = self._mirror_name(fullname)
mod = import_item(mirror_name)
sys.modules[fullname] = mod
return mod
class ShimModule(types.ModuleType):
def __init__(self, *args, **kwargs):
self._mirror = kwargs.pop("mirror")
src = kwargs.pop("src", None)
if src:
kwargs['name'] = src.rsplit('.', 1)[-1]
super(ShimModule, self).__init__(*args, **kwargs)
# add import hook for descendent modules
if src:
sys.meta_path.append(
ShimImporter(src=src, mirror=self._mirror)
)
@property
def __path__(self):
return []
@property
def __spec__(self):
"""Don't produce __spec__ until requested"""
return import_module(self._mirror).__spec__
def __dir__(self):
return dir(import_module(self._mirror))
@property
def __all__(self):
"""Ensure __all__ is always defined"""
mod = import_module(self._mirror)
try:
return mod.__all__
except AttributeError:
return [name for name in dir(mod) if not name.startswith('_')]
def __getattr__(self, key):
# Use the equivalent of import_item(name), see below
name = "%s.%s" % (self._mirror, key)
try:
return import_item(name)
except ImportError:
raise AttributeError(key)
| {
"repo_name": "unnikrishnankgs/va",
"path": "venv/lib/python3.5/site-packages/IPython/utils/shimmodule.py",
"copies": "5",
"size": "2855",
"license": "bsd-2-clause",
"hash": 4905733094069747000,
"line_mean": 29.3723404255,
"line_max": 80,
"alpha_frac": 0.5698774081,
"autogenerated": false,
"ratio": 4.332321699544765,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.014459266764231305,
"num_lines": 94
} |
"""A shim module for deprecated imports
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
import types
from .importstring import import_item
class ShimWarning(Warning):
"""A warning to show when a module has moved, and a shim is in its place."""
class ShimImporter(object):
"""Import hook for a shim.
This ensures that submodule imports return the real target module,
not a clone that will confuse `is` and `isinstance` checks.
"""
def __init__(self, src, mirror):
self.src = src
self.mirror = mirror
def _mirror_name(self, fullname):
"""get the name of the mirrored module"""
return self.mirror + fullname[len(self.src):]
def find_module(self, fullname, path=None):
"""Return self if we should be used to import the module."""
if fullname.startswith(self.src + '.'):
mirror_name = self._mirror_name(fullname)
try:
mod = import_item(mirror_name)
except ImportError:
return
else:
if not isinstance(mod, types.ModuleType):
# not a module
return None
return self
def load_module(self, fullname):
"""Import the mirrored module, and insert it into sys.modules"""
mirror_name = self._mirror_name(fullname)
mod = import_item(mirror_name)
sys.modules[fullname] = mod
return mod
class ShimModule(types.ModuleType):
def __init__(self, *args, **kwargs):
self._mirror = kwargs.pop("mirror")
src = kwargs.pop("src", None)
if src:
kwargs['name'] = src.rsplit('.', 1)[-1]
super(ShimModule, self).__init__(*args, **kwargs)
# add import hook for descendent modules
if src:
sys.meta_path.append(
ShimImporter(src=src, mirror=self._mirror)
)
@property
def __path__(self):
return []
@property
def __spec__(self):
"""Don't produce __spec__ until requested"""
return __import__(self._mirror).__spec__
def __dir__(self):
return dir(__import__(self._mirror))
@property
def __all__(self):
"""Ensure __all__ is always defined"""
mod = __import__(self._mirror)
try:
return mod.__all__
except AttributeError:
return [name for name in dir(mod) if not name.startswith('_')]
def __getattr__(self, key):
# Use the equivalent of import_item(name), see below
name = "%s.%s" % (self._mirror, key)
try:
return import_item(name)
except ImportError:
raise AttributeError(key)
| {
"repo_name": "Vvucinic/Wander",
"path": "venv_2_7/lib/python2.7/site-packages/IPython/utils/shimmodule.py",
"copies": "17",
"size": "2809",
"license": "artistic-2.0",
"hash": -1814751438685607000,
"line_mean": 29.5326086957,
"line_max": 80,
"alpha_frac": 0.5617657529,
"autogenerated": false,
"ratio": 4.334876543209877,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""ashinamo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
import os
from settings import BASE_DIR
urlpatterns = [
url(r'^statics/(?P<path>.*)$', 'django.views.static.serve',{"document_root":os.path.join(BASE_DIR, "./static").replace("\\","/")}),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'apphome.views.index', name="index"),
url(r'^cpu/$', 'apphome.views.cpu', name="cpu"),
url(r'^mem/$', 'apphome.views.mem', name="mem"),
url(r'^io/$', 'apphome.views.io', name="io"),
url(r'^net/$', 'apphome.views.net', name="net"),
url(r'^data/cpu/$', 'appdata.views.getcpu', name='datacpu'),
url(r'^data/mem/$', 'appdata.views.getmem', name='datamem'),
url(r'^data/io/$', 'appdata.views.getio', name="dataio"),
url(r'^data/net/$', 'appdata.views.getnet', name="datanet"),
]
| {
"repo_name": "baoyiluo/ashinamo",
"path": "ashinamo/ashinamo/urls.py",
"copies": "1",
"size": "1457",
"license": "apache-2.0",
"hash": -6267151755006871000,
"line_mean": 39.4722222222,
"line_max": 135,
"alpha_frac": 0.6472203157,
"autogenerated": false,
"ratio": 3.1400862068965516,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9278741268537939,
"avg_score": 0.0017130508117225384,
"num_lines": 36
} |
"""ashoka URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from dashboard.forms import LoginForm
admin.site.site_header = 'Ashoka Dashboard Management'
urlpatterns = [
url(r'^login/$', auth_views.login,
{'template_name': 'login.html', 'authentication_form': LoginForm,
'redirect_authenticated_user': True},
name='login'),
url(r'^logout/$', auth_views.logout, {'next_page': '/login'}),
url(r'^manage/', admin.site.urls),
url(r'', include('dashboard.urls')),
]
| {
"repo_name": "jarifibrahim/ashoka-dashboard",
"path": "ashoka/urls.py",
"copies": "1",
"size": "1214",
"license": "apache-2.0",
"hash": -5511663390110626000,
"line_mean": 36.9375,
"line_max": 79,
"alpha_frac": 0.6861614498,
"autogenerated": false,
"ratio": 3.5497076023391814,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47358690521391816,
"avg_score": null,
"num_lines": null
} |
"""A shortcut to deploy a fresh modoboa instance."""
import getpass
import os
from os.path import isfile
import shutil
import subprocess
import sys
import dj_database_url
import django
from django.core import management
from django.template import Context, Template
from django.utils.encoding import smart_str
from modoboa.core.commands import Command
from modoboa.lib.api_client import ModoAPIClient
from modoboa.lib.sysutils import exec_cmd
DBCONN_TPL = """
'{{ conn_name }}': {
'ENGINE': '{{ ENGINE }}',
'NAME': '{{ NAME }}',
'USER': '{% if USER %}{{ USER }}{% endif %}',
'PASSWORD': '{% if PASSWORD %}{{ PASSWORD }}{% endif %}',
'HOST': '{% if HOST %}{{ HOST }}{% endif %}',
'PORT': '{% if PORT %}{{ PORT }}{% endif %}',
'ATOMIC_REQUESTS': True,
{% if ENGINE == 'django.db.backends.mysql' %}'OPTIONS' : {
"init_command" : 'SET foreign_key_checks = 0;',
},{% endif %}
},
"""
class DeployCommand(Command):
"""The ``deploy`` command."""
help = ( # NOQA:A003
"Create a fresh django project (calling startproject)"
" and apply Modoboa specific settings."
)
def __init__(self, *args, **kwargs):
super(DeployCommand, self).__init__(*args, **kwargs)
self._parser.add_argument("name", type=str,
help="The name of your Modoboa instance")
self._parser.add_argument(
"--collectstatic", action="store_true", default=False,
help="Run django collectstatic command"
)
self._parser.add_argument(
"--dburl", type=str, nargs="+", default=None,
help="A database-url with a name")
self._parser.add_argument(
"--domain", type=str, default=None,
help="The domain under which you want to deploy modoboa")
self._parser.add_argument(
"--lang", type=str, default="en",
help="Set the default language"
)
self._parser.add_argument(
"--timezone", type=str, default="UTC",
help="Set the local timezone"
)
self._parser.add_argument(
"--devel", action="store_true", default=False,
help="Create a development instance"
)
self._parser.add_argument(
"--extensions", type=str, nargs="*",
help="The list of extension to deploy"
)
self._parser.add_argument(
"--dont-install-extensions", action="store_true", default=False,
help="Do not install extensions using pip"
)
self._parser.add_argument(
"--admin-username", default="admin",
help="Username of the initial super administrator"
)
def _exec_django_command(self, name, cwd, *args):
"""Run a django command for the freshly created project
:param name: the command name
:param cwd: the directory where the command must be executed
"""
cmd = [sys.executable, "manage.py", name]
cmd.extend(args)
if not self._verbose:
p = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd
)
output = p.communicate()
else:
p = subprocess.Popen(cmd, cwd=cwd)
p.wait()
output = None
if p.returncode:
if output:
print(
"\n".join([l.decode() for l in output if l is not None]),
file=sys.stderr
)
print("%s failed, check your configuration" % cmd, file=sys.stderr)
def ask_db_info(self, name="default"):
"""Prompt the user for database information
Gather all information required to create a new database
connection (into settings.py).
:param name: the connection name
"""
print("Configuring database connection: %s" % name)
info = {
"conn_name": name,
"ENGINE": input(
"Database type (mysql, postgres or sqlite3): ")
}
if info["ENGINE"] not in ["mysql", "postgres", "sqlite3"]:
raise RuntimeError("Unsupported database engine")
if info["ENGINE"] == "sqlite3":
info["ENGINE"] = "django.db.backends.sqlite3"
info["NAME"] = "%s.db" % name
return info
if info["ENGINE"] == "postgres":
info["ENGINE"] = "django.db.backends.postgresql"
default_port = 5432
else:
info["ENGINE"] = "django.db.backends.mysql"
default_port = 3306
info["HOST"] = input("Database host (default: 'localhost'): ")
info["PORT"] = input(
"Database port (default: '%s'): " % default_port)
# leave port setting empty, if default value is supplied and
# leave it to django
if info["PORT"] == default_port:
info["PORT"] = ""
info["NAME"] = input("Database name: ")
info["USER"] = input("Username: ")
info["PASSWORD"] = getpass.getpass("Password: ")
return info
def _get_extension_list(self):
"""Ask the API to get the list of all extensions.
We hardcode the API url here to avoid a loading of
django's settings since they are not available yet...
"""
url = "http://api.modoboa.org/"
official_exts = ModoAPIClient(url).list_extensions()
return [extension["name"] for extension in official_exts]
def find_extra_settings(self, extensions):
"""Install one or more extensions.
Return the list of extensions providing settings we must
include in the final configuration.
"""
extra_settings = []
for extension in extensions:
module = __import__(extension[1], locals(), globals(), [])
basedir = os.path.dirname(module.__file__)
if not os.path.exists("{0}/settings.py".format(basedir)):
continue
extra_settings.append(extension[1])
return extra_settings
def handle(self, parsed_args):
django.setup()
management.call_command(
"startproject", parsed_args.name, verbosity=False
)
path = "%(name)s/%(name)s" % {"name": parsed_args.name}
sys.path.append(parsed_args.name)
conn_tpl = Template(DBCONN_TPL)
connections = {}
if parsed_args.dburl:
for dburl in parsed_args.dburl:
conn_name, url = dburl.split(":", 1)
info = dj_database_url.config(default=url)
# In case the user fails to supply a valid database url,
# fallback to manual mode
if not info:
print("There was a problem with your database-url. \n")
info = self.ask_db_info(conn_name)
# If we set this earlier, our fallback method will never
# be triggered
info["conn_name"] = conn_name
connections[conn_name] = conn_tpl.render(Context(info))
else:
connections["default"] = conn_tpl.render(
Context(self.ask_db_info()))
if parsed_args.domain:
allowed_host = parsed_args.domain
else:
allowed_host = input(
"What will be the hostname used to access Modoboa? ")
if not allowed_host:
allowed_host = "localhost"
extra_settings = []
extensions = parsed_args.extensions
if extensions:
if "all" in extensions:
extensions = self._get_extension_list()
extensions = [(extension, extension.replace("-", "_"))
for extension in extensions]
if not parsed_args.dont_install_extensions:
cmd = (
sys.executable +
" -m pip install " +
" ".join([extension[0] for extension in extensions])
)
exec_cmd(cmd, capture_output=False)
extra_settings = self.find_extra_settings(extensions)
extensions = [extension[1] for extension in extensions]
bower_components_dir = os.path.realpath(
os.path.join(os.path.dirname(__file__), "../../bower_components")
)
mod = __import__(
parsed_args.name, globals(), locals(), [smart_str("settings")]
)
tpl = self._render_template(
"%s/settings.py.tpl" % self._templates_dir, {
"db_connections": connections,
"secret_key": mod.settings.SECRET_KEY,
"name": parsed_args.name,
"allowed_host": allowed_host,
"lang": parsed_args.lang,
"timezone": parsed_args.timezone,
"bower_components_dir": bower_components_dir,
"devmode": parsed_args.devel,
"extensions": extensions,
"extra_settings": extra_settings
}
)
with open("%s/settings.py" % path, "w") as fp:
fp.write(tpl)
shutil.copyfile(
"%s/urls.py.tpl" % self._templates_dir, "%s/urls.py" % path
)
os.mkdir("%s/media" % parsed_args.name)
if isfile("%s/settings.pyc" % path):
os.unlink("%s/settings.pyc" % path)
self._exec_django_command(
"migrate", parsed_args.name, "--noinput"
)
self._exec_django_command(
"load_initial_data", parsed_args.name,
"--admin-username", parsed_args.admin_username
)
if parsed_args.collectstatic:
self._exec_django_command(
"collectstatic", parsed_args.name, "--noinput"
)
self._exec_django_command(
"set_default_site", parsed_args.name, allowed_host
)
base_frontend_dir = os.path.join(
os.path.dirname(__file__), "../../../frontend/dist/")
if not os.path.exists(base_frontend_dir):
return
frontend_target_dir = "{}/frontend".format(parsed_args.name)
shutil.copytree(base_frontend_dir, frontend_target_dir)
with open("{}/config.json".format(frontend_target_dir), "w") as fp:
fp.write("""{
"API_BASE_URL": "https://%s/api/v2"
}
""" % allowed_host)
| {
"repo_name": "modoboa/modoboa",
"path": "modoboa/core/commands/deploy.py",
"copies": "1",
"size": "10466",
"license": "isc",
"hash": -628932178777296600,
"line_mean": 36.1134751773,
"line_max": 79,
"alpha_frac": 0.5411809669,
"autogenerated": false,
"ratio": 4.249289484368656,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5290470451268656,
"avg_score": null,
"num_lines": null
} |
# A* Shortest Path Algorithm
# http://en.wikipedia.org/wiki/A*
# FB - 201012256
from heapq import heappush, heappop # for priority queue
import math
import time
import random
class node:
xPos = 0 # x position
yPos = 0 # y position
distance = 0 # total distance already travelled to reach the node
priority = 0 # priority = distance + remaining distance estimate
def __init__(self, xPos, yPos, distance, priority):
self.xPos = xPos
self.yPos = yPos
self.distance = distance
self.priority = priority
def __lt__(self, other): # comparison method for priority queue
return self.priority < other.priority
def updatePriority(self, xDest, yDest):
self.priority = self.distance + self.estimate(xDest, yDest) * 10 # A*
# give higher priority to going straight instead of diagonally
def nextMove(self, dirs, d): # d: direction to move
if dirs == 8 and d % 2 != 0:
self.distance += 14
else:
self.distance += 10
# Estimation function for the remaining distance to the goal.
def estimate(self, xDest, yDest):
xd = xDest - self.xPos
yd = yDest - self.yPos
# Euclidian Distance
d = math.sqrt(xd * xd + yd * yd)
# Manhattan distance
# d = abs(xd) + abs(yd)
# Chebyshev distance
# d = max(abs(xd), abs(yd))
return(d)
# A-star algorithm.
# The path returned will be a string of digits of directions.
def pathFind(the_map, n, m, dirs, dx, dy, xA, yA, xB, yB):
closed_nodes_map = [] # map of closed (tried-out) nodes
open_nodes_map = [] # map of open (not-yet-tried) nodes
dir_map = [] # map of dirs
row = [0] * n
for i in range(m): # create 2d arrays
closed_nodes_map.append(list(row))
open_nodes_map.append(list(row))
dir_map.append(list(row))
pq = [[], []] # priority queues of open (not-yet-tried) nodes
pqi = 0 # priority queue index
# create the start node and push into list of open nodes
n0 = node(xA, yA, 0, 0)
n0.updatePriority(xB, yB)
heappush(pq[pqi], n0)
open_nodes_map[yA][xA] = n0.priority # mark it on the open nodes map
# A* search
while len(pq[pqi]) > 0:
# get the current node w/ the highest priority
# from the list of open nodes
n1 = pq[pqi][0] # top node
n0 = node(n1.xPos, n1.yPos, n1.distance, n1.priority)
x = n0.xPos
y = n0.yPos
heappop(pq[pqi]) # remove the node from the open list
open_nodes_map[y][x] = 0
closed_nodes_map[y][x] = 1 # mark it on the closed nodes map
# quit searching when the goal is reached
# if n0.estimate(xB, yB) == 0:
if x == xB and y == yB:
# generate the path from finish to start
# by following the dirs
path = ''
while not (x == xA and y == yA):
j = dir_map[y][x]
c = str((j + dirs / 2) % dirs)
path = c + path
x += dx[j]
y += dy[j]
return path
# generate moves (child nodes) in all possible dirs
for i in range(dirs):
xdx = x + dx[i]
ydy = y + dy[i]
if not (xdx < 0 or xdx > n-1 or ydy < 0 or ydy > m - 1
or the_map[ydy][xdx] == 1 or closed_nodes_map[ydy][xdx] == 1):
# generate a child node
m0 = node(xdx, ydy, n0.distance, n0.priority)
m0.nextMove(dirs, i)
m0.updatePriority(xB, yB)
# if it is not in the open list then add into that
if open_nodes_map[ydy][xdx] == 0:
open_nodes_map[ydy][xdx] = m0.priority
heappush(pq[pqi], m0)
# mark its parent node direction
dir_map[ydy][xdx] = (i + dirs / 2) % dirs
elif open_nodes_map[ydy][xdx] > m0.priority:
# update the priority
open_nodes_map[ydy][xdx] = m0.priority
# update the parent direction
dir_map[ydy][xdx] = (i + dirs / 2) % dirs
# replace the node
# by emptying one pq to the other one
# except the node to be replaced will be ignored
# and the new node will be pushed in instead
while not (pq[pqi][0].xPos == xdx and pq[pqi][0].yPos == ydy):
heappush(pq[1 - pqi], pq[pqi][0])
heappop(pq[pqi])
heappop(pq[pqi]) # remove the target node
# empty the larger size priority queue to the smaller one
if len(pq[pqi]) > len(pq[1 - pqi]):
pqi = 1 - pqi
while len(pq[pqi]) > 0:
heappush(pq[1-pqi], pq[pqi][0])
heappop(pq[pqi])
pqi = 1 - pqi
heappush(pq[pqi], m0) # add the better node instead
return '' # if no route found
# MAIN
dirs = 8 # number of possible directions to move on the map
if dirs == 4:
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
elif dirs == 8:
dx = [1, 1, 0, -1, -1, -1, 0, 1]
dy = [0, 1, 1, 1, 0, -1, -1, -1]
n = 30 # horizontal size of the map
m = 30 # vertical size of the map
the_map = []
row = [0] * n
for i in range(m): # create empty map
the_map.append(list(row))
# fillout the map with a '+' pattern
for x in range(n / 8, n * 7 / 8):
the_map[m / 2][x] = 1
for y in range(m/8, m * 7 / 8):
the_map[y][n / 2] = 1
# randomly select start and finish locations from a list
sf = []
sf.append((0, 0, n - 1, m - 1))
sf.append((0, m - 1, n - 1, 0))
sf.append((n / 2 - 1, m / 2 - 1, n / 2 + 1, m / 2 + 1))
sf.append((n / 2 - 1, m / 2 + 1, n / 2 + 1, m / 2 - 1))
sf.append((n / 2 - 1, 0, n / 2 + 1, m - 1))
sf.append((n / 2 + 1, m - 1, n / 2 - 1, 0))
sf.append((0, m / 2 - 1, n - 1, m / 2 + 1))
sf.append((n - 1, m / 2 + 1, 0, m / 2 - 1))
(xA, yA, xB, yB) = random.choice(sf)
print 'Map size (X,Y): ', n, m
print 'Start: ', xA, yA
print 'Finish: ', xB, yB
t = time.time()
route = pathFind(the_map, n, m, dirs, dx, dy, xA, yA, xB, yB)
print 'Time to generate the route (seconds): ', time.time() - t
print 'Route:'
print route
# mark the route on the map
if len(route) > 0:
x = xA
y = yA
the_map[y][x] = 2
for i in range(len(route)):
j = int(route[i])
x += dx[j]
y += dy[j]
the_map[y][x] = 3
the_map[y][x] = 4
# display the map with the route added
print 'Map:'
for y in range(m):
for x in range(n):
xy = the_map[y][x]
if xy == 0:
print '.', # space
elif xy == 1:
print 'O', # obstacle
elif xy == 2:
print 'S', # start
elif xy == 3:
print 'R', # route
elif xy == 4:
print 'F', # finish
print
raw_input('Press Enter...')
| {
"repo_name": "ActiveState/code",
"path": "recipes/Python/577519_Astar_Shortest_Path_Algorithm/recipe-577519.py",
"copies": "1",
"size": "7033",
"license": "mit",
"hash": -3640535679045650400,
"line_mean": 34.5202020202,
"line_max": 82,
"alpha_frac": 0.5113038533,
"autogenerated": false,
"ratio": 3.1723049165539017,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4183608769853902,
"avg_score": null,
"num_lines": null
} |
# A* Shortest Path Algorithm
# http://en.wikipedia.org/wiki/A*
# FB - 201012256
from heapq import heappush, heappop # for priority queue
import math
import time
import random
class Node:
xPos = 0 # x position
yPos = 0 # y position
distance = 0 # total distance already travelled to reach the node
priority = 0 # priority = distance + remaining distance estimate
def __init__(self, xPos, yPos, distance, priority):
self.xPos = xPos
self.yPos = yPos
self.distance = distance
self.priority = priority
def __lt__(self, other): # comparison method for priority queue
return self.priority < other.priority
def updatePriority(self, xDest, yDest):
self.priority = self.distance + self.estimate(xDest, yDest) * 10 # A*
# give higher priority to going straight instead of diagonally
def nextMove(self, dirs, d): # d: direction to move
if dirs == 8 and d % 2 != 0:
self.distance += 14
else:
self.distance += 10
# Estimation function for the remaining distance to the goal.
def estimate(self, xDest, yDest):
xd = xDest - self.xPos
yd = yDest - self.yPos
# Euclidian Distance
d = math.sqrt(xd * xd + yd * yd)
# Manhattan distance
# d = abs(xd) + abs(yd)
# Chebyshev distance
# d = max(abs(xd), abs(yd))
return(d)
# A-star algorithm.
# The path returned will be a string of digits of directions.
def pathFind(the_map, n, m, dirs, dx, dy, xA, yA, xB, yB):
closed_nodes_map = [] # map of closed (tried-out) nodes
open_nodes_map = [] # map of open (not-yet-tried) nodes
dir_map = [] # map of dirs
row = [0] * n
for i in range(m): # create 2d arrays
closed_nodes_map.append(list(row))
open_nodes_map.append(list(row))
dir_map.append(list(row))
pq = [[], []] # priority queues of open (not-yet-tried) nodes
pqi = 0 # priority queue index
# create the start node and push into list of open nodes
n0 = Node(xA, yA, 0, 0)
n0.updatePriority(xB, yB)
heappush(pq[pqi], n0)
open_nodes_map[yA][xA] = n0.priority # mark it on the open nodes map
# A* search
while len(pq[pqi]) > 0:
# get the current node w/ the highest priority
# from the list of open nodes
n1 = pq[pqi][0] # top node
n0 = Node(n1.xPos, n1.yPos, n1.distance, n1.priority)
x = n0.xPos
y = n0.yPos
heappop(pq[pqi]) # remove the node from the open list
open_nodes_map[y][x] = 0
closed_nodes_map[y][x] = 1 # mark it on the closed nodes map
# quit searching when the goal is reached
# if n0.estimate(xB, yB) == 0:
if x == xB and y == yB:
# generate the path from finish to start
# by following the dirs
path = ''
while not (x == xA and y == yA):
j = dir_map[y][x]
c = str((j + dirs / 2) % dirs)
path = c + path
x += dx[j]
y += dy[j]
return path
# generate moves (child nodes) in all possible dirs
for i in range(dirs):
xdx = x + dx[i]
ydy = y + dy[i]
if not (xdx < 0 or xdx > n-1 or ydy < 0 or ydy > m - 1
or the_map[ydy][xdx] == 1 or closed_nodes_map[ydy][xdx] == 1):
# generate a child node
m0 = Node(xdx, ydy, n0.distance, n0.priority)
m0.nextMove(dirs, i)
m0.updatePriority(xB, yB)
# if it is not in the open list then add into that
if open_nodes_map[ydy][xdx] == 0:
open_nodes_map[ydy][xdx] = m0.priority
heappush(pq[pqi], m0)
# mark its parent node direction
dir_map[ydy][xdx] = (i + dirs / 2) % dirs
elif open_nodes_map[ydy][xdx] > m0.priority:
# update the priority
open_nodes_map[ydy][xdx] = m0.priority
# update the parent direction
dir_map[ydy][xdx] = (i + dirs / 2) % dirs
# replace the node
# by emptying one pq to the other one
# except the node to be replaced will be ignored
# and the new node will be pushed in instead
while not (pq[pqi][0].xPos == xdx and pq[pqi][0].yPos == ydy):
heappush(pq[1 - pqi], pq[pqi][0])
heappop(pq[pqi])
heappop(pq[pqi]) # remove the target node
# empty the larger size priority queue to the smaller one
if len(pq[pqi]) > len(pq[1 - pqi]):
pqi = 1 - pqi
while len(pq[pqi]) > 0:
heappush(pq[1-pqi], pq[pqi][0])
heappop(pq[pqi])
pqi = 1 - pqi
heappush(pq[pqi], m0) # add the better node instead
return 'No Path' # if no route found
def main():
dirs = 8 # number of possible directions to move on the map
if dirs == 4:
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
elif dirs == 8:
dx = [1, 1, 0, -1, -1, -1, 0, 1]
dy = [0, 1, 1, 1, 0, -1, -1, -1]
n = 50 # horizontal size of the map
m = 50 # vertical size of the map
the_map = []
row = [0] * n
for i in range(m): # create empty map
the_map.append(list(row))
# fillout the map with a '+' pattern
for x in range(n / 8, n * 7 / 8):
the_map[m / 2][x] = 1
for y in range(m/8, m * 7 / 8):
the_map[y][n / 2] = 1
# randomly select start and finish locations from a list
sf = []
sf.append((0, 0, n - 1, m - 1))
sf.append((0, m - 1, n - 1, 0))
sf.append((n / 2 - 1, m / 2 - 1, n / 2 + 1, m / 2 + 1))
sf.append((n / 2 - 1, m / 2 + 1, n / 2 + 1, m / 2 - 1))
sf.append((n / 2 - 1, 0, n / 2 + 1, m - 1))
sf.append((n / 2 + 1, m - 1, n / 2 - 1, 0))
sf.append((0, m / 2 - 1, n - 1, m / 2 + 1))
sf.append((n - 1, m / 2 + 1, 0, m / 2 - 1))
(xA, yA, xB, yB) = random.choice(sf)
print 'Map size (X,Y): ', n, m
print 'Start: ', xA, yA
print 'Finish: ', xB, yB
t = time.time()
route = pathFind(the_map, n, m, dirs, dx, dy, xA, yA, xB, yB)
print 'Time to generate the route (seconds): ', time.time() - t
print 'Route:'
print route
# mark the route on the map
if len(route) > 0:
x = xA
y = yA
the_map[y][x] = 2
for i in range(len(route)):
j = int(route[i])
x += dx[j]
y += dy[j]
the_map[y][x] = 3
the_map[y][x] = 4
# display the map with the route added
print 'Map:'
for y in range(m):
for x in range(n):
xy = the_map[y][x]
if xy == 0:
print '.', # space
elif xy == 1:
print 'O', # obstacle
elif xy == 2:
print 'S', # start
elif xy == 3:
print 'R', # route
elif xy == 4:
print 'F', # finish
print
if __name__ == '__main__':
main()
| {
"repo_name": "COHRINT/cops_and_robots",
"path": "src/cops_and_robots/robo_tools/a_star.py",
"copies": "1",
"size": "7335",
"license": "apache-2.0",
"hash": -4221987956669642000,
"line_mean": 34.7804878049,
"line_max": 82,
"alpha_frac": 0.4909338787,
"autogenerated": false,
"ratio": 3.2716324710080285,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9255219428697768,
"avg_score": 0.0014693842020519984,
"num_lines": 205
} |
# A* Shortest Path Algorithm
# http://en.wikipedia.org/wiki/A*
# FB - 201012256
from heapq import heappush, heappop # for priority queue
import math
class node:
# current position
xPos = 0
yPos = 0
# total distance already travelled to reach the node
distance = 0
# priority = distance + remaining distance estimate
priority = 0 # smaller: higher priority
def __init__(self, xPos, yPos, distance, priority):
self.xPos = xPos
self.yPos = yPos
self.distance = distance
self.priority = priority
def __lt__(self, other): # for priority queue
return self.priority < other.priority
def updatePriority(self, xDest, yDest):
self.priority = self.distance + self.estimate(xDest, yDest) * 10 # A*
# give better priority to going straight instead of diagonally
def nextdistance(self, i): # i: direction
if i % 2 == 0:
self.distance += 10
else:
self.distance += 14
# Estimation function for the remaining distance to the goal.
def estimate(self, xDest, yDest):
xd = xDest - self.xPos
yd = yDest - self.yPos
# Euclidian Distance
d = math.sqrt(xd * xd + yd * yd)
# Manhattan distance
# d = abs(xd) + abs(yd)
# Chebyshev distance
# d = max(abs(xd), abs(yd))
return(d)
# A-star algorithm.
# Path returned will be a string of digits of directions.
def pathFind(the_map, directions, dx, dy, xStart, yStart, xFinish, yFinish):
closed_nodes_map = [] # map of closed (tried-out) nodes
open_nodes_map = [] # map of open (not-yet-tried) nodes
dir_map = [] # map of directions
row = [0] * n
for i in range(m): # create 2d arrays
closed_nodes_map.append(list(row))
open_nodes_map.append(list(row))
dir_map.append(list(row))
pq = [[], []] # priority queues of open (not-yet-tried) nodes
pqi = 0 # priority queue index
# create the start node and push into list of open nodes
n0 = node(xStart, yStart, 0, 0)
n0.updatePriority(xFinish, yFinish)
heappush(pq[pqi], n0)
open_nodes_map[yStart][xStart] = n0.priority # mark it on the open nodes map
# A* search
while len(pq[pqi]) > 0:
# get the current node w/ the highest priority
# from the list of open nodes
n1 = pq[pqi][0] # top node
n0 = node(n1.xPos, n1.yPos, n1.distance, n1.priority)
x = n0.xPos
y = n0.yPos
heappop(pq[pqi]) # remove the node from the open list
open_nodes_map[y][x] = 0
# mark it on the closed nodes map
closed_nodes_map[y][x] = 1
# quit searching when the goal state is reached
# if n0.estimate(xFinish, yFinish) == 0:
if x == xFinish and y == yFinish:
# generate the path from finish to start
# by following the directions
path = ''
while not (x == xStart and y == yStart):
j = dir_map[y][x]
c = str((j + directions // 2) % directions)
path = c + path
x += dx[j]
y += dy[j]
return path
# generate moves (child nodes) in all possible directions
for i in range(directions):
xdx = x + dx[i]
ydy = y + dy[i]
if not (xdx < 0 or xdx > n-1 or ydy < 0 or ydy > m - 1
or the_map[ydy][xdx] == 1 or closed_nodes_map[ydy][xdx] == 1):
# generate a child node
m0 = node(xdx, ydy, n0.distance, n0.priority)
m0.nextdistance(i)
m0.updatePriority(xFinish, yFinish)
# if it is not in the open list then add into that
if open_nodes_map[ydy][xdx] == 0:
open_nodes_map[ydy][xdx] = m0.priority
heappush(pq[pqi], m0)
# mark its parent node direction
dir_map[ydy][xdx] = (i + directions // 2) % directions
elif open_nodes_map[ydy][xdx] > m0.priority:
# update the priority info
open_nodes_map[ydy][xdx] = m0.priority
# update the parent direction info
dir_map[ydy][xdx] = (i + directions // 2) % directions
# replace the node
# by emptying one pq to the other one
# except the node to be replaced will be ignored
# and the new node will be pushed in instead
while not (pq[pqi][0].xPos == xdx and pq[pqi][0].yPos == ydy):
heappush(pq[1 - pqi], pq[pqi][0])
heappop(pq[pqi])
heappop(pq[pqi]) # remove the wanted node
# empty the larger size pq to the smaller one
if len(pq[pqi]) > len(pq[1 - pqi]):
pqi = 1 - pqi
while len(pq[pqi]) > 0:
heappush(pq[1-pqi], pq[pqi][0])
heappop(pq[pqi])
pqi = 1 - pqi
heappush(pq[pqi], m0) # add the better node instead
return '' # no route found
def translatePath(path):
translation = ""
for i in path:
if(i=="0"):
#To the right
translation = translation + "1"
elif(i=="1"):
#Up
translation = translation + "3"
elif(i=="2"):
#To the left
translation = translation + "2"
elif(i=="3"):
#Down
translation = translation + "4"
return translation
# MAIN
directions = 4 # number of possible directions to move on the map
if directions == 4:
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
# dx = [1, -1, 0, 0]
# dy = [0, 0, -1, 1]
elif directions == 8:
dx = [1, 1, 0, -1, -1, -1, 0, 1]
dy = [0, 1, 1, 1, 0, -1, -1, -1]
# map matrix
n = 20 # horizontal size
m = 20 # vertical size
# the_map = []
# row = [0] * n
# for i in range(m):
# the_map.append(list(row))
# # fillout the map matrix with a '+' pattern
# for x in range(n // 8, n * 7 //8):
# the_map[m //2][x] = 1
# for y in range(m//8, m * 7 // 8):
# the_map[y][n // 2] = 1
# # randomly select start and finish locations from a list
# sf = []
# sf.append((0, 0, n - 1, m - 1))
# sf.append((0, m - 1, n - 1, 0))
# sf.append((n // 2 - 1, m // 2 - 1, n // 2 + 1, m // 2 + 1))
# sf.append((n // 2 - 1, m // 2 + 1, n // 2 + 1, m // 2 - 1))
# sf.append((n // 2 - 1, 0, n // 2 + 1, m - 1))
# sf.append((n // 2 + 1, m - 1, n // 2 - 1, 0))
# sf.append((0, m // 2 - 1, n - 1, m // 2 + 1))
# sf.append((n - 1, m // 2 + 1, 0, m // 2 - 1))
# (xA, yA, xB, yB) = random.choice(sf)
# print ('Start: ', xA, yA)
# print ('Finish: ', xB, yB)
# t = time.time()
# route = pathFind(the_map, directions, dx, dy, xA, yA, xB, yB)
# print ('Time to generate the route (s): ', time.time() - t)
# print ('Route:')
# print (route)
# print (translatePath(route))
# # mark the route on the map
# if len(route) > 0:
# x = xA
# y = yA
# the_map[y][x] = 2
# for i in range(len(route)):
# j = int(route[i])
# x += dx[j]
# y += dy[j]
# the_map[y][x] = 3
# the_map[y][x] = 4
# # display the map with the route
# print ('Map:')
# for y in range(m):
# for x in range(n):
# xy = the_map[y][x]
# if xy == 0:
# print ('.', end="") # space
# elif xy == 1:
# print ('O', end="") # obstacle
# elif xy == 2:
# print ('S',end="") # start
# elif xy == 3:
# print ('R', end="") # route
# elif xy == 4:
# print ('F', end="") # finish
# print()
# print ('Map Size (X,Y): ', n, m)
# # for i in the_map:
# # for j in i:
# # print(j,end="")
# # print("")
# input('Press Enter...')
| {
"repo_name": "Juanpam/Pakman",
"path": "astar.py",
"copies": "1",
"size": "7938",
"license": "mit",
"hash": -5091242518222696000,
"line_mean": 33.2155172414,
"line_max": 82,
"alpha_frac": 0.5011337868,
"autogenerated": false,
"ratio": 3.2176732873935956,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9187026319003722,
"avg_score": 0.00635615103797482,
"num_lines": 232
} |
""" A short package to interogate TAP services """
import requests
import time
import math
try: # python 3
from io import BytesIO
from http.client import HTTPConnection
from urllib.parse import urlencode
except ImportError: # python 2
from StringIO import StringIO as BytesIO
from httplib import HTTPConnection
from urllib import urlencode
from xml.dom.minidom import parseString
from lxml import etree
import json
from astropy.table import Table
try:
from IPython.display import Markdown, display
except ImportError:
Markdown = None
display = None
def _pretty_print_time(t):
""" Print time with units """
units = [u"s", u"ms", u'us', "ns"]
scaling = [1, 1e3, 1e6, 1e9]
if t > 0.0 and t < 1000.0:
order = min(-int(math.floor(math.log10(t)) // 3), 3)
elif t >= 1000.0:
order = 0
else:
order = 3
return "%.3g %s" % (t * scaling[order], units[order])
class TAP_AsyncQuery(object):
""" Asynchronous Query
Attributes
---------
host: str
tap host
path: str
path to the service on host
port: int
port of the service
adql_query: str
query
session: Session object
use a given requests.Session to proceed
esp. useful with authenticated sessions
"""
def __init__(self, adql_query, host, path, port=80, session=None, protocol='http'):
""" set the query """
self.adql = adql_query
self.host = host
self.port = port
self.protocol = protocol
self.path = path
self.location = None
self.jobid = None
self.response = None
self.session = session
def submit(self, silent=False):
""" Submit the query to the server
Parameters
----------
silent: bool
prints some information if not set
"""
data = {'query': str(self.adql),
'request': 'doQuery',
'lang': 'ADQL',
'format': 'votable',
'phase': 'run'}
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"
}
# add authentication and other cookies to the header
try:
cookies = self.session.cookies
headers['Cookie'] = ';'.join("{0}={1}".format(k,v) for k,v in cookies.items())
except:
pass
connection = HTTPConnection(self.host, self.port)
connection.request("POST", self.path, urlencode(data), headers)
#Status
self.response = connection.getresponse()
#Server job location (URL)
self.location = self.response.getheader("location")
#Jobid
self.jobid = self.location[self.location.rfind('/') + 1:]
connection.close()
if not silent:
print("Query Status: " + str(self.response.status),
"Reason: " + str(self.response.reason))
print("Location: " + self.location)
print("Job id: " + self.jobid)
@classmethod
def recall_query(cls, host, path, port, jobid, protocol='http'):
""" Connect to a remote job
Parameters
----------
host: str
tap host
path: str
path to the service on host
port: int
port of the service
jobid: str
job identifier
Returns
-------
query: TAP_AsyncQuery
asynchrone query object
"""
location = '{1:s}/{2:s}/async/{0:s}'.format(jobid, host, path)
q = cls("", host, path, port)
q.location = location
q.jobid = jobid
q.protocol = protocol
return q
@property
def status(self):
""" Check job status on the server """
headers = {}
# add authentication and other cookies to the header
try:
location = self.location
location = location.split('://')[-1]
self.response = self.session.get(self.protocol + '://' + location)
data = self.response.text
except:
connection = HTTPConnection(self.host, self.port)
connection.request("GET", self.path + "/" + self.jobid, headers)
self.response = connection.getresponse()
data = self.response.read()
#XML response: parse it to obtain the current status
dom = parseString(data)
phase_element = dom.getElementsByTagName('uws:phase')[0]
phase_value_element = phase_element.firstChild
phase = phase_value_element.toxml()
return phase
@property
def finished(self):
""" Check if job done """
return self.status == 'COMPLETED'
def get(self, sleep=0.2, wait=True):
"""
Get the result or wait until ready
Parameters
----------
sleep: float
Delay between status update for a given number of seconds
wait: bool
set to wait until result is ready
Returns
-------
table: Astropy.Table
votable result
"""
while (not self.finished) & wait:
time.sleep(sleep)
if not self.finished:
return
#Get results
try:
location = self.location
location = location.split('://')[-1]
self.response = self.session.get(self.protocol + '://' + location + "/results/result")
self.data = self.response.text
except:
connection = HTTPConnection(self.host, self.port)
connection.request("GET", self.path + "/" + self.jobid + "/results/result")
self.response = connection.getresponse()
self.data = self.response.read()
connection.close()
try:
table = Table.read(BytesIO(self.data), format="votable")
return table
except TypeError:
table = Table.read(BytesIO(self.data.encode('utf8')), format="votable")
return table
except Exception as e:
content = parseString(self.response.text)
text = []
for k in content.getElementsByTagName('INFO'):
name, value = k.attributes.values()
if 'QUERY_STATUS' in value.nodeValue:
status = value.nodeValue
print(status)
text.append(k.firstChild.nodeValue.replace('.', '.\n').replace(':', ':\n'))
print(e)
raise RuntimeError('Query error.\n{0}'.format('\n'.join(text)))
def _repr_markdown_(self):
try:
from IPython.display import Markdown
return Markdown("""*ADQL Query*\n```mysql\n{0}\n```\n* *Status*: `{1}`, Reason `{2}`\n* *Location*: {3}\n* *Job id*: `{4}`\n
""".format(str(self.adql), str(self.response.status),
str(self.response.reason),
self.location, self.jobid))._repr_markdown_()
except ImportError:
pass
class TAP_Service(object):
"""
Attributes
----------
host: str
tap host
path: str
path to the service on host
port: int
port of the service
adql_query: str
query
"""
def __init__(self, host, path, port=80, protocol='http', **kargs):
self.host = host
self.port = port
self.path = path
self.protocol = protocol
self.session = requests.Session()
@property
def tap_endpoint(self):
""" Full path """
return "{s.protocol:s}://{s.host:s}{s.path:s}".format(s=self)
def recall_query(self, jobid):
""" Connect to a remote job
Parameters
----------
jobid: str
job identifier
Returns
-------
query: TAP_AsyncQuery
asynchrone query object
"""
location = '{1:s}{2:s}/async/{0:s}'.format(jobid, self.host, self.path)
q = TAP_AsyncQuery("", self.host, self.path, self.port, self.session,
protocol=self.protocol)
q.location = location
q.jobid = jobid
return q
def login(self, username, password=None):
"""
Login to the service
Password is not stored with this object, only the cookie will be
Parameters
----------
username: string
username to use with this service
password: string, optional
password. If not provided, will prompt for it (not stored later)
"""
if password is None:
import getpass
password = getpass.getpass()
r = self.session.post("https://{s.host:s}/tap-server/login".format(s=self),
data={'username': username, 'password':password})
if not r.ok:
raise RuntimeError('Authentication failed\n' + str(r))
def logout(self):
"""
Logout from the service
"""
return self.session.post("https://{s.host:s}/tap-server/logout".format(s=self))
def query(self, adql_query, sync=True):
"""
Query a TAP service synchronously
with a given ADQL query
Parameters
----------
adql_query: str
query to send
Returns
-------
tab: Astropy.Table
votable result
"""
if sync:
r = self.session.post(self.tap_endpoint + '/sync',
data={'query': str(adql_query),
'request': 'doQuery',
'lang': 'ADQL',
'format': 'votable',
'phase': 'run'}
)
try:
table = Table.read(BytesIO(r.text.encode('utf8')),
format="votable")
return table
except: # help debugging
self.response = r
content = parseString(self.response.text)
text = []
for k in content.getElementsByTagName('INFO'):
name, value = k.attributes.values()
if 'QUERY_STATUS' in value.nodeValue:
status = value.nodeValue
print(status)
text.append(k.firstChild.nodeValue.replace('.', '.\n').replace(':', ':\n'))
raise RuntimeError('Query error.\n{0}'.format('\n'.join(text)))
else:
return self.query_async(adql_query)
def query_async(self, adql_query, submit=True, **kwargs):
""" Send an async query
Parameters
----------
adql_query: str
query to send
submit: bool
set to submit the query otherwise
returns the constructed query that
can be submitted later.
Returns
-------
query: TAP_AsyncQuery
Query object
"""
q = TAP_AsyncQuery(adql_query, self.host,
self.path + '/async',
port=self.port,
protocol=self.protocol,
session=self.session)
if submit:
q.submit(**kwargs)
return q
def get_table_list(self):
""" returns the list of available tables from the service
ADQL query: SELECT * from TAP_SCHEMA.tables
Returns
-------
tab: Table
list of the tables with description, size and types
"""
return self.query("""select * from TAP_SCHEMA.tables where schema_name not like 'tap_schema'""")
def get_table_info(self, tablename):
return self.query("Select top 0 * from {0} ".format(tablename))
def upload_table(self, table_name, path, **kwargs):
"""
upload a table to your private local space in the archive.
Parameters
----------
table_name: str
The name to assign to this table.
path: str
The local path of the table to upload
Returns
-------
success: bool
True if the upload was successful.
"""
with open(path, "r") as fp:
url = self.tap_endpoint[:-3] + 'Upload'
self.response = self.session.post(url,
files=dict(FILE=fp),
data=dict(TABLE_NAME=table_name))
if not self.response.ok:
raise RuntimeError("Upload failed")
return True
class TAPVizieR(TAP_Service):
""" TAPVizier / CDS TAP service """
def __init__(self, *args, **kwargs):
host = 'tapvizier.u-strasbg.fr'
path = '/TAPVizieR/tap'
port = 80
TAP_Service.__init__(self, host, path, port, *args, **kwargs)
class GaiaArchive(TAP_Service):
def __init__(self, *args, **kwargs):
host = "gea.esac.esa.int"
port = 80
path = "/tap-server/tap"
kwargs['protocol'] = "https"
TAP_Service.__init__(self, host, path, port, *args, **kwargs)
class GAVO(TAP_Service):
def __init__(self, *args, **kwargs):
host = 'dc.zah.uni-heidelberg.de'
path = '/tap'
port = 80
TAP_Service.__init__(self, host, path, port, *args, **kwargs)
def resolve(objectName, full=False):
"""
Resolve the object by name using CDS
Parameters
----------
objectName: str
Name to resolve
full: bool, optional
returns more than ra, dec if set.
Returns
-------
ra: float
right ascension in degrees
dec: float
declination in degrees
plx: float
mean parallax
pmra: float, optional
pm along ra (tangent plane approx) in mas/yr
pmdec: float, optional
pm along dec in mas/yr
vel: float
radial velocity in km/s
epoch: float
epoch of the coordinates
Example:
>> resolve('M31')
(10.684708329999999, 41.268749999999997)
Requires the following module: lxml
"""
host = "cdsweb.u-strasbg.fr"
port = 80
path = "/cgi-bin/nph-sesame/-ox?{0}".format(objectName)
connection = HTTPConnection(host, port)
connection.request("GET", path)
response = connection.getresponse()
xml = response.read()
try:
tree = etree.fromstring(xml.encode('utf-8'))
except:
tree = etree.fromstring(xml)
# take the first resolver
pathRa = tree.xpath('/Sesame/Target/Resolver[1]/jradeg')
pathDec = tree.xpath('/Sesame/Target/Resolver[1]/jdedeg')
try:
ra = float(pathRa[0].text)
dec = float(pathDec[0].text)
except IndexError:
ra = dec = float('Nan')
if full:
epoch = 2000 # Default on Sesame! not in its outputs though.
pathPlx = tree.xpath('/Sesame/Target/Resolver[1]/plx/v')
pathPmRa = tree.xpath('/Sesame/Target/Resolver[1]/pm/pmRA')
pathPmDe = tree.xpath('/Sesame/Target/Resolver[1]/pm/pmDE')
try:
plx = float(pathPlx[0].text)
except IndexError:
plx = 0.
try:
pmra = float(pathPmRa[0].text)
pmde = float(pathPmDe[0].text)
except IndexError:
pmra = pmde = float('NaN')
pathVel = tree.xpath('/Sesame/Target/Resolver[1]/Vel/v')
try:
vel = float(pathVel[0].text)
except IndexError:
vel = float('NaN')
return ra,dec, plx, pmra, pmde, vel, epoch
else:
return ra, dec
class QueryStr(object):
""" A Query string that also shows well in notebook mode"""
def __init__(self, adql, *args, **kwargs):
verbose = kwargs.pop('verbose', True)
self.text = adql
self._parser = 'https://sqlformat.org/api/v1/format'
self._pars = {'sql': adql, 'reindent': 0, 'keyword_case': 'upper'}
self.parse_sql(**kwargs)
if verbose:
try:
display(self)
except:
print(self)
def parse_sql(self, **kwargs):
self._pars.update(**kwargs)
res = requests.post(self._parser, self._pars)
self.text = json.loads(res.text)['result']
return self
def __repr__(self):
return self.text
def __str__(self):
return self.text
def _repr_markdown_(self):
try:
return Markdown("""*ADQL query*\n```mysql\n{0:s}\n```""".format(self.text))._repr_markdown_()
except:
pass
class timeit(object):
""" Time a block of code of function.
Works as a context manager or decorator.
"""
def __init__(self, func=None):
self.func = func
self.text = ''
def __str__(self):
return "*Execution time*: {0}".format(self.text)
def _repr_markdown_(self):
try:
return Markdown("*Execution time*: {0}".format(self.text))._repr_markdown_()
except:
pass
def __call__(self, *args, **kwargs):
if self.func is None:
return
with timeit():
result = self.func(*args, **kwargs)
return result
@classmethod
def _pretty_print_time(cls, t):
units = [u"s", u"ms",u'us',"ns"]
scaling = [1, 1e3, 1e6, 1e9]
if t > 0.0 and t < 1000.0:
order = min(-int(math.floor(math.log10(t)) // 3), 3)
elif t >= 1000.0:
order = 0
else:
order = 3
return "%.3g %s" % (t * scaling[order], units[order])
def __enter__(self):
self.start = time.time()
def __exit__(self, *args, **kwargs):
self.stop = time.time()
self.text = self._pretty_print_time(self.stop - self.start)
display(self)
| {
"repo_name": "mfouesneau/tap",
"path": "tap/tap.py",
"copies": "1",
"size": "18315",
"license": "mit",
"hash": 6288282972564483000,
"line_mean": 30.5232358003,
"line_max": 140,
"alpha_frac": 0.5163527164,
"autogenerated": false,
"ratio": 4.226863604892684,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0021954519528815863,
"num_lines": 581
} |
# A short program to read the IANA registry of DNSSEC algorithm numbers found at
# http://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers-1.csv
# and print it out as a JSON object.
#
# Note that the JSON file has two primary differences from the IANA registry:
# 1. Only 3 of the 6 fields are included: 'Number','Mnemonic' and 'Description'.
# 2. Rows are removed if 'Description' is set to 'Reserved' or 'Unassigned'.
#
# Created by Dan York - dyork@lodestar2.com
# Comments, feedback and pull requests are welcome.
# Repository: https://github.com/danyork/dnssec-algs-json
#
import csv
import json
import urllib2
#f = open('dns-sec-alg-numbers-1.csv','r')
try:
f = urllib2.urlopen('http://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers-1.csv')
except:
print("Unable to connect to IANA server.")
exit()
algs = csv.DictReader(f)
print "["
for row in algs:
if row['Description'] not in ['Reserved','Unassigned']:
newrow = {k:v for k,v in row.items() if k in ['Number','Mnemonic','Description']}
print json.dumps(newrow,sort_keys=True,indent=4, separators=(',', ': ')) + ","
print "]"
| {
"repo_name": "danyork/dnssec-algs-json",
"path": "dnssec-algs-json.py",
"copies": "1",
"size": "1164",
"license": "mit",
"hash": -4174026810075199000,
"line_mean": 33.2647058824,
"line_max": 104,
"alpha_frac": 0.691580756,
"autogenerated": false,
"ratio": 3.137466307277628,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4329047063277628,
"avg_score": null,
"num_lines": null
} |
"""A short script for futher filtering the imagenet bounding boxes.
The original imagenet bounding boxes csv contains bounding boxes for images that
failed during download. This script will filter out those bounding boxes so that
the bounding boxes csv is as lightweight as possible.
"""
import sys
import os
import pandas as pd
def parse_imagenet_bb(raw_image_dir, in_bb_path, out_bb_path):
'''Return df with data about images and bounding boxes.
Data captured corresponds to xml files obtained from ImageNet.
'''
# paper says they use .66, but that creates search areas
# larger than image. So, 0.5 may be more appropriate.
max_box_frac_of_width = 0.66
max_box_frac_of_height = 0.66
images_successfully_downloaded = set(os.listdir(raw_image_dir))
bbox_df = (pd.read_csv(in_bb_path)
.assign(box_height = lambda df: df.y1 - df.y0,
box_width = lambda df: df.x1 - df.x0)
.assign(box_frac_of_height = lambda df:
df.box_height / df.height,
box_frac_of_width = lambda df:
df.box_width / df.width)
.query('filename in @images_successfully_downloaded')
.query('box_frac_of_height < @max_box_frac_of_height')
.query('box_frac_of_width < @max_box_frac_of_width'))
# Assuming the path ends in .csv, just insert a 2 in front
# of the .csv extension.
bbox_df.to_csv(out_bb_path, index=False)
if __name__ == '__main__':
raw_image_dir = sys.argv[1]
in_bb_path = sys.argv[2]
out_bb_path = sys.argv[3]
parse_imagenet_bb(raw_image_dir, in_bb_path, out_bb_path)
| {
"repo_name": "dansbecker/motion-tracking",
"path": "motion_tracker/data_setup/filter_imagenet_bb.py",
"copies": "1",
"size": "1730",
"license": "mit",
"hash": -5096026082900020000,
"line_mean": 39.2325581395,
"line_max": 81,
"alpha_frac": 0.612716763,
"autogenerated": false,
"ratio": 3.494949494949495,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4607666257949495,
"avg_score": null,
"num_lines": null
} |
# A short script that finds Fastq files and pairs them up if they are paired-end reads.
# The script creates a table of the pairs for reference and saves a list of input files in a txt file.
# File type (extension) can be easily modified.
from __future__ import division, print_function
import os
import glob
import tabulate
from tabulate import tabulate
def create_path_if_not_exists(mypath): # self explanatory
if not os.path.exists(mypath):
os.makedirs(mypath)
def find_pairs(my_input):
output_path = os.path.join(my_input, "Fastq_matchmaker")
create_path_if_not_exists(output_path)
paired_q = raw_input("Do you have paired reads in separate files? [y/n] ")
if paired_q.lower() == 'n':
print('Ok, one file per task.')
data_files = glob.glob(os.path.join(my_input, '*.fastq.gz'))
# finds any files with fastq.gz extension in folder
elif paired_q.lower() == 'y':
print ('Ok, looking for read mates. Mates must be named *_1.fastq.gz and *_2.fastq.gz for pairing.')
pairs = []
full_path = []
easy_read = []
for forward_file in glob.glob(os.path.join(my_input, '*_1.fastq.gz')):
forward_path, forward_name = forward_file.rsplit("/", 1)
sample_id, ext = forward_name.rsplit("_", 1)
reverse_name = sample_id + '_2.fastq.gz'
if os.path.isfile(reverse_name) is True:
pairs.append((forward_name, reverse_name))
full_path.append((forward_file, os.path.join(forward_path+"/"+reverse_name)))
for index, item in enumerate(pairs, start=1):
easy_read.append((index, item))
table = tabulate(easy_read, headers=["#", "Pair"], tablefmt="grid")
print (table)
mates_q = raw_input("Are these pairings correct? [y/n] ")
if mates_q.lower() != "y":
print("Run aborted. Double check file names.")
return
else:
print ("Ok saving table to Matchmaker folder")
filename = os.path.join(output_path, 'table_pairs.txt')
f = open(filename, 'w')
f.write(table)
f.close()
# correct delimiters for the cluster
data_files = []
for i in range(len(full_path)):
data_files.append(str.join(' ', full_path[i]))
else:
print("Run aborted.")
return
task_count = len(data_files)
assert task_count > 0, "Could not find any fastq files in folder %s" % my_input
list_index=os.path.join(output_path,'read_files.txt')
f=open(list_index,'w')
f.write(str(data_files))
f.close()
print ("All done! Files are located in %s" %output_path)
# get path and run!
input_path = raw_input("Enter the path to your file directory:")
find_pairs(input_path) | {
"repo_name": "Joannacodes/RNA-Seq-pipeline-SGE-cluster",
"path": "matchmaker.py",
"copies": "2",
"size": "2817",
"license": "apache-2.0",
"hash": 1730982253219348200,
"line_mean": 32.9518072289,
"line_max": 108,
"alpha_frac": 0.607028754,
"autogenerated": false,
"ratio": 3.534504391468005,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.004142072457170081,
"num_lines": 83
} |
""" a short script with data structures from pandas"""
from numpy import loadtxt
from matplotlib.pyplot import show
from pandas import *
ysec=loadtxt('../csp_sn/sec_max_files/y_sec_max_csp.dat', dtype='string')
jsec=loadtxt('../csp_sn/sec_max_files/j_sec_max_csp.dat', dtype='string') #loads files with two different sets of arrays in this example
#the j-band has fewer measurements than the y
d={} #define two empty dictonaries to store the parameter values in
d1={}
for i in jsec:
d[i[0]]=float(i[1])
for j in ysec:
d1[j[0]]=float(j[1]) #makes python dictionaries out of the files
s1=Series(ysec[:,1], index=ysec[:,0], dtype='float32') #define a pandas series with indices given by the supernova name
s=Series(jsec[:,1], index=jsec[:,0], dtype='float32') # same as above in j=band
d2={'y': d1, 'j':d} # a dictionary with two columns for j and y
df=DataFrame(d2, columns=['j', 'y']) #cast dictionary as dataframe, automatically assigns Nan's for no measurement
#df['flag']=df['j']>0
df['dif']=df['j']-df['y'] #append column of differences between the two values
df.plot(kind='bar') #plots the values in the dictionary as a bar graph with the differences as well. Useful to visualise a comparison between the
#different filters
show() # matplotlib function to show plot
| {
"repo_name": "ESO-python/ESOPythonTutorials",
"path": "notebooks/ptut.py",
"copies": "1",
"size": "1323",
"license": "bsd-3-clause",
"hash": -1647644324597226000,
"line_mean": 50.92,
"line_max": 146,
"alpha_frac": 0.6984126984,
"autogenerated": false,
"ratio": 3.0554272517321017,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.42538399501321017,
"avg_score": null,
"num_lines": null
} |
# a short sphinx extension to take care of hyperlinking in docstrings
# where a syntax of <Class> is employed.
import openlego
import pkgutil
import inspect
import re
from openlego.docs.config_params import IGNORE_LIST
# first, we will need a dict that contains full pathnames to every class.
# we construct that here, once, then use it for lookups in om_process_docstring
package = openlego
om_classes = {}
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
prefix=package.__name__ + '.',
onerror=lambda x: None):
if not ispkg:
if 'docs' not in modname:
if any(ignore in modname for ignore in IGNORE_LIST):
continue
module = importer.find_module(modname).load_module(modname)
for classname, class_object in inspect.getmembers(module, inspect.isclass):
if class_object.__module__.startswith("openlego"):
om_classes[classname] = class_object.__module__ + "." + classname
def om_process_docstring(app, what, name, obj, options, lines):
"""
our process_docstring
"""
for i in range(len(lines)):
# create a regex pattern to match <linktext>
pat = r'(<.*?>)'
# find all matches of the pattern in a line
match = re.findall(pat, lines[i])
if match:
for ma in match:
# strip off the angle brackets `<>`
m = ma[1:-1]
# to get rid of bad matches in OrderedDict.set_item
if m == "==":
continue
# if there's a dot in the pattern, it's a method
# e.g. <classname.method_name>
if '.' in m:
# need to grab the class name and method name separately
split_match = m.split('.')
justclass = split_match[0] # class
justmeth = split_match[1] # method
if justclass in om_classes:
classfullpath = om_classes[justclass]
# construct a link :meth:`class.method <openmdao.core.class.method>`
link = ":meth:`" + m + " <" + classfullpath + "." + justmeth + ">`"
# replace the <link> text with the constructed line.
lines[i] = lines[i].replace(ma, link)
else:
# the class isn't in the class table!
print("WARNING: {} not found in dictionary of OpenMDAO methods".format
(justclass))
# replace instances of <class> with just class in docstring
# (strip angle brackets)
lines[i] = lines[i].replace(ma, m)
# otherwise, it's a class
else:
if m in om_classes:
classfullpath = om_classes[m]
lines[i] = lines[i].replace(ma, ":class:`~" + classfullpath + "`")
else:
# the class isn't in the class table!
print("WARNING: {} not found in dictionary of OpenMDAO classes"
.format(m))
# replace instances of <class> with class in docstring
# (strip angle brackets)
lines[i] = lines[i].replace(ma, m)
# This is the crux of the extension--connecting an internal
# Sphinx event, "autodoc-process-docstring" with our own custom function.
def setup(app):
"""
"""
app.connect('autodoc-process-docstring', om_process_docstring)
| {
"repo_name": "daniel-de-vries/OpenLEGO",
"path": "openlego/docs/_exts/link_class_from_docstring.py",
"copies": "1",
"size": "3793",
"license": "apache-2.0",
"hash": -6623402278860964000,
"line_mean": 45.256097561,
"line_max": 94,
"alpha_frac": 0.5138412866,
"autogenerated": false,
"ratio": 4.625609756097561,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0012322906995042458,
"num_lines": 82
} |
"""A shot in MPF."""
from mpf.core.device_monitor import DeviceMonitor
from mpf.core.enable_disable_mixin import EnableDisableMixin
import mpf.core.delays
from mpf.core.events import event_handler
from mpf.core.mode import Mode
from mpf.core.mode_device import ModeDevice
from mpf.core.player import Player
@DeviceMonitor("state", "state_name")
class Shot(EnableDisableMixin, ModeDevice):
"""A device which represents a generic shot."""
config_section = 'shots'
collection = 'shots'
class_label = 'shot'
monitor_enabled = False
"""Class attribute which specifies whether any monitors have been registered
to track shots.
"""
__slots__ = ["delay", "active_sequences", "active_delays", "running_show", "_handlers"]
def __init__(self, machine, name):
"""Initialise shot."""
# If this device is setup in a machine-wide config, make sure it has
# a default enable event.
super(Shot, self).__init__(machine, name)
self.delay = mpf.core.delays.DelayManager(self.machine)
self.active_sequences = list()
"""List of tuples: (id, current_position_index, next_switch)"""
self.active_delays = set()
self.running_show = None
self._handlers = []
async def _initialize(self) -> None:
"""Register playfield active handlers."""
await super()._initialize()
for switch in self.config['switches'] + list(self.config['delay_switch'].keys()):
# mark the playfield active no matter what
switch.add_handler(self._mark_active)
def _mark_active(self, **kwargs):
"""Mark playfield active."""
del kwargs
if self.config['mark_playfield_active']:
self.config['playfield'].mark_playfield_active_from_device_action()
def device_loaded_in_mode(self, mode: Mode, player: Player):
"""Add device to a mode that was already started.
Automatically enables the shot and calls the the method
that's usually called when a player's turn starts since that was missed
since the mode started after that.
"""
super().device_loaded_in_mode(mode, player)
self._update_show()
def validate_and_parse_config(self, config: dict, is_mode_config: bool, debug_prefix: str = None):
"""Validate and parse shot config."""
config = super().validate_and_parse_config(config, is_mode_config, debug_prefix)
for switch in config['switch']:
if switch not in config['switches']:
config['switches'].append(switch)
return config
def _register_switch_handlers(self):
self._handlers = []
for switch in self.config['switches']:
self._handlers.append(self.machine.events.add_handler("{}_active".format(switch.name),
self.event_hit, priority=self.mode.priority,
blocking_facility="shot"))
for switch in list(self.config['delay_switch'].keys()):
self._handlers.append(self.machine.events.add_handler("{}_active".format(switch.name),
self._delay_switch_hit,
switch_name=switch.name,
priority=self.mode.priority,
blocking_facility="shot"))
def _remove_switch_handlers(self):
self.delay.clear()
self.active_delays = set()
self.machine.events.remove_handlers_by_keys(self._handlers)
self._handlers = []
@event_handler(6)
def event_advance(self, force=False, **kwargs):
"""Handle advance control event."""
del kwargs
self.advance(force)
def advance(self, force=False) -> bool:
"""Advance a shot profile forward.
If this profile is at the last step and configured to loop, it will
roll over to the first step. If this profile is at the last step and not
configured to loop, this method has no effect.
"""
if not self.enabled and not force:
return False
if not self.player:
# no player no state
return False
profile_name = self.config['profile'].name
state = self._get_state()
self.debug_log("Advancing 1 step. Profile: %s, "
"Current State: %s", profile_name, state)
if state + 1 >= len(self.config['profile'].config['states']):
if self.config['profile'].config['loop']:
self._set_state(0)
else:
return False
else:
self.debug_log("Advancing shot by one step.")
self._set_state(state + 1)
self._update_show()
return True
def _stop_show(self):
if not self.running_show:
return
self.running_show.stop()
self.running_show = None
@property
def can_rotate(self):
"""Return if the shot can be rotated according to its profile."""
state = self.state_name
return state not in self.profile.config['state_names_to_not_rotate']
@property
def state_name(self):
"""Return current state name."""
if not self.player:
# no player no state
return "None"
return self.config['profile'].config['states'][self._get_state()]['name']
@property
def state(self):
"""Return current state index."""
return self._get_state()
@property
def profile_name(self):
"""Return profile name."""
return self.config['profile'].name
@property
def profile(self):
"""Return profile."""
return self.config['profile']
def _get_state(self):
if not self.player:
return 0
return self.player["shot_{}".format(self.name)]
def _set_state(self, state):
old = self.player["shot_{}".format(self.name)]
try:
old_name = self.state_name
except IndexError:
# In this case, the shot profile was changed and the old state index
# doesn't exist in the new profile. That's okay, but we can't include
# the old state name in our event.
old_name = "unknown"
self.player["shot_{}".format(self.name)] = state
self.notify_virtual_change("state", old, state)
self.notify_virtual_change("state_name", old_name, self.state_name)
def _get_profile_settings(self):
state = self._get_state()
return self.profile.config['states'][state]
def _update_show(self):
if not self.enabled and not self.profile.config['show_when_disabled']:
self._stop_show()
return
state = self._get_state()
state_settings = self.profile.config['states'][state]
if state_settings['show']: # there's a show specified this state
self._play_show(settings=state_settings)
elif self.profile.config['show']:
# no show for this state, but we have a profile root show
self._play_show(settings=state_settings, start_step=state + 1)
# if neither if/elif above happens, it means the current step has no
# show but the previous step had one. We stop the previous show if there is one
elif self.running_show:
self._stop_show()
def _play_show(self, settings, start_step=None):
manual_advance = settings['manual_advance']
if settings['show']:
show_name = settings['show']
if settings['manual_advance'] is None:
manual_advance = False
else:
show_name = self.profile.config['show']
if settings['manual_advance'] is None:
manual_advance = True
if settings['show_tokens'] and self.config['show_tokens']:
show_tokens = dict(settings['show_tokens'])
show_tokens.update(self.config['show_tokens'])
elif settings['show_tokens']:
show_tokens = settings['show_tokens']
elif self.config['show_tokens']:
show_tokens = self.config['show_tokens']
else:
show_tokens = {}
if show_tokens:
show_tokens = {k: v.evaluate({})
for k, v in show_tokens.items()}
priority = settings['priority'] + self.mode.priority
if not start_step:
start_step = settings['start_step']
self.debug_log("Playing show: %s. %s", show_name, settings)
show_config = self.machine.show_controller.create_show_config(
show_name, priority=priority, speed=settings.get("speed"),
loops=settings.get("loops", -1), sync_ms=settings.get("sync_ms"), manual_advance=manual_advance,
show_tokens=show_tokens, events_when_played=settings.get("events_when_played"),
events_when_stopped=settings.get("events_when_stopped"),
events_when_looped=settings.get("events_when_looped"),
events_when_paused=settings.get("events_when_paused"),
events_when_resumed=settings.get("events_when_resumed"),
events_when_advanced=settings.get("events_when_advanced"),
events_when_stepped_back=settings.get("events_when_stepped_back"),
events_when_updated=settings.get("events_when_updated"),
events_when_completed=settings.get("events_when_completed"))
self.running_show = self.machine.show_controller.replace_or_advance_show(self.running_show, show_config,
start_step)
def device_removed_from_mode(self, mode):
"""Remove this shot device.
Destroys it and removes it from the shots collection.
"""
super().device_removed_from_mode(mode)
self._remove_switch_handlers()
if self.running_show:
self.running_show.stop()
self.running_show = None
@event_handler(5)
def event_hit(self, **kwargs):
"""Handle hit control event."""
success = self.hit()
if not success:
return None
if self.profile.config['block']:
min_priority = kwargs.get("_min_priority", {"all": 0})
min_shots = min_priority.get("shot", 0)
min_priority["shot"] = self.mode.priority if self.mode.priority > min_shots else min_shots
return {"_min_priority": min_priority}
return None
def hit(self) -> bool:
"""Advance the currently-active shot profile.
Note that the shot must be enabled in order for this hit to be
processed.
Returns true if the shot was enabled or false if the hit has been ignored.
"""
if not self.enabled or not self.player:
return False
# Stop if there is an active delay but no sequence
if self.active_delays:
return False
profile_settings = self._get_profile_settings()
if not profile_settings:
return False
state = profile_settings['name']
self.debug_log("Hit! Profile: %s, State: %s",
self.profile_name, state)
if self.profile.config['advance_on_hit']:
self.debug_log("Advancing shot because advance_on_hit is True.")
advancing = self.advance()
else:
self.debug_log('Not advancing shot')
advancing = False
self._notify_monitors(self.config['profile'].name, state)
self.machine.events.post('{}_hit'.format(self.name),
profile=self.profile_name, state=state, advancing=advancing)
'''event: (name)_hit
desc: The shot called (name) was just hit.
Note that there are four events posted when a shot is hit, each
with variants of the shot name, profile, and current state,
allowing you to key in on the specific granularity you need.
args:
profile: The name of the profile that was active when hit.
state: The name of the state the profile was in when it was hit'''
self.machine.events.post('{}_{}_hit'.format(self.name, self.profile_name),
profile=self.profile_name, state=state, advancing=advancing)
'''event: (name)_(profile)_hit
desc: The shot called (name) was just hit with the profile (profile)
active.
Note that there are four events posted when a shot is hit, each
with variants of the shot name, profile, and current state,
allowing you to key in on the specific granularity you need.
Also remember that shots can have more than one active profile at a
time (typically each associated with a mode), so a single hit to this
shot might result in this event being posted multiple times with
different (profile) values.
args:
profile: The name of the profile that was active when hit.
state: The name of the state the profile was in when it was hit'''
self.machine.events.post('{}_{}_{}_hit'.format(self.name, self.profile_name, state),
profile=self.profile_name, state=state, advancing=advancing)
'''event: (name)_(profile)_(state)_hit
desc: The shot called (name) was just hit with the profile (profile)
active in the state (state).
Note that there are four events posted when a shot is hit, each
with variants of the shot name, profile, and current state,
allowing you to key in on the specific granularity you need.
Also remember that shots can have more than one active profile at a
time (typically each associated with a mode), so a single hit to this
shot might result in this event being posted multiple times with
different (profile) and (state) values.
args:
profile: The name of the profile that was active when hit.
state: The name of the state the profile was in when it was hit'''
self.machine.events.post('{}_{}_hit'.format(self.name, state),
profile=self.profile_name, state=state, advancing=advancing)
'''event: (name)_(state)_hit
desc: The shot called (name) was just hit while in the profile (state).
Note that there are four events posted when a shot is hit, each
with variants of the shot name, profile, and current state,
allowing you to key in on the specific granularity you need.
Also remember that shots can have more than one active profile at a
time (typically each associated with a mode), so a single hit to this
shot might result in this event being posted multiple times with
different (profile) and (state) values.
args:
profile: The name of the profile that was active when hit.
state: The name of the state the profile was in when it was hit'''
return True
def _notify_monitors(self, profile, state):
if Shot.monitor_enabled and "shots" in self.machine.monitors:
for callback in self.machine.monitors['shots']:
callback(name=self.name, profile=profile, state=state)
@event_handler(4)
def _delay_switch_hit(self, switch_name, **kwargs):
del kwargs
if not self.enabled:
return
self.delay.reset(name=switch_name + '_delay_timer',
ms=self.config['delay_switch']
[self.machine.switches[switch_name]],
callback=self._release_delay,
switch=switch_name)
self.active_delays.add(switch_name)
def _release_delay(self, switch):
self.active_delays.remove(switch)
def jump(self, state, force=True, force_show=False):
"""Jump to a certain state in the active shot profile.
Args:
----
state: int of the state number you want to jump to. Note that states
are zero-based, so the first state is 0.
force: if true, will jump even if the shot is disabled
force_show: if true, will update the profile show even if the jumped
state index is the same as before the jump
"""
self.debug_log("Received jump request. State: %s, Force: %s", state, force)
if not self.enabled and not force:
self.debug_log("Profile is disabled and force is False. Not jumping")
return
if not self.player:
# no player no state
return
current_state = self._get_state()
if state == current_state and not force_show:
self.debug_log("Shot is already in the jump destination state")
return
self.debug_log("Jumping to profile state '%s'", state)
self._set_state(state)
self._update_show()
@event_handler(1)
def event_reset(self, **kwargs):
"""Handle reset control event."""
del kwargs
self.reset()
def reset(self):
"""Reset the shot profile for the passed mode back to the first state (State 0) and reset all sequences."""
self.debug_log("Resetting.")
self.jump(state=0)
@event_handler(2)
def event_restart(self, **kwargs):
"""Handle restart control event."""
del kwargs
self.restart()
def restart(self):
"""Restart the shot profile by calling reset() and enable().
Automatically called when one fo the restart_events is called.
"""
self.reset()
self.enable()
def _enable(self):
super()._enable()
self._register_switch_handlers()
self._update_show()
def _disable(self):
super()._disable()
self._remove_switch_handlers()
self._update_show()
| {
"repo_name": "missionpinball/mpf",
"path": "mpf/devices/shot.py",
"copies": "1",
"size": "18161",
"license": "mit",
"hash": 1048277021424748700,
"line_mean": 36.8354166667,
"line_max": 115,
"alpha_frac": 0.590385992,
"autogenerated": false,
"ratio": 4.308659549228945,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007983920571630068,
"num_lines": 480
} |
# ashworth
# this is a script for reading the source file (in pwd) for a pdb that is already loaded, and displaying the hbonds and buried unsatisfieds contained in their respective tables (if found). Similar functionality was recently introduced into the Rosetta Pymol Plugin by Ron Jacak, and this script borrows a couple of improvements from it. I hope to keep this script as a simple standalone (it's not meant to compete with the Rosetta Pymol Plugin).
from __future__ import print_function
import re, string, gzip
from pymol import cmd, cgo
class UnsAtom:
def __init__( self, uns_info ):
info = uns_info.split()
self.resi = info[6]
self.chain = info[7]
self.atom = info[10]
def hbond(don,acc,red,green,blue):
obj = []
rad = 0.08
num_dash = 4
steps = num_dash*3+1
xyz = []
step = []
for dim in range(3):
xyz.append( don.coord[dim] )
dis = acc.coord[dim]-don.coord[dim]
step.append( dis/steps )
obj = [ cgo.LINEWIDTH, 3.0, cgo.BEGIN, cgo.LINES, cgo.COLOR, red, green, blue ]
for dash in range(num_dash): # number of dashes
for dim in range(3): xyz[dim] += 2*step[dim]
obj.append( cgo.VERTEX )
obj.extend( xyz )
for dim in range(3): xyz[dim] += step[dim]
obj.append( cgo.VERTEX )
obj.extend( xyz )
obj.append( cgo.END )
return obj
def create_hbonds( lines, name ):
model = cmd.get_model(name)
# Ron Jacak's cool monster regex, borrowed from the Rosetta Pymol Plugin
hb_re = re.compile("(?:PROT|BASE) \s*[A-Z]+ \s*\d+ \s*(\d+) ([ A-Z]) \s*([A-Z0-9]+) \s*[A-Z]+ \s*\d+ \s*(\d+) ([ A-Z]) \s*([A-Z0-9]+)\s* (-?[\d\.]*)")
hbonds = []
for line in lines:
match = hb_re.search(line)
if match == None: continue
(d_resi, d_chain, d_atom, a_resi, a_chain, a_atom, energy) = match.groups()
energy = float(energy)
if energy < -0.05: # ingores very weak "hydrogen bonds"
d_addr = '/%s//%s/%s/%s' % ( name, d_chain, d_resi, d_atom )
a_addr = '/%s//%s/%s/%s' % ( name, a_chain, a_resi, a_atom )
d_atm = model.atom[ cmd.index(d_addr)[0][1] - 1 ]
a_atm = model.atom[ cmd.index(a_addr)[0][1] - 1 ]
if energy <= -0.9: colorscale = 1.0
else: colorscale = -1 * energy + 0.1 # ratio to strong, with offset
hbonds.extend( hbond( d_atm, a_atm, colorscale, colorscale, 0.0 ) )
cmd.load_cgo( hbonds, 'hb_%s' % name )
def create_ds_uns( lines, name ):
uns = { 'uns_sc':[], 'uns_bb':[] }
for line in lines:
type = line[3:8]
if type == 'SCACC' or type == 'SCDON': uns['uns_sc'].append( UnsAtom(line) )
elif type == 'BBACC' or type == 'BBDON': uns['uns_bb'].append( UnsAtom(line) )
for type,list in list(uns.items()):
if list == []: continue
selstr = string.join( [ '/%s//%s/%s/%s' % ( name, atom.chain, atom.resi, atom.atom ) for atom in list ], ' or ' )
typename = '%s_%s' % ( type, name )
cmd.select( typename, selstr )
# copy unsatisfieds into a separate object (allows unique transparency, among other things)
for type in uns:
typename = '%s_%s' % ( type, name )
cmd.disable( typename )
obj = '%s_obj' % typename
cmd.create( obj, typename )
cmd.show( 'spheres', obj )
cmd.set( 'sphere_scale' , '0.75', obj )
cmd.set( 'sphere_transparency', '0.5', obj )
###########################
### begin main function ###
###########################
def pdb_hbonds_and_uns():
# look in object list for rosetta pdb's with source files in pwd
for name in cmd.get_names():
source = None
if os.path.exists( '%s.pdb' % name ): source = file( name + '.pdb', 'r' )
elif os.path.exists( '%s.pdb.gz' % name ): source = gzip.open( '%s.pdb.gz' % name, 'r' )
else: print('cannot find source pdb file for', name); continue
hb_lines = []; ds_lines = []
hb_start = False
for line in source:
# hbond line collection uses Ron Jacak's method, for improved generality
if line == '\n': hb_start = False
if hb_start == True: hb_lines.append(line)
if line.startswith("Loc, res, pos, pdb"): hb_start = True
if line.startswith("DS "): ds_lines.append( line )
if hb_lines == []: print('no hbond lines found for %s' % name)
else:
print('Showing Rosetta hbonds for %s...' % name)
create_hbonds( hb_lines, name )
if ds_lines == []: print('no decoystats lines found for %s' % name)
else:
print('Showing Rosetta buried unsatisfieds for %s...' % name)
create_ds_uns( ds_lines, name )
cmd.extend('pdb_hb_uns',pdb_hbonds_and_uns)
| {
"repo_name": "weitzner/Dotfiles",
"path": "pymol_scripts/pdb_hb_uns.py",
"copies": "1",
"size": "4347",
"license": "mit",
"hash": 1838870494529420500,
"line_mean": 34.0564516129,
"line_max": 447,
"alpha_frac": 0.6227283184,
"autogenerated": false,
"ratio": 2.660342717258262,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8538039768089194,
"avg_score": 0.04900625351381353,
"num_lines": 124
} |
# ashworth
# useful selection groups for protein-DNA interfaces
from pymol import cmd,util
# shortcut command for pymol's "color by chains (e. c)"
def color_by_chains():
for obj in cmd.get_names('objects'):
util.color_chains('%s and e. c' %obj)
cmd.extend('cbce',color_by_chains)
#class DNA_selections:
# def __init__(self,display=True):
def DNA_selections(display='all'):
bbatoms = 'name C2\*+C3\*+C4\*+C5\*+P+O3\*+O4\*+O5\*+O1P+O2P+H1\*+1H2\*+2H2\*+H3\*+H4\*+1H5\*+2H5\*+c2\'+c3\'+c4\'+c5\'+o3\'+o4\'+o5\'+op2+op1+h1\'+1h2\'+2h2\'+h3\'+h4\'+1h5\'+2h5\''
waters = 'n. wo6+wn7+wn6+wn4+wo4 or r. hoh'
cmd.select('DNA', 'r. g+a+c+t+gua+ade+cyt+thy+da+dc+dg+dt+5mc',enable=0)
cmd.select('notDNA','not DNA',enable=0)
cmd.select('DNAbases','DNA and not %s' % bbatoms ,enable=0)
cmd.select('DNAbb','DNA and %s' % bbatoms ,enable=0)
cmd.select('sc_base','byres notDNA w. 7 of DNAbases',enable=0)
cmd.select('sc_base','sc_base and not n. c+n+o',enable=0)
cmd.select('dna_h2o','%s w. 3.6 of DNAbases' %waters ,enable=0)
cmd.set('sphere_transparency','0.5'); cmd.color('marine','dna_h2o')
cmd.do('selectPolarProtons')
# color_by_chains()
cmd.color('gray','e. c')
cmd.select('pbb','notDNA and n. c+n+ca',enable=0)
if display != 'none':
cmd.label('n. c1\*+c1\' and DNA','\'%s%s(%s)\' % (chain,resi,resn)')
cmd.set('label_color','white')
if display == 'all':
# display things
cmd.show('sticks','DNAbases or sc_base')
cmd.show('ribbon','DNAbb')
cmd.show('cartoon','notDNA')
cmd.show('spheres','dna_h2o')
cmd.hide('everything','e. h and not polar_protons')
cmd.extend('DNAselections', DNA_selections )
cmd.extend('DNAselections_nodisplay', lambda: DNA_selections('none') )
cmd.extend('DNAselections_labelsonly', lambda: DNA_selections('labels') )
| {
"repo_name": "weitzner/Dotfiles",
"path": "pymol_scripts/DNAselections.py",
"copies": "1",
"size": "1773",
"license": "mit",
"hash": -9001088743482275000,
"line_mean": 38.4,
"line_max": 183,
"alpha_frac": 0.6520022561,
"autogenerated": false,
"ratio": 2.1915945611866503,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.33435968172866504,
"avg_score": null,
"num_lines": null
} |
# The MIT License (MIT)
#
# Copyright (c) 2018-2020 Peter Hinch
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import uasyncio as asyncio
import machine
import utime
import gc
from .asi2c import Channel
# The initiator is an I2C slave. It runs on a Pyboard. I2C uses pyb for slave
# mode, but pins are instantiated using machine.
# reset (if provided) is a means of resetting Responder in case of error: it
# is (pin, active_level, ms)
class Initiator(Channel):
t_poll = 100 # ms between Initiator polling Responder
rxbufsize = 200
def __init__(self, i2c, pin, pinack, reset=None, verbose=True,
cr_go=False, go_args=(), cr_fail=False, f_args=()):
super().__init__(i2c, pin, pinack, verbose, self.rxbufsize)
self.reset = reset
self.cr_go = cr_go
self.go_args = go_args
self.cr_fail = cr_fail
self.f_args = f_args
if reset is not None:
reset[0].init(mode=machine.Pin.OUT, value=not (reset[1]))
# Self measurement
self.nboots = 0 # No. of reboots of Responder
self.block_max = 0 # Blocking times: max
self.block_sum = 0 # Total
self.block_cnt = 0 # Count
asyncio.create_task(self._run())
def waitfor(self, val): # Wait for response for 1 sec
tim = utime.ticks_ms()
while not self.rem() == val:
if utime.ticks_diff(utime.ticks_ms(), tim) > 1000:
raise OSError
async def reboot(self):
self.close() # Leave own pin high
if self.reset is not None:
rspin, rsval, rstim = self.reset
self.verbose and print('Resetting target.')
rspin(rsval) # Pulse reset line
await asyncio.sleep_ms(rstim)
rspin(not rsval)
async def _run(self):
while True:
# If hardware link exists reboot Responder
await self.reboot()
self.txbyt = b''
self.rxbyt = b''
await self._sync()
await asyncio.sleep(1) # Ensure Responder is ready
if self.cr_go:
self.loop.create_task(self.cr_go(*self.go_args))
while True:
gc.collect()
try:
tstart = utime.ticks_us()
self._sendrx()
t = utime.ticks_diff(utime.ticks_us(), tstart)
except OSError: # Reboot remote.
break
await asyncio.sleep_ms(Initiator.t_poll)
self.block_max = max(self.block_max, t) # self measurement
self.block_cnt += 1
self.block_sum += t
self.nboots += 1
if self.cr_fail:
await self.cr_fail(*self.f_args)
if self.reset is None: # No means of recovery
raise OSError('Responder fail.')
def _send(self, d):
# CRITICAL TIMING. Trigger interrupt on responder immediately before
# send. Send must start before RX begins. Fast responders may need to
# do a short blocking wait to guarantee this.
self.own(1) # Trigger interrupt.
self.i2c.send(d) # Blocks until RX complete.
self.waitfor(1)
self.own(0)
self.waitfor(0)
# Send payload length (may be 0) then payload (if any)
def _sendrx(self, sn=bytearray(2), txnull=bytearray(2)):
siz = self.txsiz if self.cantx else txnull
if self.rxbyt:
siz[1] |= 0x80 # Hold off further received data
else:
siz[1] &= 0x7f
self._send(siz)
if self.txbyt and self.cantx:
self._send(self.txbyt)
self._txdone() # Invalidate source
# Send complete
self.waitfor(1) # Wait for responder to request send
self.own(1) # Acknowledge
self.i2c.recv(sn)
self.waitfor(0)
self.own(0)
n = sn[0] + ((sn[1] & 0x7f) << 8) # no of bytes to receive
if n > self.rxbufsize:
raise ValueError('Receive data too large for buffer.')
self.cantx = not bool(sn[1] & 0x80)
if n:
self.waitfor(1) # Wait for responder to request send
self.own(1) # Acknowledge
mv = self.rx_mv[0: n] # mv is a memoryview instance
self.i2c.recv(mv)
self.waitfor(0)
self.own(0)
self._handle_rxd(mv)
| {
"repo_name": "peterhinch/micropython-async",
"path": "v3/as_drivers/i2c/asi2c_i.py",
"copies": "1",
"size": "5556",
"license": "mit",
"hash": 3788877957544356000,
"line_mean": 38.9712230216,
"line_max": 79,
"alpha_frac": 0.601511879,
"autogenerated": false,
"ratio": 3.716387959866221,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4817899838866221,
"avg_score": null,
"num_lines": null
} |
# The MIT License (MIT)
#
# Copyright (c) 2018 Peter Hinch
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import uasyncio as asyncio
import machine
import utime
import gc
from asi2c import Channel
# The initiator is an I2C slave. It runs on a Pyboard. I2C uses pyb for slave
# mode, but pins are instantiated using machine.
# reset (if provided) is a means of resetting Responder in case of error: it
# is (pin, active_level, ms)
class Initiator(Channel):
t_poll = 100 # ms between Initiator polling Responder
rxbufsize = 200
def __init__(self, i2c, pin, pinack, reset=None, verbose=True,
cr_go=False, go_args=(), cr_fail=False, f_args=()):
super().__init__(i2c, pin, pinack, verbose, self.rxbufsize)
self.reset = reset
self.cr_go = cr_go
self.go_args = go_args
self.cr_fail = cr_fail
self.f_args = f_args
if reset is not None:
reset[0].init(mode=machine.Pin.OUT, value=not (reset[1]))
# Self measurement
self.nboots = 0 # No. of reboots of Responder
self.block_max = 0 # Blocking times: max
self.block_sum = 0 # Total
self.block_cnt = 0 # Count
self.loop = asyncio.get_event_loop()
self.loop.create_task(self._run())
def waitfor(self, val): # Wait for response for 1 sec
tim = utime.ticks_ms()
while not self.rem() == val:
if utime.ticks_diff(utime.ticks_ms(), tim) > 1000:
raise OSError
async def reboot(self):
self.close() # Leave own pin high
if self.reset is not None:
rspin, rsval, rstim = self.reset
self.verbose and print('Resetting target.')
rspin(rsval) # Pulse reset line
await asyncio.sleep_ms(rstim)
rspin(not rsval)
async def _run(self):
while True:
# If hardware link exists reboot Responder
await self.reboot()
self.txbyt = b''
self.rxbyt = b''
await self._sync()
await asyncio.sleep(1) # Ensure Responder is ready
if self.cr_go:
self.loop.create_task(self.cr_go(*self.go_args))
while True:
gc.collect()
try:
tstart = utime.ticks_us()
self._sendrx()
t = utime.ticks_diff(utime.ticks_us(), tstart)
except OSError:
break
await asyncio.sleep_ms(Initiator.t_poll)
self.block_max = max(self.block_max, t) # self measurement
self.block_cnt += 1
self.block_sum += t
self.nboots += 1
if self.cr_fail:
await self.cr_fail(*self.f_args)
if self.reset is None: # No means of recovery
raise OSError('Responder fail.')
# Send payload length (may be 0) then payload (if any)
def _sendrx(self, sn=bytearray(2), txnull=bytearray(2)):
siz = self.txsiz if self.cantx else txnull
if self.rxbyt:
siz[1] |= 0x80 # Hold off further received data
else:
siz[1] &= 0x7f
# CRITICAL TIMING. Trigger interrupt on responder immediately before
# send. Send must start before RX begins. Fast responders may need to
# do a short blocking wait to guarantee this.
self.own(1) # Trigger interrupt.
self.i2c.send(siz) # Blocks until RX complete.
self.waitfor(1)
self.own(0)
self.waitfor(0)
if self.txbyt and self.cantx:
self.own(1)
self.i2c.send(self.txbyt)
self.waitfor(1)
self.own(0)
self.waitfor(0)
self._txdone() # Invalidate source
# Send complete
self.waitfor(1) # Wait for responder to request send
self.own(1) # Acknowledge
self.i2c.recv(sn)
self.waitfor(0)
self.own(0)
n = sn[0] + ((sn[1] & 0x7f) << 8) # no of bytes to receive
if n > self.rxbufsize:
raise ValueError('Receive data too large for buffer.')
self.cantx = not bool(sn[1] & 0x80)
if n:
self.waitfor(1) # Wait for responder to request send
# print('setting up receive', n,' bytes')
self.own(1) # Acknowledge
mv = memoryview(self.rx_mv[0: n])
self.i2c.recv(mv)
self.waitfor(0)
self.own(0)
self._handle_rxd(mv)
| {
"repo_name": "peterhinch/micropython-async",
"path": "v2/i2c/asi2c_i.py",
"copies": "1",
"size": "5636",
"license": "mit",
"hash": 3349796380270936000,
"line_mean": 38.6901408451,
"line_max": 79,
"alpha_frac": 0.5963449255,
"autogenerated": false,
"ratio": 3.7275132275132274,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48238581530132274,
"avg_score": null,
"num_lines": null
} |
# The MIT License (MIT)
#
# Copyright (c) 2018-2020 Peter Hinch
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import uasyncio as asyncio
import machine
import utime
from micropython import const
import io
_MP_STREAM_POLL_RD = const(1)
_MP_STREAM_POLL_WR = const(4)
_MP_STREAM_POLL = const(3)
_MP_STREAM_ERROR = const(-1)
# Delay compensates for short Responder interrupt latency. Must be >= max delay
# between Initiator setting a pin and initiating an I2C transfer: ensure
# Initiator sets up first.
_DELAY = const(20) # μs
# Base class provides user interface and send/receive object buffers
class Channel(io.IOBase):
def __init__(self, i2c, own, rem, verbose, rxbufsize):
self.rxbufsize = rxbufsize
self.verbose = verbose
self.synchronised = False
# Hardware
self.i2c = i2c
self.own = own
self.rem = rem
own.init(mode=machine.Pin.OUT, value=1)
rem.init(mode=machine.Pin.IN, pull=machine.Pin.PULL_UP)
# I/O
self.txbyt = b'' # Data to send
self.txsiz = bytearray(2) # Size of .txbyt encoded as 2 bytes
self.rxbyt = b''
self.rxbuf = bytearray(rxbufsize)
self.rx_mv = memoryview(self.rxbuf)
self.cantx = True # Remote can accept data
async def _sync(self):
self.verbose and print('Synchronising')
self.own(0)
while self.rem():
await asyncio.sleep_ms(100)
# Both pins are now low
await asyncio.sleep(0)
self.verbose and print('Synchronised')
self.synchronised = True
def waitfor(self, val): # Initiator overrides
while not self.rem() == val:
pass
# Get incoming bytes instance from memoryview.
def _handle_rxd(self, msg):
self.rxbyt = bytes(msg)
def _txdone(self):
self.txbyt = b''
self.txsiz[0] = 0
self.txsiz[1] = 0
# Stream interface
def ioctl(self, req, arg):
ret = _MP_STREAM_ERROR
if req == _MP_STREAM_POLL:
ret = 0
if self.synchronised:
if arg & _MP_STREAM_POLL_RD:
if self.rxbyt:
ret |= _MP_STREAM_POLL_RD
if arg & _MP_STREAM_POLL_WR:
if (not self.txbyt) and self.cantx:
ret |= _MP_STREAM_POLL_WR
return ret
def readline(self):
n = self.rxbyt.find(b'\n')
if n == -1:
t = self.rxbyt[:]
self.rxbyt = b''
else:
t = self.rxbyt[: n + 1]
self.rxbyt = self.rxbyt[n + 1:]
return t.decode()
def read(self, n):
t = self.rxbyt[:n]
self.rxbyt = self.rxbyt[n:]
return t.decode()
# Set .txbyt to the required data. Return its size. So awrite returns
# with transmission occurring in tha background.
# uasyncio V3: Stream.drain() calls write with buf being a memoryview
# and no off or sz args.
def write(self, buf):
if self.synchronised:
if self.txbyt: # Initial call from awrite
return 0 # Waiting for existing data to go out
l = len(buf)
self.txbyt = buf
self.txsiz[0] = l & 0xff
self.txsiz[1] = l >> 8
return l
return 0
# User interface
# Wait for sync
async def ready(self):
while not self.synchronised:
await asyncio.sleep_ms(100)
# Leave pin high in case we run again
def close(self):
self.own(1)
# Responder is I2C master. It is cross-platform and uses machine.
# It does not handle errors: if I2C fails it dies and awaits reset by initiator.
# send_recv is triggered by Interrupt from Initiator.
class Responder(Channel):
addr = 0x12
rxbufsize = 200
def __init__(self, i2c, pin, pinack, verbose=True):
super().__init__(i2c, pinack, pin, verbose, self.rxbufsize)
loop = asyncio.get_event_loop()
loop.create_task(self._run())
async def _run(self):
await self._sync() # own pin ->0, wait for remote pin == 0
self.rem.irq(handler=self._handler, trigger=machine.Pin.IRQ_RISING)
# Request was received: immediately read payload size, then payload
# On Pyboard blocks for 380μs to 1.2ms for small amounts of data
def _handler(self, _, sn=bytearray(2), txnull=bytearray(2)):
addr = Responder.addr
self.rem.irq(handler=None)
utime.sleep_us(_DELAY) # Ensure Initiator has set up to write.
self.i2c.readfrom_into(addr, sn)
self.own(1)
self.waitfor(0)
self.own(0)
n = sn[0] + ((sn[1] & 0x7f) << 8) # no of bytes to receive
if n > self.rxbufsize:
raise ValueError('Receive data too large for buffer.')
self.cantx = not bool(sn[1] & 0x80) # Can Initiator accept a payload?
if n:
self.waitfor(1)
utime.sleep_us(_DELAY)
mv = memoryview(self.rx_mv[0: n]) # allocates
self.i2c.readfrom_into(addr, mv)
self.own(1)
self.waitfor(0)
self.own(0)
self._handle_rxd(mv)
self.own(1) # Request to send
self.waitfor(1)
utime.sleep_us(_DELAY)
dtx = self.txbyt != b'' and self.cantx # Data to send
siz = self.txsiz if dtx else txnull
if self.rxbyt:
siz[1] |= 0x80 # Hold off Initiator TX
else:
siz[1] &= 0x7f
self.i2c.writeto(addr, siz) # Was getting ENODEV occasionally on Pyboard
self.own(0)
self.waitfor(0)
if dtx:
self.own(1)
self.waitfor(1)
utime.sleep_us(_DELAY)
self.i2c.writeto(addr, self.txbyt)
self.own(0)
self.waitfor(0)
self._txdone() # Invalidate source
self.rem.irq(handler=self._handler, trigger=machine.Pin.IRQ_RISING)
| {
"repo_name": "peterhinch/micropython-async",
"path": "v3/as_drivers/i2c/asi2c.py",
"copies": "1",
"size": "7094",
"license": "mit",
"hash": 254055653663777920,
"line_mean": 33.9359605911,
"line_max": 81,
"alpha_frac": 0.6061759729,
"autogenerated": false,
"ratio": 3.5230998509687033,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9627686148968122,
"avg_score": 0.0003179349801160847,
"num_lines": 203
} |
# The MIT License (MIT)
#
# Copyright (c) 2018 Peter Hinch
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import uasyncio as asyncio
import machine
import utime
from micropython import const
import io
_MP_STREAM_POLL_RD = const(1)
_MP_STREAM_POLL_WR = const(4)
_MP_STREAM_POLL = const(3)
_MP_STREAM_ERROR = const(-1)
# Delay compensates for short Responder interrupt latency. Must be >= max delay
# between Initiator setting a pin and initiating an I2C transfer: ensure
# Initiator sets up first.
_DELAY = const(20) # μs
# Base class provides user interface and send/receive object buffers
class Channel(io.IOBase):
def __init__(self, i2c, own, rem, verbose, rxbufsize):
self.rxbufsize = rxbufsize
self.verbose = verbose
self.synchronised = False
# Hardware
self.i2c = i2c
self.own = own
self.rem = rem
own.init(mode=machine.Pin.OUT, value=1)
rem.init(mode=machine.Pin.IN, pull=machine.Pin.PULL_UP)
# I/O
self.txbyt = b'' # Data to send
self.txsiz = bytearray(2) # Size of .txbyt encoded as 2 bytes
self.rxbyt = b''
self.rxbuf = bytearray(rxbufsize)
self.rx_mv = memoryview(self.rxbuf)
self.cantx = True # Remote can accept data
async def _sync(self):
self.verbose and print('Synchronising')
self.own(0)
while self.rem():
await asyncio.sleep_ms(100)
# Both pins are now low
await asyncio.sleep(0)
self.verbose and print('Synchronised')
self.synchronised = True
def waitfor(self, val): # Initiator overrides
while not self.rem() == val:
pass
# Get incoming bytes instance from memoryview.
def _handle_rxd(self, msg):
self.rxbyt = bytes(msg)
def _txdone(self):
self.txbyt = b''
self.txsiz[0] = 0
self.txsiz[1] = 0
# Stream interface
def ioctl(self, req, arg):
ret = _MP_STREAM_ERROR
if req == _MP_STREAM_POLL:
ret = 0
if self.synchronised:
if arg & _MP_STREAM_POLL_RD:
if self.rxbyt:
ret |= _MP_STREAM_POLL_RD
if arg & _MP_STREAM_POLL_WR:
if (not self.txbyt) and self.cantx:
ret |= _MP_STREAM_POLL_WR
return ret
def readline(self):
n = self.rxbyt.find(b'\n')
if n == -1:
t = self.rxbyt[:]
self.rxbyt = b''
else:
t = self.rxbyt[: n + 1]
self.rxbyt = self.rxbyt[n + 1:]
return t.decode()
def read(self, n):
t = self.rxbyt[:n]
self.rxbyt = self.rxbyt[n:]
return t.decode()
# Set .txbyt to the required data. Return its size. So awrite returns
# with transmission occurring in tha background.
def write(self, buf, off, sz):
if self.synchronised:
if self.txbyt: # Initial call from awrite
return 0 # Waiting for existing data to go out
# If awrite is called without off or sz args, avoid allocation
if off == 0 and sz == len(buf):
d = buf
else:
d = buf[off: off + sz]
d = d.encode()
l = len(d)
self.txbyt = d
self.txsiz[0] = l & 0xff
self.txsiz[1] = l >> 8
return l
return 0
# User interface
# Wait for sync
async def ready(self):
while not self.synchronised:
await asyncio.sleep_ms(100)
# Leave pin high in case we run again
def close(self):
self.own(1)
# Responder is I2C master. It is cross-platform and uses machine.
# It does not handle errors: if I2C fails it dies and awaits reset by initiator.
# send_recv is triggered by Interrupt from Initiator.
class Responder(Channel):
addr = 0x12
rxbufsize = 200
def __init__(self, i2c, pin, pinack, verbose=True):
super().__init__(i2c, pinack, pin, verbose, self.rxbufsize)
loop = asyncio.get_event_loop()
loop.create_task(self._run())
async def _run(self):
await self._sync() # own pin ->0, wait for remote pin == 0
self.rem.irq(handler=self._handler, trigger=machine.Pin.IRQ_RISING)
# Request was received: immediately read payload size, then payload
# On Pyboard blocks for 380μs to 1.2ms for small amounts of data
def _handler(self, _, sn=bytearray(2), txnull=bytearray(2)):
addr = Responder.addr
self.rem.irq(handler=None, trigger=machine.Pin.IRQ_RISING)
utime.sleep_us(_DELAY) # Ensure Initiator has set up to write.
self.i2c.readfrom_into(addr, sn)
self.own(1)
self.waitfor(0)
self.own(0)
n = sn[0] + ((sn[1] & 0x7f) << 8) # no of bytes to receive
if n > self.rxbufsize:
raise ValueError('Receive data too large for buffer.')
self.cantx = not bool(sn[1] & 0x80) # Can Initiator accept a payload?
if n:
self.waitfor(1)
utime.sleep_us(_DELAY)
mv = memoryview(self.rx_mv[0: n]) # allocates
self.i2c.readfrom_into(addr, mv)
self.own(1)
self.waitfor(0)
self.own(0)
self._handle_rxd(mv)
self.own(1) # Request to send
self.waitfor(1)
utime.sleep_us(_DELAY)
dtx = self.txbyt != b'' and self.cantx # Data to send
siz = self.txsiz if dtx else txnull
if self.rxbyt:
siz[1] |= 0x80 # Hold off Initiator TX
else:
siz[1] &= 0x7f
self.i2c.writeto(addr, siz) # Was getting ENODEV occasionally on Pyboard
self.own(0)
self.waitfor(0)
if dtx:
self.own(1)
self.waitfor(1)
utime.sleep_us(_DELAY)
self.i2c.writeto(addr, self.txbyt)
self.own(0)
self.waitfor(0)
self._txdone() # Invalidate source
self.rem.irq(handler=self._handler, trigger=machine.Pin.IRQ_RISING)
| {
"repo_name": "peterhinch/micropython-async",
"path": "v2/i2c/asi2c.py",
"copies": "1",
"size": "7180",
"license": "mit",
"hash": 5932878666760429000,
"line_mean": 33.8446601942,
"line_max": 81,
"alpha_frac": 0.5977988298,
"autogenerated": false,
"ratio": 3.535960591133005,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9632108472830259,
"avg_score": 0.0003301896205491767,
"num_lines": 206
} |
# Asia Bayes Net
# Contact: Jacob Schreiber
# jmschr@cs.washington.edu
'''
The Asia Bayesian Network. See a description here:
http://www.norsys.com/tutorials/netica/secA/tut_A1.htm
'''
from pomegranate import *
# Create the distributions
asia = DiscreteDistribution({ 'True' : 0.5, 'False' : 0.5 })
tuberculosis = ConditionalDiscreteDistribution({
'True' : DiscreteDistribution({ 'True' : 0.2, 'False' : 0.80 }),
'False' : DiscreteDistribution({ 'True' : 0.01, 'False' : 0.99 })
}, [asia])
smoking = DiscreteDistribution({ 'True' : 0.5, 'False' : 0.5 })
lung = ConditionalDiscreteDistribution({
'True' : DiscreteDistribution({ 'True' : 0.75, 'False' : 0.25 }),
'False' : DiscreteDistribution({ 'True' : 0.02, 'False' : 0.98 })
}, [smoking] )
bronchitis = ConditionalDiscreteDistribution({
'True' : DiscreteDistribution({ 'True' : 0.92, 'False' : 0.08 }),
'False' : DiscreteDistribution({ 'True' : 0.03, 'False' : 0.97})
}, [smoking] )
tuberculosis_or_cancer = ConditionalDiscreteDistribution({
'True' : { 'True' : DiscreteDistribution({ 'True' : 1.0, 'False' : 0.0 }),
'False' : DiscreteDistribution({ 'True' : 1.0, 'False' : 0.0 }),
},
'False' : { 'True' : DiscreteDistribution({ 'True' : 1.0, 'False' : 0.0 }),
'False' : DiscreteDistribution({ 'True' : 0.0, 'False' : 1.0 })
}
}, [tuberculosis, lung] )
xray = ConditionalDiscreteDistribution({
'True' : DiscreteDistribution({ 'True' : .885, 'False' : .115 }),
'False' : DiscreteDistribution({ 'True' : 0.04, 'False' : 0.96 })
}, [tuberculosis_or_cancer] )
dyspnea = ConditionalDiscreteDistribution({
'True' : { 'True' : DiscreteDistribution({ 'True' : 0.96, 'False' : 0.04 }),
'False' : DiscreteDistribution({ 'True' : 0.89, 'False' : 0.11 })
},
'False' : { 'True' : DiscreteDistribution({ 'True' : 0.82, 'False' : 0.18 }),
'False' : DiscreteDistribution({ 'True' : 0.4, 'False' : 0.6 })
}
}, [tuberculosis_or_cancer, bronchitis])
# Make the states. Note the name can be different than the name of the state
# can be different than the name of the distribution
s0 = State( asia, name="asia" )
s1 = State( tuberculosis, name="tuberculosis" )
s2 = State( smoking, name="smoker" )
s3 = State( lung, name="cancer" )
s4 = State( bronchitis, name="bronchitis" )
s5 = State( tuberculosis_or_cancer, name="TvC" )
s6 = State( xray, name="xray" )
s7 = State( dyspnea, name='dyspnea' )
# Create the Bayesian network
network = BayesianNetwork( "asia" )
network.add_nodes([ s0, s1, s2, s3, s4, s5, s6, s7 ])
network.add_edge( s0, s1 )
network.add_edge( s1, s5 )
network.add_edge( s2, s3 )
network.add_edge( s2, s4 )
network.add_edge( s3, s5 )
network.add_edge( s5, s6 )
network.add_edge( s5, s7 )
network.add_edge( s4, s7 )
network.bake()
print "Has tuberculosis, is not a smoker, 80-20 chance he has bronchitis"
observations = { 'tuberculosis' : 'True', 'smoker' : 'False',
'bronchitis' : DiscreteDistribution({ 'True' : 0.8, 'False' : 0.2 }) }
beliefs = map( str, network.forward_backward( observations ) )
print "\n".join( "{}\t\t{}".format( state.name, belief ) for state, belief in zip( network.states, beliefs ) ) | {
"repo_name": "Geoion/pomegranate",
"path": "examples/bayesnet_asia.py",
"copies": "1",
"size": "3156",
"license": "mit",
"hash": 7049957044282259000,
"line_mean": 38.4625,
"line_max": 110,
"alpha_frac": 0.6422686946,
"autogenerated": false,
"ratio": 2.5805396565821748,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.37228083511821747,
"avg_score": null,
"num_lines": null
} |
""" ASI Data Timeseries """
import datetime
from io import BytesIO
import psycopg2.extras
import pytz
import numpy as np
import matplotlib.dates as mdates
from paste.request import parse_formvars
from pyiem.plot.use_agg import plt
from pyiem.network import Table as NetworkTable
from pyiem.util import get_dbconn
def application(environ, start_response):
"""Go Main Go"""
nt = NetworkTable("ISUASI")
form = parse_formvars(environ)
if (
"syear" in form
and "eyear" in form
and "smonth" in form
and "emonth" in form
and "sday" in form
and "eday" in form
and "shour" in form
and "ehour" in form
):
sts = datetime.datetime(
int(form["syear"].value),
int(form["smonth"].value),
int(form["sday"].value),
int(form["shour"].value),
0,
)
ets = datetime.datetime(
int(form["eyear"].value),
int(form["emonth"].value),
int(form["eday"].value),
int(form["ehour"].value),
0,
)
else:
sts = datetime.datetime(2012, 12, 1)
ets = datetime.datetime(2012, 12, 3)
station = form.getvalue("station", "ISU4003")
if station not in nt.sts:
start_response("200 OK", [("Content-type", "text/plain")])
return [b"ERROR"]
pgconn = get_dbconn("other")
icursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor)
sql = """
SELECT * from asi_data WHERE
station = '%s' and valid BETWEEN '%s' and '%s' ORDER by valid ASC
""" % (
station,
sts.strftime("%Y-%m-%d %H:%M"),
ets.strftime("%Y-%m-%d %H:%M"),
)
icursor.execute(sql)
data = {}
for i in range(1, 13):
data["ch%savg" % (i,)] = []
valid = []
for row in icursor:
for i in range(1, 13):
data["ch%savg" % (i,)].append(row["ch%savg" % (i,)])
valid.append(row["valid"])
for i in range(1, 13):
data["ch%savg" % (i,)] = np.array(data["ch%savg" % (i,)])
if len(valid) < 3:
(_fig, ax) = plt.subplots(1, 1)
ax.text(0.5, 0.5, "Sorry, no data found!", ha="center")
start_response("200 OK", [("Content-Type", "image/png")])
io = BytesIO()
plt.savefig(io, format="png")
io.seek(0)
return [io.read()]
(_fig, ax) = plt.subplots(2, 1, sharex=True)
ax[0].grid(True)
ax[0].plot(
valid, data["ch1avg"], linewidth=2, color="r", zorder=2, label="48.5m"
)
ax[0].plot(
valid,
data["ch3avg"],
linewidth=2,
color="purple",
zorder=2,
label="32m",
)
ax[0].plot(
valid,
data["ch5avg"],
linewidth=2,
color="black",
zorder=2,
label="10m",
)
ax[0].set_ylabel("Wind Speed [m/s]")
ax[0].legend(loc=(0.05, -0.15), ncol=3)
ax[0].set_xlim(min(valid), max(valid))
days = (max(valid) - min(valid)).days
central = pytz.timezone("America/Chicago")
if days >= 3:
interval = max(int(days / 7), 1)
ax[0].xaxis.set_major_locator(
mdates.DayLocator(interval=interval, tz=central)
)
ax[0].xaxis.set_major_formatter(
mdates.DateFormatter("%d %b\n%Y", tz=central)
)
else:
ax[0].xaxis.set_major_locator(
mdates.AutoDateLocator(maxticks=10, tz=central)
)
ax[0].xaxis.set_major_formatter(
mdates.DateFormatter("%-I %p\n%d %b", tz=central)
)
ax[0].set_title(
"ISUASI Station: %s Timeseries" % (nt.sts[station]["name"],)
)
ax[1].plot(valid, data["ch10avg"], color="b", label="3m")
ax[1].plot(valid, data["ch11avg"], color="r", label="48.5m")
ax[1].grid(True)
ax[1].set_ylabel("Air Temperature [C]")
ax[1].legend(loc="best")
start_response("200 OK", [("Content-Type", "image/png")])
io = BytesIO()
plt.savefig(io, format="png")
io.seek(0)
return [io.read()]
| {
"repo_name": "akrherz/iem",
"path": "htdocs/other/asi_plot.py",
"copies": "1",
"size": "4051",
"license": "mit",
"hash": -6515078913749957000,
"line_mean": 27.5281690141,
"line_max": 78,
"alpha_frac": 0.5339422365,
"autogenerated": false,
"ratio": 3.1922773837667453,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4226219620266745,
"avg_score": null,
"num_lines": null
} |
# A signal group.
class SignalGroup(object):
"""A CAN signal group. Signal groups are used to define a group of
signals within a message, e.g. to define that the signals of a
group have to be updated in common.
"""
def __init__(self,
name,
repetitions=1,
signal_names=[]):
self._name = name
self._repetitions = repetitions
self._signal_names = signal_names
@property
def name(self):
"""The signal group name as a string.
"""
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def repetitions(self):
"""The signal group repetitions.
"""
return self._repetitions
@repetitions.setter
def repetitions(self, value):
self._repetitions = value
@property
def signal_names(self):
"""The signal names in the signal group
"""
return self._signal_names
@signal_names.setter
def signal_names(self, value):
self._signal_names = value
def __repr__(self):
return "signal_group('{}', {}, {})".format(self._name,
self._repetitions,
self._signal_names)
| {
"repo_name": "eerimoq/cantools",
"path": "cantools/database/can/signal_group.py",
"copies": "1",
"size": "1336",
"license": "mit",
"hash": 6916304265494551000,
"line_mean": 22.0344827586,
"line_max": 70,
"alpha_frac": 0.5254491018,
"autogenerated": false,
"ratio": 4.655052264808362,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5680501366608363,
"avg_score": null,
"num_lines": null
} |
""" A signal/slot implementation
File: signal.py
Author: Thiago Marcos P. Santos
Author: Christopher S. Case
Author: David H. Bronke
Created: August 28, 2008
Updated: December 12, 2011
License: MIT
"""
from __future__ import print_function
import inspect
from weakref import WeakSet, WeakKeyDictionary
class Signal(object):
def __init__(self):
self._functions = WeakSet()
self._methods = WeakKeyDictionary()
def __call__(self, *args, **kargs):
# Call handler functions
for func in self._functions:
func(*args, **kargs)
# Call handler methods
for obj, funcs in self._methods.items():
for func in funcs:
func(obj, *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
if slot.__self__ not in self._methods:
self._methods[slot.__self__] = set()
self._methods[slot.__self__].add(slot.__func__)
else:
self._functions.add(slot)
def disconnect(self, slot):
if inspect.ismethod(slot):
if slot.__self__ in self._methods:
self._methods[slot.__self__].remove(slot.__func__)
else:
if slot in self._functions:
self._functions.remove(slot)
def clear(self):
self._functions.clear()
self._methods.clear()
# Sample usage:
if __name__ == '__main__':
class Model(object):
def __init__(self, value):
self.__value = value
self.changed = Signal()
def set_value(self, value):
self.__value = value
self.changed() # Emit signal
def get_value(self):
return self.__value
class View(object):
def __init__(self, model):
self.model = model
model.changed.connect(self.model_changed)
def model_changed(self):
print(" New value:", self.model.get_value())
print("Beginning Tests:")
model = Model(10)
view1 = View(model)
view2 = View(model)
view3 = View(model)
print("Setting value to 20...")
model.set_value(20)
print("Deleting a view, and setting value to 30...")
del view1
model.set_value(30)
print("Clearing all listeners, and setting value to 40...")
model.changed.clear()
model.set_value(40)
print("Testing non-member function...")
def bar():
print(" Calling Non Class Function!")
model.changed.connect(bar)
model.set_value(50)
| {
"repo_name": "ActiveState/code",
"path": "recipes/Python/577980_Improved_SignalsSlots/recipe-577980.py",
"copies": "1",
"size": "2532",
"license": "mit",
"hash": 4002879538707116000,
"line_mean": 24.32,
"line_max": 66,
"alpha_frac": 0.5683254344,
"autogenerated": false,
"ratio": 3.981132075471698,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5049457509871698,
"avg_score": null,
"num_lines": null
} |
"""A silly command line XBMC client.
Usage:
shucks [--host=HOST] [--port=PORT]
Options:
-H --host=HOST Address of the XBMC server to connect with.
-P --port=PORT Web server port on server [default: 8080].
--version Show version.
-h --help Show this screen.
"""
VERSION = "0.0.1"
import cmd2
from docopt import docopt
import json
import os
from pprint import pprint
import sys
import textwrap
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient
from shucks import namespaces
def success(message):
check = u"\u2713".encode('utf-8')
green = u"\033[0;32m%s\033[0m".encode('utf-8')
print green % (" ".join((check, message)))
def fail(message):
x = u"\u2717".encode('utf-8')
red = u"\033[0;31m%s\033[0m".encode('utf-8')
print red % (" ".join((x, message)))
# Decorator to wrap a function in try/catch
def failexc(func):
from functools import wraps
@wraps(func)
def handles_exception(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Exception, e:
fail(str(e))
return handles_exception
_width = int(os.popen("stty size", "r").read().split()[1])
TAG_WRAP = textwrap.TextWrapper(width=_width, initial_indent=" ",
subsequent_indent=" ")
PLOT_WRAP = textwrap.TextWrapper(width=_width, initial_indent=" ",
subsequent_indent=" ")
def movie_to_string(obj):
def num_to_str(num):
# Convert a number to a time string
from datetime import timedelta
duration = timedelta(seconds=float(num))
days, seconds = duration.days, duration.seconds
hours = days*24 + seconds/3600
minutes = (seconds % 3600) / 60
seconds = seconds % 60
return "%dh %dm" % (hours, minutes) + \
(" %ds" % seconds if seconds else "")
r = "\033[1;37m"
r += obj.get('title', ">> NO TITLE <<")
r += (" (%d)" % obj['year'] if 'year' in obj else '')
r += u"\033[0;32m \u22ef ID: %d" % obj['movieid']
r += "\033[0m\n"
r += " \033[1mLength:\033[0m %s\n" % num_to_str(obj['runtime'])
if obj['tagline']:
tagline = TAG_WRAP.fill(obj['tagline'])
r += "\033[1;33m" + tagline + "\033[0m\n"
if obj['plot']:
r += PLOT_WRAP.fill(obj['plot']) + "\n"
pos = float(obj.get('resume', {}).get('position', 0))
if pos:
position = num_to_str(pos)
r += " \033[0;35m> Playback position: %s\033[0m\n" % str(position)
return r
class ShucksShell(cmd2.Cmd):
def __init__(self, args):
cmd2.Cmd.__init__(self)
self.prompt = "\n\033[1;33m# \033[0m"
self.args = args
uri = ''.join(["http://", args['--host'], ":", args['--port'],
"/jsonrpc"])
rpc_client = RPCClient(
JSONRPCProtocol(),
HttpPostClientTransport(uri))
self.xbmc = rpc_client
self.input = namespaces.Input(self.xbmc)
self.gui = namespaces.GUI(self.xbmc)
self.jsonrpc = namespaces.JSONRPC(self.xbmc)
self.video_library = namespaces.VideoLibrary(self.xbmc)
self.player = namespaces.Player(self.xbmc)
# Will throw exception if it doesn't work
#self.xbmc.call("JSONRPC.Ping", [], {})
@failexc
def do_ping(self, arg=""):
"""Ping the server to see if the connection works."""
self.jsonrpc.ping()
success("Ping successful.")
@failexc
def do_clear(self, arg=""):
"""Clear the screen."""
os.system('clear')
@failexc
def do_notify(self, arg=""):
"""Shows a GUI notification. Takes two args: a title and a message."""
import shlex
args = shlex.split(arg)
if len(args) != 2:
fail("Expected two strings: title and message")
return
self.gui.notify(title=args[0], message=args[1])
success("")
@failexc
def do_movies(self, arg):
"""Alias for `list movies`"""
import subprocess
# This will page the output if it's greater than one screen. Also will
# allow colors, and search ignores case.
less = subprocess.Popen(["less", "-iRX"], stdin=subprocess.PIPE)
rv = self.do_ls("movies", output=less.stdin)
less.communicate()
less.stdin.close()
self.do_clear()
return rv
# output is the output stream to write to. We want the 'movies' command to
# have its output piped to less, so this is necessary.
@failexc
def do_ls(self, what, output=sys.stdout):
"""`ls movies`: Get a list of movies in the library."""
if not what:
fail("Need to say 'ls movies' or 'ls <whatever>'")
return
if what == "movies":
props = ["title", "year", "tagline", "resume", "runtime",
"plot"]
response = self.video_library.get_movies(
properties=props, sort={"method": "title"})
movies = response['movies']
for movie in movies:
s = movie_to_string(movie).rstrip() + "\n"
output.write(s.encode('utf-8'))
output.write("\n")
else:
fail("I only understand movies right now...")
return False
def do_info(self, arg):
"""`info movie <id>`: get movie details"""
if not arg:
fail("info on what? 'info movie #', etc.")
return False
args = arg.split()
if args[0] != "movie":
fail("I can only handle movie info at the moment")
return False
try:
mid = int(args[1])
except ValueError:
fail("Usage: list movie <id>")
return False
#props = ["title", "year", "tagline", "plot", "genre", "runtime",
#"plot"]
props = ["title", "year", "runtime", "tagline", "plot", "resume"]
info = self.video_library.get_movie_details(movieid=mid,
properties=props)
print (movie_to_string(info['moviedetails']).rstrip() +
"\n\n").encode('utf-8')
@failexc
def do_players(self, arg):
"""Get all active players."""
pprint(self.player.get_active_players())
@failexc
def do_nowplaying(self, arg=""):
"""Get information about what's currently playing.
Takes an optional arg: player type to look at (video/picture/audio)
(default: video)
"""
if arg:
playertype = arg.strip()
else:
playertype = "video"
players = self.player.get_active_players()
if not len(players):
raise Exception("No players are active")
of_type = [p for p in players if p['type'] == playertype]
if not len(of_type):
raise Exception("No active player of type '%s'" % playertype)
current = self.player.whats_playing(playerid=of_type[1]['playerid'])
pprint(current)
@failexc
def do_call(self, arg):
"""Do a manual JSONRPC call.
Takes 3 args: method, [args], {kwargs}
Arguments are parsed by just using split() on the argument string in
all, so [args] and {kwargs} need to be JSON with no whitespace.
"""
args = arg.split()
if not len(args):
fail("Usage: call <method> [args] [kwargs]")
return
elif len(args) == 1:
args = args + ["[]", "{}"]
elif len(args) == 2:
args = args + ["{}"]
elif len(args) > 3:
fail("Usage: call <method> [args] [kwargs]")
return
try:
args[1] = json.loads(args[1])
if not isinstance(args[1], list):
raise Exception
except Exception:
fail("'args' is not a valid JSON list")
return
try:
args[2] = json.loads(args[2])
if not isinstance(args[2], dict):
raise Exception
except Exception:
fail("'kwargs' is not a valid JSON dict")
return
print (u"\033[36m\u21B3 Trying method \"%s\"...\033[0m" %
args[0]).encode('utf-8')
method, args, kwargs = args
return_value = self.xbmc.call(method, args, kwargs)
print json.dumps(return_value, indent=2)
@failexc
def do_left(self, arg):
"""Navigate left in the UI."""
result = self.input.left()
success("") if (result == "OK") else fail(result)
@failexc
def do_right(self, arg):
"""Navigate right in the UI."""
result = self.input.right()
success("") if (result == "OK") else fail(result)
@failexc
def do_down(self, arg):
"""Navigate up in the UI."""
result = self.input.down()
success("") if (result == "OK") else fail(result)
@failexc
def do_up(self, arg):
"""Navigate up in the UI."""
result = self.input.up()
success("") if (result == "OK") else fail(result)
@failexc
def do_s(self, arg):
"""Select the current item in the UI."""
result = self.input.select()
success("") if (result == "OK") else fail(result)
@failexc
def do_c(self, arg):
"""Shows the context menu."""
result = self.input.menu()
success("") if (result == "OK") else fail(result)
do_menu = do_c
@failexc
def do_b(self, arg):
"""Navigate back in the UI."""
result = self.input.back()
success("") if (result == "OK") else fail(result)
do_back = do_b
def do_eof(self, arg=""):
"""End this shucks session."""
print "\nAww, shucks! Leaving so soon?"
return True
do_exit = do_eof
do_quit = do_eof
do_q = do_eof
def emptyline(self):
pass
def begin():
arguments = docopt(__doc__, version="Shucks v" + VERSION)
if not arguments['--host']:
if 'SHUCKS' not in os.environ:
print "No host given, and no environment variable named SHUCKS."
sys.exit(1)
else:
config = json.load(open(os.environ['SHUCKS'], "r"))
arguments['--host'] = config['host']
ShucksShell(arguments).cmdloop()
| {
"repo_name": "mikewadsten/shucks",
"path": "shucks/__init__.py",
"copies": "1",
"size": "10502",
"license": "mit",
"hash": 7107800028148468000,
"line_mean": 29.0057142857,
"line_max": 78,
"alpha_frac": 0.538564083,
"autogenerated": false,
"ratio": 3.7480371163454675,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4786601199345467,
"avg_score": null,
"num_lines": null
} |
"""A simple actor component.
"""
# Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
# Copyright (c) 2005, Enthought, Inc.
# License: BSD Style.
# Enthought library imports.
from traits.api import Instance, Bool, Enum
from tvtk.api import tvtk
from traits.api import DelegatesTo
from tvtk.common import is_old_pipeline
# Local imports.
from mayavi.core.component import Component
from mayavi.core.source import Source
######################################################################
# `Actor` class.
######################################################################
class Actor(Component):
# The version of this class. Used for persistence.
__version__ = 0
# The mapper.
mapper = Instance(tvtk.Mapper, record=True)
# The actor.
actor = Instance(tvtk.Actor, record=True)
# The actor's property.
property = Instance(tvtk.Property, record=True)
# FIXME: None of the texture stuff is picklable. This will NOT be
# supported till the pickling infrastructure is cleaned up and
# fixed.
# If texturing is enabled for the actor or not
enable_texture = Bool(False, desc='if texturing is enabled')
# The source of the texture's image
texture_source_object = Instance(Source)
# The actors texture
texture = Instance(tvtk.Texture, record=True)
# The texture coord generation mode.
tcoord_generator_mode = Enum('none', 'cylinder', 'sphere', 'plane',
desc='the mode for texture coord generation')
# Texture coord generator.
tcoord_generator = Instance(tvtk.Object, allow_none=True)
######################################################################
# `object` interface
######################################################################
def __get_pure_state__(self):
d = super(Actor, self).__get_pure_state__()
for attr in ('texture', 'texture_source_object',
'enable_texture', 'tcoord_generator_mode',
'tcoord_generator'):
d.pop(attr,None)
return d
######################################################################
# `Component` interface
######################################################################
def setup_pipeline(self):
"""Override this method so that it *creates* its tvtk
pipeline.
This method is invoked when the object is initialized via
`__init__`. Note that at the time this method is called, the
tvtk data pipeline will *not* yet be setup. So upstream data
will not be available. The idea is that you simply create the
basic objects and setup those parts of the pipeline not
dependent on upstream sources and filters.
"""
self.mapper = tvtk.PolyDataMapper(use_lookup_table_scalar_range=1)
self.actor = tvtk.Actor()
self.property = self.actor.property
self.texture = tvtk.Texture()
def update_pipeline(self):
"""Override this method so that it *updates* the tvtk pipeline
when data upstream is known to have changed.
This method is invoked (automatically) when the input fires a
`pipeline_changed` event.
"""
if (len(self.inputs) == 0) or \
(len(self.inputs[0].outputs) == 0):
return
self._tcoord_generator_mode_changed(self.tcoord_generator_mode)
self.render()
def update_data(self):
"""Override this method to do what is necessary when upstream
data changes.
This method is invoked (automatically) when any of the inputs
sends a `data_changed` event.
"""
# Invoke render to update any changes.
if not is_old_pipeline():
from mayavi.modules.outline import Outline
from mayavi.components.glyph import Glyph
#FIXME: A bad hack, but without these checks results in seg fault
input = self.inputs[0]
if isinstance(input, Outline) or isinstance(input, Glyph):
self.mapper.update(0)
else:
self.mapper.update()
self.render()
######################################################################
# `Actor` interface
######################################################################
def set_lut(self, lut):
"""Set the Lookup table to use."""
self.mapper.lookup_table = lut
# A hack to avoid a problem with the VRML output that seems to
# ignore the use_lookup_table_scalar_range setting
# on the mapping
self.mapper.scalar_range = lut.table_range
######################################################################
# Non-public interface.
######################################################################
def _setup_handlers(self, old, new):
if old is not None:
old.on_trait_change(self.render, remove=True)
new.on_trait_change(self.render)
def _mapper_changed(self, old, new):
# Setup the handlers.
self._setup_handlers(old, new)
# Setup the LUT.
if old is not None:
self.set_lut(old.lookup_table)
# Setup the inputs to the mapper.
if (len(self.inputs) > 0) and (len(self.inputs[0].outputs) > 0):
self.configure_connection(new, self.inputs[0])
# Setup the actor's mapper.
actor = self.actor
if actor is not None:
actor.mapper = new
self.render()
def _actor_changed(self, old, new):
# Setup the handlers.
self._setup_handlers(old, new)
# Set the mapper.
mapper = self.mapper
if mapper is not None:
new.mapper = mapper
# Set the property.
prop = self.property
if prop is not None:
new.property = prop
# Setup the `actors` trait.
self.actors = [new]
def _property_changed(self, old, new):
# Setup the handlers.
self._setup_handlers(old, new)
# Setup the actor.
actor = self.actor
if new is not actor.property:
actor.property = new
def _foreground_changed_for_scene(self, old, new):
# Change the default color for the actor.
self.property.color = new
self.render()
def _scene_changed(self, old, new):
super(Actor, self)._scene_changed(old, new)
self._foreground_changed_for_scene(None, new.foreground)
def _enable_texture_changed(self, value):
if self.texture_source_object is None :
self.actor.texture = None
return
if value:
self.actor.texture = self.texture
else:
self.actor.texture = None
def _can_object_give_image_data(self, source):
if source is None:
return False
if not isinstance(source, Source):
return False
if source.outputs[0].is_a('vtkImageData'):
return True
return False
def _change_texture_input(self):
if self._can_object_give_image_data(self.texture_source_object):
self.configure_connection(self.texture,
self.texture_source_object)
self.actor.texture = self.texture
else:
self.texture_source_object = None
def _texture_source_object_changed(self,old,new):
if old is not None :
old.on_trait_change(self._change_texture_input,
'pipeline_changed',
remove=True)
if new is not None :
new.on_trait_change(self._change_texture_input,
'pipeline_changed' )
if new is not None:
self._change_texture_input()
else:
self.actor.texture = None
self.texture.input = None
self.texture.input_connection = None
def _texture_changed(self,value):
# Setup the actor's texture.
actor = self.actor
if actor is not None and (value.input is not None
or value.input_connection is not None):
actor.texture = value
self.texture.on_trait_change(self.render)
self.render()
def _tcoord_generator_mode_changed(self, value):
inp = self.inputs
if (len(inp) == 0) or \
(len(inp[0].outputs) == 0):
return
old_tg = self.tcoord_generator
if old_tg is not None:
old_tg.on_trait_change(self.render, remove=True)
if value == 'none':
self.tcoord_generator = None
self.configure_connection(self.mapper, inp[0])
else:
tg_dict = {'cylinder': tvtk.TextureMapToCylinder,
'sphere': tvtk.TextureMapToSphere,
'plane': tvtk.TextureMapToPlane}
tg = tg_dict[value]()
self.tcoord_generator = tg
self.configure_connection(tg, inp[0])
self.configure_connection(self.mapper, inp[0])
tg = self.tcoord_generator
if tg is not None:
tg.on_trait_change(self.render)
self.render()
| {
"repo_name": "liulion/mayavi",
"path": "mayavi/components/actor.py",
"copies": "3",
"size": "9254",
"license": "bsd-3-clause",
"hash": 5900930106391347000,
"line_mean": 34.8682170543,
"line_max": 78,
"alpha_frac": 0.5420358764,
"autogenerated": false,
"ratio": 4.394112060778728,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6436147937178728,
"avg_score": null,
"num_lines": null
} |
# A simple adjacency matrix graph data structure
from difflib import SequenceMatcher as stringMatcher
class simpleTagGraph:
nodes = {}
weights = []
tagList = []
# Initialize the weights array and automatically generate and store the sequenceMatcher similarity as weights
def __init__(self, tagList):
self.weights = [[0] * len(tagList) for i in range(len(tagList))]
self.tagList = tagList
for x in range(0, len(tagList)):
self.nodes[tagList[x]] = x
for y in range(0, len(tagList)):
if x == y:
self.weights[x][y] = 0
else:
self.weights[x][y] = stringMatcher(None, tagList[x], tagList[y]).ratio()
# Returns the set of weights corresponding to a node
def getWeights(self, tagName):
return self.weights[self.nodes[tagName]]
def printNodes(self):
print self.nodes
# Prints the adjacency matrix graph
def printGraph(self):
row_format = "{:>18}" * (len(self.tagList) + 1)
print row_format.format("", *self.tagList)
for tagName, row in zip(self.tagList, self.weights):
print row_format.format(tagName +" |", *row) | {
"repo_name": "izconcept/trelloTagSync",
"path": "src/graph.py",
"copies": "1",
"size": "1220",
"license": "mit",
"hash": 289261703443435140,
"line_mean": 37.15625,
"line_max": 113,
"alpha_frac": 0.6032786885,
"autogenerated": false,
"ratio": 3.91025641025641,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.501353509875641,
"avg_score": null,
"num_lines": null
} |
# A "simple" adventure game.
class Player(object):
def __init__(self, name, place):
"""Create a player object."""
self.name = name
self.place = place
self.backpack = []
def look(self):
self.place.look()
def go_to(self, location):
"""Go to a location if it's among the exits of player's current place.
>>> sather_gate = Place('Sather Gate', 'You are at Sather Gate', [], [])
>>> gbc = Place('GBC', 'You are at Golden Bear Cafe', [], [])
>>> sather_gate.add_exits([gbc])
>>> sather_gate.locked = True
>>> gbc.add_exits([sather_gate])
>>> me = Player('player', sather_gate)
>>> me.go_to('GBC')
You are at GBC
>>> me.place is gbc
True
>>> me.place.name
'GBC'
>>> me.go_to('GBC')
Can't go to GBC from GBC.
Try looking around to see where to go.
You are at GBC
>>> me.go_to('Sather Gate')
Sather Gate is locked! Go look for a key to unlock it
You are at GBC
"""
destination_place = self.place.get_neighbor(location)
if destination_place.locked:
print(destination_place.name, 'is locked! Go look for a key to unlock it')
elif destination_place != self:
self.place = destination_place
print('You are at {}'.format(self.place.name))
def talk_to(self, person):
"""Talk to person if person is at player's current place.
>>> john = Character('John', 'Have to run for lecture!')
>>> sather_gate = Place('Sather Gate', 'You are at Sather Gate', [john], [])
>>> me = Player('player', sather_gate)
>>> me.talk_to(john)
Person has to be a string.
>>> me.talk_to('John')
John says: Have to run for lecture!
>>> me.talk_to('Albert')
Albert is not here.
"""
if type(person) != str:
print('Person has to be a string.')
elif person in self.place.characters:
print('{} says: {}'.format(person, self.place.characters[person].talk()))
else:
print('{} is not here.'.format(person))
def take(self, thing):
"""Take a thing if thing is at player's current place
>>> hotdog = Thing('Hotdog', 'A hot looking hotdog')
>>> gbc = Place('GBC', 'You are at Golden Bear Cafe', [], [hotdog])
>>> me = Player('Player', gbc)
>>> me.backpack
[]
>>> me.take(hotdog)
Thing should be a string.
>>> me.take('dog')
dog is not here.
>>> me.take('Hotdog')
Player takes the Hotdog
>>> me.take('Hotdog')
Hotdog is not here.
>>> isinstance(me.backpack[0], Thing)
True
>>> len(me.backpack)
1
"""
if type(thing) != str:
print('Thing should be a string.')
elif thing in self.place.things:
self.backpack.append(self.place.take(thing))
print('Player takes the {}'.format(thing))
else:
print('{} is not here.'.format(thing))
def check_backpack(self):
"""Print each item with its description and return a list of item names.
>>> cookie = Thing('Cookie', 'A huge cookie')
>>> donut = Thing('Donut', 'A huge donut')
>>> cupcake = Thing('Cupcake', 'A huge cupcake')
>>> gbc = Place('GBC', 'You are at Golden Bear Cafe',
... [], [cookie, donut, cupcake])
>>> me = Player('Player', gbc)
>>> me.check_backpack()
In your backpack:
there is nothing.
[]
>>> me.take('Cookie')
Player takes the Cookie
>>> me.check_backpack()
In your backpack:
Cookie - A huge cookie
['Cookie']
>>> me.take('Donut')
Player takes the Donut
>>> food = me.check_backpack()
In your backpack:
Cookie - A huge cookie
Donut - A huge donut
>>> food
['Cookie', 'Donut']
"""
print('In your backpack:')
if not self.backpack:
print(' there is nothing.')
else:
for item in self.backpack:
print(' ', item.name, '-', item.description)
return [item.name for item in self.backpack]
def unlock(self, place):
"""If player has a key, unlock a locked neighboring place.
>>> key = Key('SkeletonKey', 'A Key to unlock all doors.')
>>> gbc = Place('GBC', 'You are at Golden Bear Cafe', [], [key])
>>> fsm = Place('FSM', 'Home of the nectar of the gods', [], [])
>>> gbc.add_exits([fsm])
>>> fsm.locked = True
>>> me = Player('Player', gbc)
>>> me.unlock(fsm)
Place must be a string
>>> me.go_to('FSM')
FSM is locked! Go look for a key to unlock it
You are at GBC
>>> me.unlock(fsm)
Place must be a string
>>> me.unlock('FSM')
FSM can't be unlocked without a key!
>>> me.take('SkeletonKey')
Player takes the SkeletonKey
>>> me.unlock('FSM')
FSM is now unlocked!
>>> me.unlock('FSM')
FSM is already unlocked!
>>> me.go_to('FSM')
You are at FSM
"""
if type(place) != str:
print("Place must be a string")
return
key = None
for item in self.backpack:
if type(item) == Key:
key = item
destination_place = self.place.get_neighbor(place)
if not key:
print("{} can't be unlocked without a key!".format(place))
else:
key.use(destination_place)
def knapsack(self, max_weight, list_of_treasures):
"""Return the total value of the most valuable combination of treasures
which have a combined weight less than max_weight
>>> t1 = Treasure('Treasure 1', 'Software Engineering 2008', 5, 6)
>>> t2 = Treasure('Treasure 2', "Paul Hilfinger's First Computer", 10, 50)
>>> t3 = Treasure('Treasure 3', "John's Silly Hat", 6, 3)
>>> t4 = Treasure('Treasure 4', 'Whiteboard Marker', 4, 2)
>>> t5 = Treasure('Treasure 5', 'USB with a Linux Distro', 2, 4)
>>> treasure_list = [t1, t2, t3, t4, t5]
>>> soda = Place('Soda', 'Soda', [], [])
>>> me = Player('Player', soda)
>>> me.knapsack(10, treasure_list) # Treasures 3, 4, 5
12
>>> me.knapsack(2, treasure_list) # Treasure 4
4
>>> me.knapsack(100, treasure_list) # Treasures 1, 2, 3, 4, 5
27
"""
"*** YOUR CODE HERE ***"
if not list_of_treasures:
return 0
cur = list_of_treasures[0]
value_without = Player.knapsack(self, max_weight, list_of_treasures[1:])
if max_weight >= cur.weight:
value_with = cur.value + Player.knapsack(self, max_weight - cur.weight, list_of_treasures[1:])
if value_with > value_without:
return value_with
return value_without
class Character(object):
def __init__(self, name, message):
self.name = name
self.message = message
def talk(self):
return self.message
class Thing(object):
def __init__(self, name, description):
self.name = name
self.description = description
def use(self, place):
print("You can't use a {0} here".format(self.name))
""" Implement Key here! """
class Key(Thing):
def use(self, place):
if place.locked:
place.locked = False
print(place.name, 'is now unlocked!')
else:
print(place.name, 'is already unlocked!')
class Treasure(Thing):
def __init__(self, name, description, value, weight):
Thing.__init__(self, name, description)
self.value = value
self.weight = weight
class Place(object):
def __init__(self, name, description, characters, things):
self.name = name
self.description = description
self.characters = {character.name: character for character in characters}
self.things = {thing.name: thing for thing in things}
self.locked = False
self.exits = {} # {'name': (exit, 'description')}
def look(self):
print('You are currently at ' + self.name + '. You take a look around and see:')
print('Characters:')
if not self.characters:
print(' no one in particular')
else:
for character in self.characters:
print(' ', character)
print('Things:')
if not self.things:
print(' nothing in particular')
else:
for thing in self.things.values():
print(' ', thing.name, '-', thing.description)
self.check_exits()
def get_neighbor(self, exit):
"""
>>> sather_gate = Place('Sather Gate', 'You are at Sather Gate', [], [])
>>> gbc = Place('GBC', 'You are at Golden Bear Cafe', [], [])
>>> gbc.add_exits([sather_gate])
>>> place = gbc.get_neighbor('Sather Gate')
>>> place is sather_gate
True
>>> place = gbc.get_neighbor('FSM')
Can't go to FSM from GBC.
Try looking around to see where to go.
>>> place is gbc
True
"""
if type(exit) != str:
print('Exit has to be a string.')
return self
elif exit in self.exits:
exit_place = self.exits[exit][0]
return exit_place
else:
print("Can't go to {} from {}.".format(exit, self.name))
print("Try looking around to see where to go.")
return self
def take(self, thing):
return self.things.pop(thing)
def check_exits(self):
print('You can exit to:')
for exit in self.exits:
print(' ', exit)
def add_exits(self, places):
for place in places:
self.exits[place.name] = (place, place.description)
| {
"repo_name": "tavaresdong/courses-notes",
"path": "ucb_cs61A/lab/lab06/classes.py",
"copies": "3",
"size": "10101",
"license": "mit",
"hash": 4445780013963992000,
"line_mean": 33.2406779661,
"line_max": 106,
"alpha_frac": 0.5295515296,
"autogenerated": false,
"ratio": 3.730059084194978,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5759610613794978,
"avg_score": null,
"num_lines": null
} |
# A simple (and dirty) script to generate
# a java class from a shared program.
# This helps is statically resolving shader programs
# using LWJGL3.
import os.path
import sys
def jstringify(content):
'''Return a java string from a "normal" string '''
jstr = "\""
for ch in content:
if ch == '"':
jstr += '\\"'
elif ch == '\n':
jstr += '\\n'
else:
jstr += ch
return jstr + '\"'
def classify(package_name, class_name, shader_str):
return """
// This file is generated from `{class_name}.fs` shader program
// Please do not edit directly
package {package_name};
public class {class_name} {{
public final static String SHADER_STRING = {shader_str};
}}
""".format(**locals())
def fatal_error(explain):
print("Fatal error: {}".format(explain), file=sys.stderr)
print("Abort.")
if __name__ == "__main__":
if len(sys.argv) != 3:
fatal_error("needs at least two arguments")
package_name = sys.argv[1]
input_fname = sys.argv[2]
print("Classifying shader program '{}' in package '{}'"
.format(input_fname, package_name))
base_fname = os.path.basename(input_fname)
class_name = os.path.splitext(base_fname)[0]
output_fname = class_name + ".java"
with open(input_fname, 'r') as f:
content = f.read()
shader_str = jstringify(content)
class_src = classify(package_name, class_name, shader_str)
with open(output_fname, 'w') as f:
f.write(class_src)
print("... shader program classified in '{}'".format(output_fname))
print("Bye bye!")
| {
"repo_name": "fredokun/yaw",
"path": "src/java/yaw/engine/shader/shader_classify.py",
"copies": "1",
"size": "1619",
"license": "mit",
"hash": -2605028189028590600,
"line_mean": 22.4637681159,
"line_max": 71,
"alpha_frac": 0.6034589253,
"autogenerated": false,
"ratio": 3.5195652173913046,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9623024142691304,
"avg_score": 0,
"num_lines": 69
} |
""" A simple API wrapper for FTPing files
you should be able to this:
from ftpretty import ftpretty
f = ftpretty(host, user, pass, secure=False, timeout=10)
f.get(remote, local)
f.put(local, remote)
f.list(remote)
f.cd(remote)
f.delete(remote)
f.rename(remote_from, remote_to)
f.close()
"""
from __future__ import print_function
import datetime
from ftplib import FTP, error_perm
import os
import re
from dateutil import parser
from compat import buffer_type, file_type
try:
from ftplib import FTP_TLS
except ImportError:
FTP_TLS = None
class dotdict(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class ftpretty(object):
""" A wrapper for FTP connections """
conn = None
port = None
tmp_output = None
relative_paths = set(['.', '..'])
def __init__(self, host, user, password,
secure=False, passive=True, ftp_conn=None, **kwargs):
if 'port' in kwargs:
self.port = kwargs['port']
del kwargs['port']
if ftp_conn:
self.conn = ftp_conn
elif secure and FTP_TLS:
if self.port:
FTP_TLS.port = self.port
self.conn = FTP_TLS(host=host, user=user, passwd=password, **kwargs)
self.conn.prot_p()
else:
if self.port:
FTP.port = self.port
self.conn = FTP(host=host, user=user, passwd=password, **kwargs)
if not passive:
self.conn.set_pasv(False)
def __getattr__(self, name):
""" Pass anything we don't know about, to underlying ftp connection """
def wrapper(*args, **kwargs):
method = getattr(self.conn, name)
return method(*args, **kwargs)
return wrapper
def get(self, remote, local=None):
""" Gets the file from FTP server
local can be:
a file: opened for writing, left open
a string: path to output file
None: contents are returned
"""
if isinstance(local, file_type): # open file, leave open
local_file = local
elif local is None: # return string
local_file = buffer_type()
else: # path to file, open, write/close return None
local_file = open(local, 'wb')
self.conn.retrbinary("RETR %s" % remote, local_file.write)
if isinstance(local, file_type):
pass
elif local is None:
contents = local_file.getvalue()
local_file.close()
return contents
else:
local_file.close()
return None
def put(self, local, remote, contents=None, quiet=False):
""" Puts a local file (or contents) on to the FTP server
local can be:
a string: path to inpit file
a file: opened for reading
None: contents are pushed
"""
remote_dir = os.path.dirname(remote)
remote_file = os.path.basename(local)\
if remote.endswith('/') else os.path.basename(remote)
if contents:
# local is ignored if contents is set
local_file = buffer_type(contents)
elif isinstance(local, file_type):
local_file = local
else:
local_file = open(local, 'rb')
if remote_dir:
self.descend(remote_dir, force=True)
size = 0
try:
self.conn.storbinary('STOR %s' % remote_file, local_file)
size = self.conn.size(remote_file)
except:
if not quiet:
raise
finally:
local_file.close()
if remote_dir:
depth = len(remote_dir.split('/'))
back = "/".join(['..' for d in range(depth)])
self.conn.cwd(back)
return size
def upload_tree(self, src, dst, ignore=None):
""" Recursively upload a directory tree.
Although similar to shutil.copytree we don't follow symlinks.
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
try:
dst = dst.replace('\\', '/')
self.conn.mkd(dst)
except error_perm:
pass
errors = []
for name in names:
if name in ignored_names:
continue
src_name = os.path.join(src, name)
dst_name = os.path.join(dst, name)
try:
if os.path.islink(src_name):
pass
elif os.path.isdir(src_name):
self.upload_tree(src_name, dst_name, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
self.put(src_name, dst_name)
except Exception as why:
errors.append((src_name, dst_name, str(why)))
return dst
def put_tree(self, *args, **kwargs):
""" Alias for upload_tree """
return self.upload_tree(*args, **kwargs)
def get_tree(self, remote, local):
""" Recursively download a directory tree.
"""
remote = remote.replace('\\', '/')
for entry in self.list(remote, extra=True):
name = entry['name']
remote_path = os.path.join(remote, name)
local_path = os.path.join(local, name)
if entry.flags == 'd':
if not os.path.exists(local_path):
os.mkdir(local_path)
self.get_tree(remote_path, local_path)
elif entry.flags == '-':
self.get(remote_path, local_path)
else:
pass
def list(self, remote='.', extra=False, remove_relative_paths=False):
""" Return directory list """
if extra:
self.tmp_output = []
self.conn.dir(remote, self._collector)
directory_list = split_file_info(self.tmp_output)
else:
directory_list = self.conn.nlst(remote)
if remove_relative_paths:
return list(filter(self.is_not_relative_path, directory_list))
return directory_list
def is_not_relative_path(self, path):
if isinstance(path, dict):
return path.get('name') not in self.relative_paths
else:
return path not in self.relative_paths
def descend(self, remote, force=False):
""" Descend, possibly creating directories as needed """
remote_dirs = remote.split('/')
for directory in remote_dirs:
try:
self.conn.cwd(directory)
except Exception:
if force:
self.conn.mkd(directory)
self.conn.cwd(directory)
return self.conn.pwd()
def delete(self, remote):
""" Delete a file from server """
try:
self.conn.delete(remote)
except Exception as exc:
try:
self.conn.rmd(remote)
except:
return False
else:
return True
def cd(self, remote):
""" Change working directory on server """
try:
self.conn.cwd(remote)
except Exception:
return False
else:
return self.pwd()
def pwd(self):
""" Return the current working directory """
return self.conn.pwd()
def rename(self, remote_from, remote_to):
""" Rename a file on the server """
return self.conn.rename(remote_from, remote_to)
def mkdir(self, new_dir):
""" Create directory on the server """
return self.conn.mkd(new_dir)
def close(self):
""" End the session """
try:
self.conn.quit()
except Exception:
self.conn.close()
def _collector(self, line):
""" Helper for collecting output from dir() """
self.tmp_output.append(line)
def _get_year(date):
from dateutil.relativedelta import relativedelta
current_date = datetime.datetime.now()
parsed_date = parser.parse("%s" % date)
if current_date > parsed_date:
current = current_date
else:
current = current_date - relativedelta(years=1)
return current.strftime('%Y')
def split_file_info(fileinfo):
""" Parse sane directory output usually ls -l
Adapted from https://gist.github.com/tobiasoberrauch/2942716
"""
files = []
unix_format = re.compile(
r'^([\-dbclps])' + # Directory flag [1]
r'((?:[r-][w-][-xsStT]){3})\s+' + # Permissions [2]
r'(\d+)\s+' + # Number of items [3]
r'([a-zA-Z0-9_-]+)\s+' + # File owner [4]
r'([a-zA-Z0-9_-]+)\s+' + # File group [5]
r'(\d+)\s+' + # File size in bytes [6]
r'(\w{3}\s+\d{1,2})\s+' + # 3-char month and 1/2-char day of the month [7]
r'(\d{1,2}:\d{1,2}|\d{4})\s+' + # Time or year (need to check conditions) [+= 7]
r'(.+)$' # File/directory name [8]
)
# not exactly sure what format this, but seems windows-esque
# attempting to address issue: https://github.com/codebynumbers/ftpretty/issues/34
# can get better results with more data.
windows_format = re.compile(
r'(\d{2})-(\d{2})-(\d{2})\s+' + # month/day/2-digit year (assuming after 2000)
r'(\d{2}):(\d{2})([AP])M\s+' + # time
r'(\d+)\s+' + # file size
r'(.+)$' # filename
)
for line in fileinfo:
if unix_format.match(line):
parts = unix_format.split(line)
date = parts[7]
time = parts[8] if ':' in parts[8] else '00:00'
year = parts[8] if ':' not in parts[8] else _get_year(date)
dt_obj = parser.parse("%s %s %s" % (date, year, time))
files.append(dotdict({
'directory': parts[1],
'flags': parts[1],
'perms': parts[2],
'items': parts[3],
'owner': parts[4],
'group': parts[5],
'size': int(parts[6]),
'date': date,
'time': time,
'year': year,
'name': parts[9],
'datetime': dt_obj
}))
elif windows_format.match(line):
parts = windows_format.split(line)
hour = int(parts[4])
hour += 12 if parts[6] == 'P' else 0
hour = 0 if hour == 24 else hour
year = int(parts[3]) + 2000
dt_obj = datetime.datetime(year, int(parts[1]), int(parts[2]), hour, int(parts[5]), 0)
files.append(dotdict({
'directory': None,
'flags': None,
'perms': None,
'items': None,
'owner': None,
'group': None,
'size': int(parts[7]),
'date': "{}-{}-{}".format(*parts[1:4]),
'time': "{}:{}{}".format(*parts[4:7]),
'year': year,
'name': parts[8],
'datetime': dt_obj
}))
return files
| {
"repo_name": "codebynumbers/ftpretty",
"path": "ftpretty.py",
"copies": "1",
"size": "11530",
"license": "mit",
"hash": -1356827543225454000,
"line_mean": 31.0277777778,
"line_max": 98,
"alpha_frac": 0.5065915004,
"autogenerated": false,
"ratio": 4.057002111189303,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0013980482521870018,
"num_lines": 360
} |
"""A simple async RPC client that shows how to do load balancing."""
#-----------------------------------------------------------------------------
# Copyright (C) 2012. Brian Granger, Min Ragan-Kelley
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.BSD, distributed as part of this software.
#-----------------------------------------------------------------------------
from zpyrpc import AsyncRPCServiceProxy, JSONSerializer
from zmq.eventloop import ioloop
from zmq.utils import jsonapi
def print_result(r):
print "Got result:", r
def print_error(ename, evalue, tb):
print "Got error:", ename, evalue
print tb
if __name__ == '__main__':
# Custom serializer/deserializer functions can be passed in. The server
# side ones must match.
echo = AsyncRPCServiceProxy(serializer=JSONSerializer())
echo.connect('tcp://127.0.0.1:5555')
echo.echo(print_result, print_error, 0, "Hi there")
echo.error(print_result, print_error, 0)
# Sleep for 2.0s but timeout after 1000ms.
echo.sleep(print_result, print_error, 1000, 2.0)
math = AsyncRPCServiceProxy()
# By connecting to two instances, requests are load balanced.
math.connect('tcp://127.0.0.1:5556')
math.connect('tcp://127.0.0.1:5557')
for i in range(5):
for j in range(5):
math.add(print_result, print_error, 0, i,j)
loop = ioloop.IOLoop.instance()
loop.start()
| {
"repo_name": "ellisonbg/zpyrpc",
"path": "examples/async_client.py",
"copies": "1",
"size": "1460",
"license": "bsd-3-clause",
"hash": -6583861509778993000,
"line_mean": 35.5,
"line_max": 78,
"alpha_frac": 0.6082191781,
"autogenerated": false,
"ratio": 3.7244897959183674,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9811065058938826,
"avg_score": 0.004328783015908265,
"num_lines": 40
} |
# a simple attempt at a color matching, stack choosing card game
# joadavis Oct 20, 2016
# Another attempt at a game in one .py file
# No AI for this version, just two players taking turns
# objects - cards, buttons [draw, place, take, help], game session (to track turns)
# need to display scores and player labels
# display a "who won" message at the end
import pygame
import random
GAME_WHITE = (250, 250, 250)
GAME_BLACK = (0, 0, 0)
GAME_GREEN = (0,55,0)
GAME_SPLASH = (25, 80, 25)
class GameSession(object):
pass
class SomeButton(pygame.sprite.Sprite):
label = ""
def __init__(self, x, y):
super().__init__()
# image setup
self.image = pygame.Surface([40,20])
self.init_draw(self.image)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def init_draw(self, screen):
pygame.draw.rect(screen, GAME_BLACK, [0, 0, 50, 50])
class SplashBox(pygame.sprite.Sprite):
welcome_message = ["Welcome to Fort Collorins.","",
"This is a two player card game.",
"On your turn, either draw a new card and place it on a pile,", " or choose a pile to add to your stacks.",
"Play until there are less than 15 cards left in deck.",
"Only your three largest stacks are scored for you,", " the rest count against your score.",
"", "Click this dialog to begin." ]
rect = [0,0,1,1]
def __init__(self, x, y):
super().__init__()
print("splash init")
# image setup
self.image = pygame.Surface([400,250])
self.init_draw(self.image)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def update(self):
print("Splash")
pass
def init_draw(self, screen):
# now using sprite, so coords relative within sprite image (screen)
# upper left corner x and y then width and height (downward)
pygame.draw.rect(screen, GAME_SPLASH, self.rect)
infont = pygame.font.Font(None, 18)
for msg_id in range(len(self.welcome_message)):
text = infont.render(self.welcome_message[msg_id], True, GAME_WHITE)
screen.blit(text, [30, 30 + msg_id * 18])
class Card(pygame.sprite.Sprite):
def __init__(self, color, x, y):
super().__init__()
self.color = color
self.flip = 0 # face down
# image setup
self.image = pygame.Surface([50,50])
self.init_draw(self.image)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def update(self):
print("upd")
pass
def init_draw(self, screen):
# now using sprite, so coords relative within sprite image (screen)
# upper left corner x and y then width and height (downward)
pygame.draw.rect(screen, GAME_BLACK, [0, 0, 50, 50])
def draw_finger(screen, x, y):
pygame.draw.polygon(screen, GAME_WHITE,
[ [x,y], [x+2, y], [x+2, y+5],
[x+8, y+5], [x+7, y+15],
[x+1, y+15], [x, y] ] )
# Setup --------------------------------------
pygame.init()
# Set the width and height of the screen [width,height]
size = [700, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Ft. Collorins")
# try defining this in constants
afont = pygame.font.Font(None, 18)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# Hide the mouse cursor
pygame.mouse.set_visible(0)
splash = SplashBox(100, 100)
dialog_group = pygame.sprite.Group()
dialog_group.add(splash)
splash_show = True
# -------- Main Program Loop -----------
while not done:
# ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
click_event = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# User clicks the mouse. Get the position
click_pos = pygame.mouse.get_pos()
print("Click ", click_pos)
click_event = True
# ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT
# ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT
pos = pygame.mouse.get_pos()
x = pos[0]
y = pos[1]
# ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
# First, clear the screen to ___. Don't put other drawing commands
# above this, or they will be erased with this command.
screen.fill( (0,55,0) )
if splash_show:
dialog_group.draw(screen)
if click_event and splash.rect.collidepoint(click_pos[0], click_pos[1]):
splash_show = False
draw_finger(screen, x, y)
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 20 frames per second
clock.tick(60)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
| {
"repo_name": "joadavis/rpi-coding",
"path": "ftcollorins/game.py",
"copies": "1",
"size": "5259",
"license": "mit",
"hash": 7452202255969483000,
"line_mean": 29.224137931,
"line_max": 131,
"alpha_frac": 0.5896558281,
"autogenerated": false,
"ratio": 3.531900604432505,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46215564325325054,
"avg_score": null,
"num_lines": null
} |
# a simple attempt at a color matching, stack choosing card game
# this version has no graphics, just text output
# joadavis Oct 20, 2016
# Another attempt at a game in one .py file
# No AI for this version, just two players taking turns
# objects - cards, buttons [draw, place, take, help], game session (to track turns)
# need to display scores and player labels
# display a "who won" message at the end
import random
COLORS_2P = ["Orange", "Brown", "Gray", "Blue", "Red"]
# from http://www.gossamer-threads.com/lists/python/dev/760692
# ANSI colors
colours = {
'none' : "",
'default' : "\033[.0m",
'bold' : "\033[.1m",
'underline' : "\033[.4m",
'blink' : "\033[.5m",
'reverse' : "\033[.7m",
'concealed' : "\033[.8m",
'black' : "\033[.30m",
'red' : "\033[.31m",
'green' : "\033[.32m",
'yellow' : "\033[.33m",
'blue' : "\033[.34m",
'magenta' : "\033[.35m",
'cyan' : "\033[.36m",
'white' : "\033[.37m",
'on_black' : "\033[.40m",
'on_red' : "\033[.41m",
'on_green' : "\033[.42m",
'on_yellow' : "\033[.43m",
'on_blue' : "\033[.44m",
'on_magenta' : "\033[.45m",
'on_cyan' : "\033[46m",
'on_white' : "\033[47m",
'beep' : "\007",
# non-standard attributes, supported by some terminals
'dark' : "\033[.2m",
'italic' : "\033[3m",
'rapidblink' : "\033[6m",
'strikethrough': "\033[9m",
}
# end clip from website
scoring_reminder = "1 card is 1 point, 2 is 3, 6, 10, 15, 21 max."
# alternate is 1 4 8 7 6 5
scoring_lookup = [0, 1, 3, 6, 10, 15, 21, 21, 21, 21] # only 9 cards of each color
card_runout_count = 15 # can increase to shorten game in testing
class Player(object):
# a list of the colored cards, sorted by number of cards
# store a tuple of (color, count)
ordered_stacks = []
done_for_round = False
name="Player X"
num_jokers = 0
bonus = 0
score = 0
def __init__(self):
# let empty stacks exist
self.ordered_stacks = []
self.num_jokers = 0
self.bonus = 0
# urgh. want an ordered dictionary sorted by card count
# maybe I just take the hit on sorting each turn because it will change each turn
self.done_for_round = False
def __str__(self):
return "--> {}\n--> {} and {} jokers with {} bonus".format(self.name, self.ordered_stacks, self.num_jokers, self.bonus)
def take(self, stack):
for card in stack:
if card == "joker":
self.num_jokers += 1
elif card == "+2":
self.bonus += 2
# if there is an existing ord stack, add it
# if not, create one
# thought 1 - if we had populated elements for all colors, could just list comprehension it
# thought 2 - more 'efficient' to not check all elements to do simple update, so search only til find match (or no match if not pre-populate)
# its a short list (5 or 7 colors) so not a big deal either way
# if was a really long list, lookup would be faster with hash or dict, but then also need to track which were non-empty in a second data structure
else:
updated = False
for index, ord_stack in enumerate(self.ordered_stacks):
st_color, st_count = ord_stack
if st_color == card:
st_count += 1
self.ordered_stacks[index] = (st_color, st_count)
updated = True
if not updated:
# create a new stack
self.ordered_stacks.append((card, 1))
print(card)
# TODO sort by count
print("done take {}".format(self.ordered_stacks))
def print_score(self):
#print("i dunno, like 0?")
# this is kinda tricky - dict is not sorted
# thinking - get a list of all the scores for the colors,
# then sort thelist, then first 3 of list + rest -
# ah, but what about jokers? if just have score, how do we know what the next score in scoring is?
color_scores = []
#for color in self.
#but using a list of tuples, not dict
self.score = self.bonus # start with bonus
jokers_to_use = self.num_jokers
if len(self.ordered_stacks) > 1:
to_score_positive = 3
for stack in self.ordered_stacks:
#st_color, st_count = self.ordered_stacks[0]
st_color, st_count = stack
while jokers_to_use > 0 and st_count < 6:
jokers_to_use -= 1
st_count += 1
st_score = scoring_lookup[st_count]
color_scores.append(st_score)
if to_score_positive > 0:
self.score = self.score + st_score
print("{} scored {} for {} cards".format(st_color, st_score, st_count))
else:
self.score = self.score - st_score
print("{} scored -{} for {} cards".format(st_color, st_score, st_count))
to_score_positive -= 1
# done. sum the color_scores then add bonus, store in self.score
print(" TOTAL SCORE is {}".format(self.score))
class GameSession(object):
players = []
deck = []
fresh_deck_2p = []
stacks = []
stack_limit_2p = [1, 2, 3]
def __init__(self):
# future: more players
if len(self.fresh_deck_2p) < 1:
self.generate_deck_2p()
self.stacks = [[] for i in self.stack_limit_2p]
put_back = []
for i in range(2):
pla = Player()
pla_name = input("What is your name Player {}? ".format(i))
if len(pla_name) > 1:
pla.name = pla_name
else:
pla.name = "Player " + str(i)
self.players.append(pla)
# give each player two non matching color cards
# put any that match into a list to go back
start_2 = []
picked_card = self.deck.pop()
while picked_card == "joker" or picked_card == "+2":
put_back.append(picked_card)
picked_card = self.deck.pop()
picked_card_2 = self.deck.pop()
while picked_card_2 == "joker" \
or picked_card_2 == "+2" \
or picked_card_2 == picked_card:
put_back.append(picked_card_2)
picked_card_2 = self.deck.pop()
pla.take([picked_card, picked_card_2])
self.deck = self.deck + put_back
def generate_deck_2p(self):
self.fresh_deck_2p = ["joker"] * 3
self.fresh_deck_2p.extend(["+2"] * 10)
for color in COLORS_2P:
self.fresh_deck_2p.extend([color] * 9)
random.shuffle(self.fresh_deck_2p)
print(self.fresh_deck_2p)
self.deck = self.fresh_deck_2p # thinking I'd just reshuffle later
def can_draw_and_place(self):
can_place = []
# todo refactor into elegant python code
for index in range(len(self.stack_limit_2p)):
if not self.stacks[index] == None \
and len(self.stacks[index]) < self.stack_limit_2p[index]:
can_place.append(index)
return can_place
def can_take(self):
''' return a list of stacks that may be taken '''
# todo: refactor as a list comprehension?
takeable_stacks = []
for index in range(len(self.stacks)):
if self.stacks[index] != None and len(self.stacks[index]) > 0:
takeable_stacks.append(index)
return takeable_stacks
def __str__(self):
return "\nStack 1 {} limit {}\n" \
"Stack 2 {} limit {}\n" \
"Stack 3 {} limit {}".format(
self.stacks[0], self.stack_limit_2p[0],
self.stacks[1], self.stack_limit_2p[1],
self.stacks[2], self.stack_limit_2p[2])
###
# Start playing the game
gs = GameSession()
for pla in gs.players:
print(pla)
# round loop
game_running = True
#while len(gs.deck) > 15:
while game_running:
# turn loop
for pla in gs.players:
print(gs)
#print("\n{}=========={}\n{}".format(colours['red'], colours['default'], pla))
print("\n==========\n{}".format( pla))
pla.done_for_turn = False
while not pla.done_for_round and not pla.done_for_turn:
# Determine what are valid moves for the player
# TODO: if all stacks full, cant draw
open_stacks = gs.can_draw_and_place()
takeable = gs.can_take()
if len(takeable) > 0:
# TODO incrrment displayed values by one
print("You can take one of {} stacks " \
"by pressing its number.".format(takeable))
if len(open_stacks) > 0:
print("You can draw a card by pressing d.")
act = input("What is your choice? ")
if act.startswith("d") and len(open_stacks) > 0:
card = gs.deck.pop()
while not pla.done_for_turn:
print("Can place a card in {}.".format(open_stacks))
act2 = input("Card is {}. Put it where? ".format(card))
# convert to int
# check it was a valid choice, and stack has room
# place card
if act2.startswith("1") and 0 in open_stacks:
gs.stacks[0].append(card)
pla.done_for_turn = True
if act2.startswith("2") and 1 in open_stacks:
gs.stacks[1].append(card)
pla.done_for_turn = True
if act2.startswith("3") and 2 in open_stacks:
gs.stacks[2].append(card)
pla.done_for_turn = True
else:
print(">> Invalid choice, please try again! <<")
elif act.startswith("1") and gs.stacks[0] != None:
# take first stack
pla.take(gs.stacks[0])
gs.stacks[0] = None
pla.done_for_round = True
pla.done_for_turn = True
elif act.startswith("2") and gs.stacks[1] != None:
# take second stack
pla.take(gs.stacks[1])
gs.stacks[1] = None
pla.done_for_round = True
pla.done_for_turn = True
elif act.startswith("3") and gs.stacks[2] != None:
# take third stack
pla.take(gs.stacks[2])
gs.stacks[2] = None
pla.done_for_round = True
pla.done_for_turn = True
else:
print(">> Invalid choice, try again. <<")
print("=== End of player turns ===\n")
#if all players done for round: or if num stacks taken
# dump remaining stack
# reset done flags
if gs.players[0].done_for_round and gs.players[1].done_for_round:
print("=== reset round ...:::::....:::::...")
#for stack in gs.stacks:
# stack = []
gs.stacks[0] = []
gs.stacks[1] = []
gs.stacks[2] = []
gs.players[0].done_for_round = False
gs.players[1].done_for_round = False
# check for game end at end of round
if len(gs.deck) < card_runout_count:
game_running = False
print("=== final round was triggered. time for scoring")
#else:
# print("{} dr = {}".format(gs.players[0].name, gs.players[0].done_for_round))
# TODO maybe num remaining stacks <= 1 (which is total num stacks - num players)?
# test
#gs.players[0].take(COLORS_2P)
# calculate scores and winner
winning_score = 0
winning_player = "Its a tie!"
for pla in gs.players:
print(pla.name)
pla.print_score()
if pla.score > winning_score:
winning_score = pla.score
winning_player = pla.name
elif pla.score == winning_score:
winning_player = "Its a tie!"
print("With {} points the winner is... {}".format(winning_score, winning_player))
print("\nGame is done. Hope you enjoyed it.\n")
| {
"repo_name": "joadavis/rpi-coding",
"path": "ftcollorins/game-textversion.py",
"copies": "1",
"size": "12256",
"license": "mit",
"hash": -3938201163024798700,
"line_mean": 36.7107692308,
"line_max": 158,
"alpha_frac": 0.529944517,
"autogenerated": false,
"ratio": 3.606827545615068,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9558632222424391,
"avg_score": 0.015627968038135282,
"num_lines": 325
} |
"""A simple base for creating common types of work-db filters.
"""
import argparse
import logging
import sys
from exit_codes import ExitCode
from cosmic_ray.work_db import use_db
class FilterApp:
"""Base class for simple WorkDB filters.
This provides command-line handling for common filter options like
the session and verbosity level. Subclasses can add their own arguments
as well. This provides a `main()` function that open the session's WorkDB
and passes it to the subclass's `filter()` function.
"""
def add_args(self, parser: argparse.ArgumentParser):
"""Add any arguments that the subclass needs to the parser.
Args:
parser: The ArgumentParser for command-line processing.
"""
def description(self):
"""The description of the filter.
This is used for the command-line help message.
"""
return None
def main(self, argv=None):
"""The main function for the app.
Args:
argv: Command line argument list of parse.
"""
if argv is None:
argv = sys.argv[1:]
parser = argparse.ArgumentParser(
description=self.description(),
)
parser.add_argument(
'session', help="Path to the session on which to operate")
parser.add_argument(
'--verbosity', help='Verbosity level for logging', default='WARNING')
self.add_args(parser)
args = parser.parse_args(argv)
logging.basicConfig(level=getattr(logging, args.verbosity))
with use_db(args.session) as db:
self.filter(db, args)
return ExitCode.OK
def filter(self, work_db, args):
"""Apply this filter to a WorkDB.
This should modify the WorkDB in place.
Args:
work_db: An open WorkDB instance.
args: The argparse Namespace for the command line.
"""
raise NotImplementedError()
| {
"repo_name": "sixty-north/cosmic-ray",
"path": "src/cosmic_ray/tools/filters/filter_app.py",
"copies": "1",
"size": "1980",
"license": "mit",
"hash": 2772021144137747500,
"line_mean": 27.2857142857,
"line_max": 81,
"alpha_frac": 0.6237373737,
"autogenerated": false,
"ratio": 4.551724137931035,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5675461511631035,
"avg_score": null,
"num_lines": null
} |
""" A simple benchmark comparing the ALS model here to QMF from Quora.
Compares the running time of this package vs the QMF library from Quora.
On my desktop (Intel Core i7 7820x) running with 50 factors for 15 iterations
on the last.fm 360k dataset, this is the output:
QMF finished in 279.32511353492737
Implicit finished in 24.046602964401245
Implicit is 11.615990580808532 times faster
"""
from __future__ import print_function
import argparse
import logging
import time
from subprocess import call
import scipy.io
from implicit.als import AlternatingLeastSquares
from implicit.nearest_neighbours import bm25_weight
def benchmark_implicit(matrix, factors, reg, iterations):
start = time.time()
model = AlternatingLeastSquares(factors, regularization=reg, iterations=iterations, use_cg=True)
model.fit(matrix)
return time.time() - start
def benchmark_qmf(qmfpath, matrix, factors, reg, iterations):
matrix = matrix.tocoo()
datafile = "qmf_data.txt"
open(datafile, "w").write(
"\n".join("%s %s %s" % vals for vals in zip(matrix.row, matrix.col, matrix.data))
)
def get_qmf_command(nepochs):
return [
qmfpath,
"--train_dataset",
datafile,
"--nfactors",
str(factors),
"--confidence_weight",
"1",
"--nepochs",
str(nepochs),
"--regularization_lambda",
str(reg),
]
# ok, so QMF needs to read the data in - and including
# that in the timing isn't fair. So run it once with no iterations
# to get a sense of how long reading the input data takes, and
# subtract from the final results
read_start = time.time()
call(get_qmf_command(0))
read_dataset_time = time.time() - read_start
calculate_start = time.time()
call(get_qmf_command(iterations))
return time.time() - calculate_start - read_dataset_time
def run_benchmark(args):
plays = bm25_weight(scipy.io.mmread(args.inputfile))
qmf_time = benchmark_qmf(
args.qmfpath, plays, args.factors, args.regularization, args.iterations
)
implicit_time = benchmark_implicit(plays, args.factors, args.regularization, args.iterations)
print("QMF finished in", qmf_time)
print("Implicit finished in", implicit_time)
print("Implicit is %s times faster" % (qmf_time / implicit_time))
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Generates Benchmark", formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"--input", type=str, dest="inputfile", help="dataset file in matrix market format"
)
parser.add_argument(
"--qmfpath", type=str, dest="qmfpath", help="full path to qmf wals.bin file", required=True
)
parser.add_argument(
"--factors", type=int, default=50, dest="factors", help="Number of factors to calculate"
)
parser.add_argument(
"--reg", type=float, default=0.8, dest="regularization", help="regularization weight"
)
parser.add_argument(
"--iter", type=int, default=15, dest="iterations", help="Number of ALS iterations"
)
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG)
run_benchmark(args)
| {
"repo_name": "benfred/implicit",
"path": "benchmarks/benchmark_qmf.py",
"copies": "1",
"size": "3314",
"license": "mit",
"hash": 5050523821809884000,
"line_mean": 30.8653846154,
"line_max": 100,
"alpha_frac": 0.662039831,
"autogenerated": false,
"ratio": 3.7152466367713006,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48772864677713,
"avg_score": null,
"num_lines": null
} |
""" A simple benchmark of exfoliate vs aiohttp.
Compares the performance of aiohttp to exfoliate for making 1000 requests to an aiohttp server that
is spawned automatically by the script. The server returns random content with random size between
0 bytes and 1 MB.
Of course, as with any benchmark, your mileage may vary, and if performance is critical, you should
benchmark exfoliate using a workload representative of yours to assess its suitability for your
needs.
"""
import multiprocessing
import requests
import timeit
def wait_for_server_to_start(url):
while True:
try:
response = requests.get('http://127.0.0.1:8080/')
response.raise_for_status()
except:
pass
else:
break
def run_server():
import aiohttp.web
import asyncio
import random
import os
async def root(request):
content_length = random.randint(0, 1000000) # between 0 bytes and 1 MB
content = os.urandom(content_length)
response = aiohttp.web.Response(body=content)
return response
async def set_seed(request):
seed = request.match_info.get('seed')
random.seed(seed)
response = aiohttp.web.Response()
return response
app = aiohttp.web.Application()
app.router.add_get('/', root)
app.router.add_put('/seed/{seed}', set_seed)
def noop_print(*args, **kwargs): pass
# runs at http://127.0.0.1:8080/
aiohttp.web.run_app(app, print=noop_print)
server_process = multiprocessing.Process(target=run_server)
server_process.daemon = True
server_process.start()
wait_for_server_to_start('http://127.0.0.1:8080/')
setup = """
import aiohttp
import asyncio
import requests
NUMBER_OF_REQUESTS = 1000
requests.put('http://127.0.0.1:8080/seed/1')
"""
execute = """
async def make_request(url, session):
async with session.get(url) as response:
content = await response.read()
return response.status
async def make_requests():
async with aiohttp.ClientSession() as session:
tasks = [
asyncio.ensure_future(
make_request('http://127.0.0.1:8080/', session)
) for _ in range(NUMBER_OF_REQUESTS)
]
status_codes = await asyncio.gather(*tasks)
for status_code in status_codes:
assert status_code == 200
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(make_requests())
loop.run_until_complete(future)
"""
aiohttp_time = timeit.timeit(execute, setup=setup, number=3)
print('aiohttp: {} seconds'.format(round(aiohttp_time, 1)))
setup = """
import exfoliate
import requests
requests.put('http://127.0.0.1:8080/seed/1')
NUMBER_OF_REQUESTS = 1000
"""
execute = """
client = exfoliate.Client()
for _ in range(NUMBER_OF_REQUESTS):
client.get('http://127.0.0.1:8080/')
for future in client.futures:
response = future.result()
assert response.status_code == 200
"""
exfoliate_time = timeit.timeit(execute, setup=setup, number=3)
print('exfoliate: {} seconds'.format(round(exfoliate_time, 1)))
| {
"repo_name": "brianjpetersen/exfoliate",
"path": "benchmark.py",
"copies": "1",
"size": "3104",
"license": "mit",
"hash": 8295516679138504000,
"line_mean": 25.5299145299,
"line_max": 100,
"alpha_frac": 0.6639819588,
"autogenerated": false,
"ratio": 3.5474285714285716,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.967438942611514,
"avg_score": 0.007404220822686347,
"num_lines": 117
} |
# A simple bot framework
import requests
import json
class CPBot(object):
def __init__(self, endpoint):
self.endpoint = endpoint
self.module_capabilities = None
self.static_capabilities = None
self.background_capabilities = None
def doCommands(self, cmd_list):
json_data = json.dumps(cmd_list)
headers = {"Content-type": "text/json"}
resp = requests.post(self.endpoint, data=json_data, headers=headers)
return resp.json()
def whoami(self):
resp = requests.post(self.endpoint, data='[]', headers={"Content-type": "text/json"})
return resp.headers['Client-ip']
def doCommand(self,cmd):
return self.doCommands([cmd])[0]
def assert_success(self,result):
if isinstance(result,dict):
if result['success']:
if 'result' in result:
return result['result']
return None
raise Exception(result['error'])
if isinstance(result,list):
for r in result:
if not r['success']:
raise Exception(r['error'])
return [r['result'] for r in result if 'result' in r]
raise Exception('Bad response type from server')
| {
"repo_name": "zbanks/landfill",
"path": "landfill/scraper/cpbot.py",
"copies": "1",
"size": "1273",
"license": "mit",
"hash": -3608889245527982000,
"line_mean": 30.825,
"line_max": 93,
"alpha_frac": 0.5773762765,
"autogenerated": false,
"ratio": 4.3447098976109215,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5422086174110922,
"avg_score": null,
"num_lines": null
} |
"""A simple bot script, built on Pyramid using Cornice
This sample script leverages the Pyramid web framework (https://trypyramid.com/) with
Cornice (https://cornice.readthedocs.io). By default the web server will be reachable at
port 6543 you can change this default if desired (see `pyramidSparkBot.ini`).
ngrok (https://ngrok.com/) can be used to tunnel traffic back to your server
if your machine sits behind a firewall.
You must create a Spark webhook that points to the URL where this script is
hosted. You can do this via the CiscoSparkAPI.webhooks.create() method.
Additional Spark webhook details can be found here:
https://developer.ciscospark.com/webhooks-explained.html
A bot must be created and pointed to this server in the My Apps section of
https://developer.ciscospark.com. The bot's Access Token should be added as a
'SPARK_ACCESS_TOKEN' environment variable on the web server hosting this
script.
This script supports Python versions 2 and 3.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from cornice import Service
from builtins import *
import json
import requests
from ciscosparkapi import CiscoSparkAPI, Webhook
import logging
log = logging.getLogger(__name__)
# Module constants
CAT_FACT_URL = 'http://catfacts-api.appspot.com/api/facts?number=1'
# Initialize the environment
spark_api = CiscoSparkAPI() # Create the Cisco Spark API connection object
# Helper functions
def get_catfact():
"""Get a cat fact from catfacts-api.appspot.com and return it as a string.
Functions for Soundhound, Google, IBM Watson, or other APIs can be added
to create the desired functionality into this bot.
"""
response = requests.get(CAT_FACT_URL, verify=False)
response_dict = json.loads(response.text)
return response_dict['facts'][0]
sparkwebhook = Service(name='sparkwebhook', path='/sparkwebhook', description="Spark Webhook")
@sparkwebhook.get()
def get_sparkwebhook(request):
log.info(get_catfact())
return {"fact": get_catfact()}
@sparkwebhook.post()
# Your Spark webhook should point to http://<serverip>:6543/sparkwebhook
def post_sparkwebhook(request):
"""Respond to inbound webhook JSON HTTP POST from Cisco Spark."""
json_data = request.json # Get the POST data sent from Cisco Spark
log.info("\n")
log.info("WEBHOOK POST RECEIVED:")
log.info(json_data)
log.info("\n")
webhook_obj = Webhook(json_data) # Create a Webhook object from the JSON data
room = spark_api.rooms.get(webhook_obj.data.roomId) # Get the room details
message = spark_api.messages.get(webhook_obj.data.id) # Get the message details
person = spark_api.people.get(message.personId) # Get the sender's details
log.info("NEW MESSAGE IN ROOM '{}'".format(room.title))
log.info("FROM '{}'".format(person.displayName))
log.info("MESSAGE '{}'\n".format(message.text))
# This is a VERY IMPORTANT loop prevention control step.
# If you respond to all messages... You will respond to the messages
# that the bot posts and thereby create a loop condition.
me = spark_api.people.me()
if message.personId == me.id:
# Message was sent by me (bot); do not respond.
return {'Message': 'OK'}
else:
# Message was sent by someone else; parse message and respond.
if "/CAT" in message.text:
log.info("FOUND '/CAT'")
catfact = get_catfact() # Get a cat fact
log.info("SENDING CAT FACT'{}'".format(catfact))
spark_api.messages.create(room.id, text=catfact) # Post the fact to the room where the request was received
return {'Message': 'OK'}
| {
"repo_name": "jbogarin/ciscosparkapi",
"path": "examples/pyramidSparkBot/pyramidSparkBot/views.py",
"copies": "1",
"size": "3913",
"license": "mit",
"hash": 6365849613040943000,
"line_mean": 37.362745098,
"line_max": 132,
"alpha_frac": 0.6718630207,
"autogenerated": false,
"ratio": 3.817560975609756,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9932675183685635,
"avg_score": 0.01134976252482416,
"num_lines": 102
} |
""" A simple box-model of an estuary-ocean-river system which tracks the
evolution of oxygen, nutrients, and salinity given simple, idealized
scenarios.
Authors:
Daniel Rothenberg <darothen@mit.edu>
Evan Howard <ehoward@whoi.edu>
Version: January 18, 2016
"""
from numpy import array, ceil, mean, sin, pi, vstack
from pandas import DataFrame, Index
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='ticks', context='talk')
class EstuaryModel(object):
""" Container class implementing the simple estuary model.
Parameters
----------
V, S, N, O: floats
Initial (average) estuary volume [m3], salinity [kg/m3], and molar
concentration of nitrogen and oxygen [mmol/m3]
z : float
Average estuary depth, in m
tide_func : function
A function of the argument `t` (again in hours) which yields
the mass transport due to tidal inflow and outflow in m3/hr.
By convention, the function should return positive values for
inflow and negative values for outflow.
river_flow_rate : float
Fraction (preferably between 0 and 0.2) of river flow per day
relative to estuary mean volume. Set to `0` to disable river
flow
N_river, O_river : float
Nitrogen and oxygen concentration in river in mmol m-3
S_ocean, N_ocean, O_ocean : floats
Boundary condition concentrations for S, N, O in ocean and upriver
sources. Because these are concentrations, S is kg/m3, and N and O
are mmol/m3
G : float
Gas exchange rate in m/d, between 1 and 5
P : float
System productivity relative to normal conditions (P=1); may vary
between 0.5 (cloudy) and 2.0 (bloom)
Attributes
----------
y0 : array of floats
Model initial conditions, computed from initial state species
concentrations
V0 : float
Initial estuary volume, in m3
estuary_area : float
Surface area of estuary available for gas exchange, based on
initial geometry (volume / depth) in m3
has_river, has_tides : boolean
Flags indicating whether the simulation has river flow and tides,
respectively
"""
def __init__(self, V, S, N, O,
z=5., tide_func=lambda t: 0,
river_flow_rate=0.05, N_river=100., O_river=231.2,
S_ocean=35., N_ocean=20., O_ocean=231.2,
G=3., P=1.):
# Bind initial conditions
self.V = V
self.S = S
self.N = N
self.O = O
# Bind model parameters and arguments
self.tide_func = tide_func
self.z = z
self.river_flow_rate = river_flow_rate
self.N_river = N_river
self.O_river = O_river
self.S_ocean = S_ocean
self.N_ocean = N_ocean
self.O_ocean = O_ocean
self.G = G
self.P = P
# Infer additional parameters
self.y0 = array([V, S*V, N*V, O*V])
self.V0 = V
self.estuary_area = V/z
self.has_river = river_flow_rate > 0
self.has_tides = tide_func(1.15) != tide_func(1.85)
def __call__(self, y, t, *args, **kwargs):
""" Alias to call the model system of ODEs directly. """
return self.model_ode(y, t, *args, **kwargs)
def estuary_ode(self, y, t, P_scale=1.0):
""" Model system of ODEs.
This function evaluates the model differential equations
at a time instant `t`, and returns the vector representing
the derivative of the model state with respect to time.
Parameters
----------
y : array
The current volume, salinity, nitrogen, and ocean state
variables:
- V: m3
- S: kg
- N: mmol
- O: mmol
t : float
The current evaluation time, in hours.
P_scale : float
Factor to scale system productivity,
Returns
-------
dy_dt : array
Derivative of the current state-time.
"""
# Un-pack current state
V, S, N, O = y[:]
# Pre-compute terms which will be used in the derivative
# calculations
# 2) Biological production minus respiration
# Note: there's clearly some sort of stoichiometry going on here, o
# need to find out what those reactions are. also, in Evan's
# production code (post-spin-up), this is scaled by the mean
# N value from the past 24 hours divided by the ocean N
# levels
J = P_scale*self.P*(125.*16./154.)*sin(2.*pi*(t+0.75)/24. + pi) # mmol/m2/day
# J /= 24 # day-1 -> h-1
# 4) Current molar concentrations of N and O (to mmol / m3)
S = S/V
N = N/V
O = O/V
# 5) Tidal source gradients, given direction of tide
tidal_flow = self.estuary_area*self.tide_func(t)
if tidal_flow > 0:
tidal_S_contrib = tidal_flow*self.S_ocean
tidal_N_contrib = tidal_flow*self.N_ocean
tidal_O_contrib = tidal_flow*self.O_ocean
else:
# N/O are already in molar concentrations
tidal_S_contrib = tidal_flow*S
tidal_N_contrib = tidal_flow*N
tidal_O_contrib = tidal_flow*O
# Compute derivative terms
dV_dt = tidal_flow
dS_dt = -self.river_flow_rate*self.V0*S + tidal_S_contrib
dN_dt = -J*self.estuary_area \
- self.river_flow_rate*self.V0*(N - self.N_river) \
+ tidal_N_contrib
dO_dt = J*(154./16.)*self.estuary_area \
+ (self.G/24.)*(self.O_river - O)*self.estuary_area \
- self.river_flow_rate*self.V0*(O - self.O_river) \
+ tidal_O_contrib
return array([dV_dt, dS_dt, dN_dt, dO_dt])
def run_model(self, dt=1., t_end=1000., t_spinup=48.):
""" Run the current model with a simple Euler marching algorithm
Parameters
----------
dt : float
Timestep, in hours
t_end : float
Cut-off time in hours to end integration/marching
t_spinup : float
Time in hours after which productivity will be scaled by
daily averages of nutrient availability
Returns
-------
result : DataFrame
A DataFrame with the columns V, S, N, O corresponding to the
components of the model state vector, indexed along time in hours.
S, N, O are in kg/m3 and mmol/m3, and V is % of initial volume
"""
# Initialize output as an array
out_y = vstack([self.y0, ])
ts = [0., ]
# Main integration loop
i, t = 1, 0.
while t < t_end:
# Pop last state off of stack
y = out_y[-1].T
# If we're past spin-up, then average the N concentration over
# the last 24 hours to scale productivity
if t > t_spinup:
n_24hrs = int(ceil(24./dt))
P_scale = \
mean(out_y[-n_24hrs:, 2]/out_y[-n_24hrs:, 0])/self.N_ocean
else:
P_scale = 1.
# Euler step
t += dt
new_y = y + dt*self.estuary_ode(y, t, P_scale)
# Correct non-physical V, S, N, or O (where they're < 0)
new_y[new_y < 0] = 0.
# Save output onto stack
out_y = vstack([out_y, new_y])
ts.append(t)
i += 1
# Shape output into DataFrame
out = out_y[:]
ts = array(ts)
result = DataFrame(data=out, columns=['V', 'S', 'N', 'O'],
dtype=float,
index=Index(ts, name='time'))
# Convert to molar concentrations
result.S /= result.V
result.N /= result.V
result.O /= result.V
# Add tidal height (meters) to output
result['Z'] = result.V/self.estuary_area
# Convert volume to percentage relative to initial
result.V = 100*(result.V - self.V)/self.V
return result
def basic_tidal_flow(t):
""" Rate of tidal height change in m/s as a function of time in hours. """
return 0.5*sin(2.*pi*(t / 12.45))
def quick_plot(results, aspect=4., size=3., palette='Dark2'):
""" Make a quick 3-panel plot with the results timeseries. """
colors = sns.cycle(sns.color_palette(palette, 3))
# Compute figure size based on aspect/size
fig_width = size*aspect
fig_height = 3*size
fig, axs = plt.subplots(3, 1, sharex=True, figsize=(fig_width, fig_height))
ax_S, ax_N, ax_O = axs
# Salinity
# Note that results here is in kg/m3, but assuming STP and density of
# water = 1000 kg/m3, this is equivalent to g/kg
ax_S.plot(results.index, results.S, color=next(colors))
ax_S.set_ylabel("Salinity (g/kg)")
# Nitrogen
# Note that results here is in mmol/m3, which is equivalent to micromol/L
# if we assume STP (1 L = 1000 m3)
ax_N.plot(results.index, results.N, color=next(colors))
ax_N.set_ylabel("Nitrate ($\mu$mol/L)")
# Oxygen
ax_O.plot(results.index, results.O, color=next(colors))
ax_O.set_ylabel("Oxygen ($\mu$mol/L)")
ax_O.set_xlabel("Days")
for ax in axs:
ax.set_ylim(0)
ylims = ax.get_ylim()
ax.vlines(2, ylims[0], ylims[1], linestyle='dashed', color='k')
ax.set_xlim(0, results.index[-1])
sns.despine(fig)
plt.show()
return fig, axs
| {
"repo_name": "darothen/blb_estuary",
"path": "app/estuary.py",
"copies": "1",
"size": "9614",
"license": "mit",
"hash": -773362799212233700,
"line_mean": 30.8344370861,
"line_max": 85,
"alpha_frac": 0.5637611816,
"autogenerated": false,
"ratio": 3.4998179832544594,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45635791648544594,
"avg_score": null,
"num_lines": null
} |
"""A simple but flexible modal dialog box."""
from Tkinter import *
class SimpleDialog:
def __init__(self, master,
text='', buttons=[], default=None, cancel=None,
title=None, class_=None):
if class_:
self.root = Toplevel(master, class_=class_)
else:
self.root = Toplevel(master)
if title:
self.root.title(title)
self.root.iconname(title)
self.message = Message(self.root, text=text, aspect=400)
self.message.pack(expand=1, fill=BOTH)
self.frame = Frame(self.root)
self.frame.pack()
self.num = default
self.cancel = cancel
self.default = default
self.root.bind('<Return>', self.return_event)
for num in range(len(buttons)):
s = buttons[num]
b = Button(self.frame, text=s,
command=(lambda self=self, num=num: self.done(num)))
if num == default:
b.config(relief=RIDGE, borderwidth=8)
b.pack(side=LEFT, fill=BOTH, expand=1)
self.root.protocol('WM_DELETE_WINDOW', self.wm_delete_window)
self._set_transient(master)
def _set_transient(self, master, relx=0.5, rely=0.3):
widget = self.root
widget.withdraw() # Remain invisible while we figure out the geometry
widget.transient(master)
widget.update_idletasks() # Actualize geometry information
if master.winfo_ismapped():
m_width = master.winfo_width()
m_height = master.winfo_height()
m_x = master.winfo_rootx()
m_y = master.winfo_rooty()
else:
m_width = master.winfo_screenwidth()
m_height = master.winfo_screenheight()
m_x = m_y = 0
w_width = widget.winfo_reqwidth()
w_height = widget.winfo_reqheight()
x = m_x + (m_width - w_width) * relx
y = m_y + (m_height - w_height) * rely
if x+w_width > master.winfo_screenwidth():
x = master.winfo_screenwidth() - w_width
elif x < 0:
x = 0
if y+w_height > master.winfo_screenheight():
y = master.winfo_screenheight() - w_height
elif y < 0:
y = 0
widget.geometry("+%d+%d" % (x, y))
widget.deiconify() # Become visible at the desired location
def go(self):
self.root.wait_visibility()
self.root.grab_set()
self.root.mainloop()
self.root.destroy()
return self.num
def return_event(self, event):
if self.default is None:
self.root.bell()
else:
self.done(self.default)
def wm_delete_window(self):
if self.cancel is None:
self.root.bell()
else:
self.done(self.cancel)
def done(self, num):
self.num = num
self.root.quit()
if __name__ == '__main__':
def test():
root = Tk()
def doit(root=root):
d = SimpleDialog(root,
text="This is a test dialog. "
"Would this have been an actual dialog, "
"the buttons below would have been glowing "
"in soft pink light.\n"
"Do you believe this?",
buttons=["Yes", "No", "Cancel"],
default=0,
cancel=2,
title="Test Dialog")
print d.go()
t = Button(root, text='Test', command=doit)
t.pack()
q = Button(root, text='Quit', command=t.quit)
q.pack()
t.mainloop()
test()
| {
"repo_name": "kkdd/arangodb",
"path": "3rdParty/V8-4.3.61/third_party/python_26/Lib/lib-tk/SimpleDialog.py",
"copies": "204",
"size": "3728",
"license": "apache-2.0",
"hash": 2980666221380429300,
"line_mean": 32.2857142857,
"line_max": 77,
"alpha_frac": 0.5099248927,
"autogenerated": false,
"ratio": 3.9200841219768665,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0016947152024279339,
"num_lines": 112
} |
# A simple chat server using websockets
# Uses a slight modification to the protocol I'm using to write a different
# application
# Modifications:
# No rooms
# Uses Facebook to authenticate
from flask import Flask, session, escape, request, redirect
from flask_socketio import SocketIO, emit
from blog.util import render_template, app
from os import getenv
from urllib.request import urlopen
from json import loads as loadjson
socketio = SocketIO(app)
fb_appid = getenv('FB_APPID')
fb_secret = getenv('FB_SECRET')
@app.route('/chat')
def chat():
if 'accesskey' not in session:
if 'error_reason' in request.args:
return 'You must login via Facebook to use our chat!'
elif 'code' in request.args:
resp = ''
with urlopen('https://graph.facebook.com/v2.3/oauth/access_token?client_id=%s&redirect_uri=http://wtc.codeguild.co/chat&client_secret=%s&code=%s' % (fb_appid, fb_secret, request.args['code'])) as r:
resp = r.read()
j = loadjson(resp.decode("utf-8"))
if 'access_token' in j:
session['accesskey'] = j['access_token']
return redirect('/chat')
else:
return 'An error has occured, please try again later'
else:
return redirect('https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=http://wtc.codeguild.co/chat&response_type=code' % fb_appid)
return render_template('chat.html')
@socketio.on('message')
def handle_message(json):
emit('message', {
'room': 'willcoates',
'msg': escape('%s: %s' % (session['displayname'], json['msg'])),
'role': 'message'
}, broadcast=True, include_self=False)
emit('message', {
'room': 'willcoates',
'msg': escape('%s' % json['msg']),
'role': 'mymessage'
})
@socketio.on('connect')
def connect():
if 'accesskey' not in session:
return False
resp = ''
with urlopen('https://graph.facebook.com/v2.3/me?client_id=%s&client_secret=%s&access_token=%s' % (fb_appid, fb_secret, session['accesskey'])) as r:
resp = r.read()
j = loadjson(resp.decode("utf-8"))
session['displayname'] = j['name']
emit('message', {
'room': 'broadcast',
'msg': 'Welcome to Will Coates\' Chat',
'role': 'notice'
})
emit('message', {
'room': 'willcoates',
'msg': escape('%s has joined the chat!' % session['displayname']),
'role': 'notice'
}, broadcast=True)
@socketio.on('disconnect')
def disconnect():
if 'displayname' in session:
emit('message', {
'room': 'willcoates',
'msg': escape('%s has left the chat!' % session['displayname']),
'role': 'notice'
}, broadcast=True)
else:
emit('message', {
'room': 'willcoates',
'msg': 'Connection dropped on connect',
'role': 'notice'
}, broadcast=True)
| {
"repo_name": "CodeGuild-co/wtc",
"path": "blog/chat.py",
"copies": "1",
"size": "2629",
"license": "mit",
"hash": -962476915297159700,
"line_mean": 29.5697674419,
"line_max": 201,
"alpha_frac": 0.6694560669,
"autogenerated": false,
"ratio": 2.963923337091319,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4133379403991319,
"avg_score": null,
"num_lines": null
} |
"""A simple class for distiguising between events coming from various sources.
"""
from functools import wraps
class Event(object):
"""A basic event class that has a kind (name, type, identifier, whatevs) and
some associated data.
"""
def __init__(self, name, data=None):
"""Parameters
----------
name : str
The kind of the event, such as 'github'.
data : optional
Information associated with the even for the plugins to use.
"""
self.name = name
self.data = data
def __str__(self):
return "{0} event holding {1}".format(self.name, self.data)
def __repr__(self):
return "{0}(kind={1}, data={2})".format(self.__class__.__name__, self.name,
self.data)
def __eq__(self, other):
if not isinstance(other, Event):
return NotImplemented
return (self.name == other.name) and (self.data == other.data)
def runfor(*events):
"""A decorator for running only certain events.
"""
events = frozenset(events)
def dec(f):
@wraps(f)
def wrapper(self, rc, *args, **kwargs):
if rc.event.name not in events:
return
return f(self, rc, *args, **kwargs)
return wrapper
return dec
| {
"repo_name": "polyphemus-ci/polyphemus",
"path": "polyphemus/event.py",
"copies": "1",
"size": "1351",
"license": "bsd-2-clause",
"hash": 3156204382372060700,
"line_mean": 29.0222222222,
"line_max": 84,
"alpha_frac": 0.5455218357,
"autogenerated": false,
"ratio": 4.261829652996846,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.005907620802009452,
"num_lines": 45
} |
# A simple CLI runner for slurm that can be used when running Galaxy from a
# non-submit host and using a Slurm cluster.
from logging import getLogger
try:
from galaxy.model import Job
job_states = Job.states
except ImportError:
# Not in Galaxy, map Galaxy job states to Pulsar ones.
from pulsar.util import enum
job_states = enum(RUNNING='running', OK='complete', QUEUED='queued', ERROR="failed")
from ..job import BaseJobExec
log = getLogger(__name__)
argmap = {
'memory': '-M', # There is code in job_script_kwargs relying on this name's setting
'cores': '-n',
'queue': '-q',
'working_dir': '-cwd',
'project': '-P'
}
class LSF(BaseJobExec):
def __init__(self, **params):
self.params = {}
for k, v in params.items():
self.params[k] = v
def job_script_kwargs(self, ofile, efile, job_name):
scriptargs = {'-o': ofile,
'-e': efile,
'-J': job_name}
# Map arguments using argmap.
for k, v in self.params.items():
if k == 'plugin':
continue
try:
if k == 'memory':
# Memory requires both -m and -R rusage[mem=v] request
scriptargs['-R'] = "\"rusage[mem=%s]\"" % v
if not k.startswith('-'):
k = argmap[k]
scriptargs[k] = v
except Exception:
log.warning('Unrecognized long argument passed to LSF CLI plugin: %s' % k)
# Generated template.
template_scriptargs = ''
for k, v in scriptargs.items():
template_scriptargs += '#BSUB %s %s\n' % (k, v)
return dict(headers=template_scriptargs)
def submit(self, script_file):
# bsub returns Job <9147983> is submitted to default queue <research-rh7>.
# This should be really handled outside with something like
# parse_external. Currently CLI runner expect this to just send it in the last position
# of the string.
return "bsub <%s | awk '{ print $2}' | sed 's/[<>]//g'" % script_file
def delete(self, job_id):
return 'bkill %s' % job_id
def get_status(self, job_ids=None):
return "bjobs -a -o \"id stat\" -noheader" # check this
def get_single_status(self, job_id):
return "bjobs -o stat -noheader " + job_id
def parse_status(self, status, job_ids):
# Get status for each job, skipping header.
rval = {}
for line in status.splitlines():
job_id, state = line.split()
if job_id in job_ids:
# map job states to Galaxy job states.
rval[job_id] = self._get_job_state(state)
return rval
def parse_single_status(self, status, job_id):
if not status:
# Job not found in LSF, most probably finished and forgotten.
# lsf outputs: Job <num> is not found -- but that is on the stderr
# Note: a very old failed job job will not be shown here either,
# which would be badly handled here. So this only works well when Galaxy
# is constantly monitoring the jobs. The logic here is that DONE jobs get forgotten
# faster than failed jobs.
log.warning("Job id '%s' not found LSF status check" % job_id)
return job_states.OK
return self._get_job_state(status)
def get_failure_reason(self, job_id):
return "bjobs -l " + job_id
def parse_failure_reason(self, reason, job_id):
# LSF will produce the following in the job output file:
# TERM_MEMLIMIT: job killed after reaching LSF memory usage limit.
# Exited with exit code 143.
for line in reason.splitlines():
if "TERM_MEMLIMIT" in line:
from galaxy.jobs import JobState
return JobState.runner_states.MEMORY_LIMIT_REACHED
return None
def _get_job_state(self, state):
# based on:
# https://www.ibm.com/support/knowledgecenter/en/SSETD4_9.1.3/lsf_admin/job_state_lsf.html
# https://www.ibm.com/support/knowledgecenter/en/SSETD4_9.1.2/lsf_command_ref/bjobs.1.html
try:
return {
'EXIT': job_states.ERROR,
'RUN': job_states.RUNNING,
'PEND': job_states.QUEUED,
'DONE': job_states.OK,
'PSUSP': job_states.ERROR,
'USUSP': job_states.ERROR,
'SSUSP': job_states.ERROR,
'UNKWN': job_states.ERROR,
'WAIT': job_states.QUEUED,
'ZOMBI': job_states.ERROR
}.get(state)
except KeyError:
raise KeyError("Failed to map LSF status code [%s] to job state." % state)
__all__ = ('LSF',)
| {
"repo_name": "galaxyproject/pulsar",
"path": "pulsar/managers/util/cli/job/lsf.py",
"copies": "2",
"size": "4842",
"license": "apache-2.0",
"hash": -5907865479388304000,
"line_mean": 36.5348837209,
"line_max": 98,
"alpha_frac": 0.5646427096,
"autogenerated": false,
"ratio": 3.738996138996139,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0006945845423387935,
"num_lines": 129
} |
# A simple CLI runner for slurm that can be used when running Galaxy from a
# non-submit host and using a Slurm cluster.
from ..job import BaseJobExec
from logging import getLogger
try:
from galaxy.model import Job
job_states = Job.states
except ImportError:
# Not in Galaxy, map Galaxy job states to Pulsar ones.
from galaxy.util import enum
job_states = enum(RUNNING='running', OK='complete', QUEUED='queued', ERROR="failed")
log = getLogger(__name__)
argmap = {
'time': '-t',
'ncpus': '-c',
'partition': '-p'
}
class Slurm(BaseJobExec):
def __init__(self, **params):
self.params = {}
for k, v in params.items():
self.params[k] = v
def job_script_kwargs(self, ofile, efile, job_name):
scriptargs = {'-o': ofile,
'-e': efile,
'-J': job_name}
# Map arguments using argmap.
for k, v in self.params.items():
if k == 'plugin':
continue
try:
if not k.startswith('-'):
k = argmap[k]
scriptargs[k] = v
except:
log.warning('Unrecognized long argument passed to Slurm CLI plugin: %s' % k)
# Generated template.
template_scriptargs = ''
for k, v in scriptargs.items():
template_scriptargs += '#SBATCH %s %s\n' % (k, v)
return dict(headers=template_scriptargs)
def submit(self, script_file):
return 'sbatch %s' % script_file
def delete(self, job_id):
return 'scancel %s' % job_id
def get_status(self, job_ids=None):
return "squeue -a -o '%A %t'"
def get_single_status(self, job_id):
return "squeue -a -o '%A %t' -j " + job_id
def parse_status(self, status, job_ids):
# Get status for each job, skipping header.
rval = {}
for line in status.splitlines()[1:]:
id, state = line.split()
if id in job_ids:
# map job states to Galaxy job states.
rval[id] = self._get_job_state(state)
return rval
def parse_single_status(self, status, job_id):
status = status.splitlines()
if len(status) > 1:
# Job still on cluster and has state.
id, state = status[1].split()
return self._get_job_state(state)
# else line like "slurm_load_jobs error: Invalid job id specified"
return job_states.OK
def _get_job_state(self, state):
try:
return {
'F': job_states.ERROR,
'R': job_states.RUNNING,
'CG': job_states.RUNNING,
'PD': job_states.QUEUED,
'CD': job_states.OK
}.get(state)
except KeyError:
raise KeyError("Failed to map slurm status code [%s] to job state." % state)
__all__ = ('Slurm',)
| {
"repo_name": "jmchilton/pulsar",
"path": "pulsar/managers/util/cli/job/slurm.py",
"copies": "2",
"size": "2928",
"license": "apache-2.0",
"hash": -6464207677713035000,
"line_mean": 28.8775510204,
"line_max": 92,
"alpha_frac": 0.537226776,
"autogenerated": false,
"ratio": 3.7204574332909783,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5257684209290979,
"avg_score": null,
"num_lines": null
} |
# A simple CLI runner for slurm that can be used when running Galaxy from a
# non-submit host and using a Slurm cluster.
try:
from galaxy.model import Job
job_states = Job.states
except ImportError:
# Not in Galaxy, map Galaxy job states to LWR ones.
from galaxy.util import enum
job_states = enum(RUNNING='running', OK='complete', QUEUED='queued')
from ..job import BaseJobExec
__all__ = ('Slurm',)
from logging import getLogger
log = getLogger(__name__)
argmap = {
'time': '-t',
'ncpus': '-c',
'partition': '-p'
}
class Slurm(BaseJobExec):
def __init__(self, **params):
self.params = {}
for k, v in params.items():
self.params[k] = v
def job_script_kwargs(self, ofile, efile, job_name):
scriptargs = {'-o': ofile,
'-e': efile,
'-J': job_name}
# Map arguments using argmap.
for k, v in self.params.items():
if k == 'plugin':
continue
try:
if not k.startswith('-'):
k = argmap[k]
scriptargs[k] = v
except:
log.warning('Unrecognized long argument passed to Slurm CLI plugin: %s' % k)
# Generated template.
template_scriptargs = ''
for k, v in scriptargs.items():
template_scriptargs += '#SBATCH %s %s\n' % (k, v)
return dict(headers=template_scriptargs)
def submit(self, script_file):
return 'sbatch %s' % script_file
def delete(self, job_id):
return 'scancel %s' % job_id
def get_status(self, job_ids=None):
return 'squeue -a -o \\"%A %t\\"'
def get_single_status(self, job_id):
return 'squeue -a -o \\"%A %t\\" -j ' + job_id
def parse_status(self, status, job_ids):
# Get status for each job, skipping header.
rval = {}
for line in status.splitlines()[1:]:
id, state = line.split()
if id in job_ids:
# map job states to Galaxy job states.
rval[id] = self._get_job_state(state)
return rval
def parse_single_status(self, status, job_id):
status = status.splitlines()
if len(status) > 1:
# Job still on cluster and has state.
id, state = status[1].split()
return self._get_job_state(state)
return job_states.OK
def _get_job_state(self, state):
try:
return {
'F': job_states.ERROR,
'R': job_states.RUNNING,
'CG': job_states.RUNNING,
'PD': job_states.QUEUED,
'CD': job_states.OK
}.get(state)
except KeyError:
raise KeyError("Failed to map slurm status code [%s] to job state." % state)
| {
"repo_name": "jmchilton/lwr",
"path": "lwr/managers/util/cli/job/slurm.py",
"copies": "1",
"size": "2840",
"license": "apache-2.0",
"hash": 2239649825209126000,
"line_mean": 28.8947368421,
"line_max": 92,
"alpha_frac": 0.5309859155,
"autogenerated": false,
"ratio": 3.7027379400260756,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4733723855526076,
"avg_score": null,
"num_lines": null
} |
"""A simple CLI to create Kubernetes contexts."""
import logging
import fire
import subprocess
import re
class ContextCreator:
@staticmethod
def create(project, location, cluster, name, namespace):
"""Create a context for the given GCP cluster.
Args:
project: Project that owns the cluster
location: zone or region for the cluster
cluster: Name of the cluster
name: Name to give the context
namespace: Namespace to use for the context.
"""
if re.match("[^-]+-[^-]+-[^-]", location):
location_type = "zone"
else:
location_type = "region"
subprocess.check_call(["gcloud", f"--project={project}", "container",
"clusters", "get-credentials",
f"--{location_type}={location}", cluster])
current_context = subprocess.check_output(["kubectl", "config",
"current-context"]).strip()
subprocess.check_call(["kubectl", "config", "rename-context",
current_context, name])
# Set the namespace
subprocess.check_call(["kubectl", "config", "set-context", "--current",
"--namespace={namespace}"])
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format=('%(levelname)s|%(asctime)s'
'|%(pathname)s|%(lineno)d| %(message)s'),
datefmt='%Y-%m-%dT%H:%M:%S',
)
logging.getLogger().setLevel(logging.INFO)
fire.Fire(ContextCreator)
| {
"repo_name": "kubeflow/testing",
"path": "py/kubeflow/testing/create_context.py",
"copies": "1",
"size": "1574",
"license": "apache-2.0",
"hash": -7699177333422422000,
"line_mean": 34.7727272727,
"line_max": 75,
"alpha_frac": 0.5552731893,
"autogenerated": false,
"ratio": 4.433802816901409,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5489076006201409,
"avg_score": null,
"num_lines": null
} |
""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import argparse
import json
import sys
import os
def read_emote_mappings(json_obj_files=[]):
""" Reads the contents of a list of files of json objects and combines
them into one large json object. """
super_json = {}
for fname in json_obj_files:
with open(fname) as f:
super_json.update(json.loads(f.read().decode('utf-8')))
return super_json
def parse_arguments():
parser = argparse.ArgumentParser(description=sys.modules[__name__].__doc__)
parser.add_argument('-l','--list', action="store_true",
help="List all available emotes.")
parser.add_argument('-s','--silent', action="store_true",
help="Don't print to stdout.")
parser.add_argument('--no-clipboard', action="store_false",
help="Don't copy to clipboard.")
parser.add_argument("name", type=str, nargs='?',
help="The name of the emote.")
if len(sys.argv) < 2:
parser.print_help()
sys.exit(0)
return parser.parse_args()
def list_emotes(emotes):
for k, v in emotes.iteritems():
whitespace = 30
pad = whitespace - len(k)
print "{}{}{}".format(k.encode('utf-8'), " "*pad, v.encode('utf-8'))
def print_emote(name, emotes, silent=False, clipboard=True):
try:
emote = emotes[name]
if clipboard:
pyperclip.copy(emote)
if not silent:
print emote
except KeyError:
print("That emote does not exist. You can see all existing emotes "
"with the command: `emote -l`.")
def main():
args = parse_arguments()
emote_files = [
os.path.join(os.path.dirname(__file__), 'mapping.json'),
os.path.expanduser("~/.emotes.json")
]
emotes = read_emote_mappings(emote_files)
if args.list:
list_emotes(emotes)
if args.name:
print_emote(args.name, emotes, silent=args.silent,
clipboard=args.no_clipboard)
if __name__ == "__main__":
main()
| {
"repo_name": "d6e/emotion",
"path": "emote/emote.py",
"copies": "1",
"size": "2135",
"license": "mit",
"hash": 8500093779927371000,
"line_mean": 32.359375,
"line_max": 79,
"alpha_frac": 0.5906323185,
"autogenerated": false,
"ratio": 3.5822147651006713,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9649397451614943,
"avg_score": 0.004689926397145772,
"num_lines": 64
} |
"""A simple clock program for Pimoroni's Micro Dot pHAT"""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import time
import argparse
from microdotphat import write_string, clear, show, set_rotate180, \
set_brightness, set_col, set_pixel
# Allow the user to specify settings from the command line
parser = argparse.ArgumentParser(prog='Clock',
description='A Python script to display the \
time on a Pimoroni Micro Dot pHat')
parser.add_argument('-t',
'--twelve',
action='store_true',
dest='twelve',
help='Set this switch to display a 12 hour clock \
instead of the default 24 hour clock')
parser.add_argument('-v',
'--version',
action='version',
version='%(prog)s 1.0.1',
help="Print the program's version number and exit")
args = parser.parse_args()
# Accept the user's command line input
# Clock refresh rate
s = 0.1
# Set desired brightness, from 0.0 to 1.0
b = 1.0
# Uncomment the line below to rotate the clock 180 degrees
set_rotate180(True)
# Set the brightness once
set_brightness(b)
# Code for 12 hour clock
def twelve():
"""Gets the time, adds am/pm blob and blinks the colon."""
while True:
# Set up and display the time
clear()
the_time = datetime.datetime.now()
write_string(the_time.strftime("%_I:%M"), 0, 0, kerning=False)
# Set the 'am' and 'pm' blobs
if the_time.strftime("%_H") <= "11":
for x in range(43, 45):
for y in range(0, 2):
set_pixel(x, y, 1)
else:
for x in range(43, 45):
for y in range(5, 7):
set_pixel(x, y, 1)
# Make the colon flash
if int(time.time()) % 2 == 0:
set_col(17, 0)
set_col(18, 0)
show()
time.sleep(s)
# Code for 24 hour clock
def twentyfour():
"""Gets the time and blinks the colon."""
while True:
clear()
the_time = datetime.datetime.now()
write_string(the_time.strftime(" %H:%M"), kerning=False)
# Make the colon flash
if int(time.time()) % 2 == 0:
set_col(25, 0)
set_col(26, 0)
show()
time.sleep(s)
try:
if args.twelve is True:
twelve()
else:
twentyfour()
except OSError:
exit('There has been an error. Please check all your things')
| {
"repo_name": "ncguk/Micro-Dot-pHAT-Clock",
"path": "microdotphat_clock.py",
"copies": "1",
"size": "2618",
"license": "mit",
"hash": -3849740308237600000,
"line_mean": 26.8510638298,
"line_max": 78,
"alpha_frac": 0.5351413293,
"autogenerated": false,
"ratio": 3.821897810218978,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4857039139518978,
"avg_score": null,
"num_lines": null
} |
"""A simple CL program that takes the path to a mrimap.py file and an
experiment name (see Notes) and generates all the needed subject-level
.params files.
Usage
-----
python ./sparams boldmap.py fh saveas
Notes
-----
Valid experiment names are:
- fh - the 2011 face/house data
"""
import sys
def _write_params(sid, mprage, t2, func, func_names, savename):
"""Write out a subject's .params file.
Parameters
----------
sid - the subject id (int)
mprage - a list of scan number matching the mprage data
t2 - a list of scan number matching the T2 data
func - a list of scan number matching the functional (BOLD) data
func_names - a list of names (str) giving a unique name to each scan
savename - the prefix to name the saved file ('.params' is automatically
appended).
"""
fid = open(savename+".params", "w+")
fid.write("# This .params file was autogenerated with sparams.py\n")
fid.write("\n")
fid.write("set patid = s{0}\n".format(sid))
fid.write("\n")
fid.write("#######################\n")
fid.write("# structural scan index\n")
fid.write("#######################\n")
fid.write("\n")
fid.write("set mprs = (" + " ".join(map(str, mprage)) + ")\n")
fid.write("set tse = (" + " ".join(map(str, t2)) + ")\n")
fid.write("\n")
fid.write("#################\n")
fid.write("# fMRI scan index\n")
fid.write("#################\n")
fid.write("\n")
fid.write("set fstd = (" + " ".join(map(str, func)) + ")\n")
fid.write("\t\t## fMRI study (series) number\n")
fid.write("\n")
fid.write("#################\n")
fid.write("# fMRI scan names\n")
fid.write("#################\n")
fid.write("\n")
fid.write("set irun = (" + " ".join(map(str, func_names)) + ")\n")
fid.write("\t\t## Rename counting by scan number not collection index\n")
fid.flush()
fid.close()
def main(mrimap, bolddataname, t2name, mpragename, saveas):
mrimapstr = open(mrimap).read()
mrimap = eval(mrimapstr)
for scode in mrimap.keys():
sdata = mrimap[scode]
t2_scan_numbers = sdata[t2name]
mprage_scan_numbers = sdata[mpragename]
func_scan_numbers = sdata[bolddataname]
func_names = [bolddataname+str(scan_cnt) for scan_cnt in
range(len(sdata[bolddataname]))]
## Generate functional scan names by combined bolddataname
## with the scan number
_write_params(scode,
mprage_scan_numbers,
t2_scan_numbers,
func_scan_numbers,
func_names,
"s"+str(scode) + "_" + saveas)
def _process_exp(exp):
"""Use the exp name to return the names of the t2 data, the MPRAGE data
and the bold data (in that order).
"""
if exp == "fh":
t2name = "t2"
mpragename = "mprage"
boldname = "fh"
else:
raise ValueError("exp name not understood.")
return t2name, mpragename, boldname
if __name__ == "__main__":
if len(sys.argv[1:]) != 3:
raise ValueError("Three arguments required")
mrimap = sys.argv[1]
t2name, mpragename, boldname = _process_exp(sys.argv[2])
saveas = sys.argv[3]
main(mrimap, boldname, t2name, mpragename, saveas)
| {
"repo_name": "parenthetical-e/wheelerdata",
"path": "mniconvert/archive/sparams.py",
"copies": "1",
"size": "3366",
"license": "bsd-2-clause",
"hash": 3082119564259762700,
"line_mean": 29.0625,
"line_max": 77,
"alpha_frac": 0.5603089721,
"autogenerated": false,
"ratio": 3.3592814371257487,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4419590409225748,
"avg_score": null,
"num_lines": null
} |
"""A simple command line interface.
It attempts to connect to a server, by default on the current machine
and then allows the user to enter commands"""
import cmd
import logging
import requests
# TODO: Remove this module completely
# Create Logger
LOGGER = logging.getLogger(__name__)
class CommandLineInterface(cmd.Cmd):
"""A simple implementation of a CLI"""
connection = {"url": "localhost", "port": 19113}
connection_attempts = 0
prompt = ">>> "
def preloop(self):
"""Runs before the loop. Greets the user"""
LOGGER.debug("Running the preloop-function, saying hi.")
print("\n"
" ____ _ __ __ _ _ _ _____ _ _ _ ""\n"
r" / ___| / \ | \/ | / \ | \ | |_ _| | | | / \ ""\n"
r" \___ \ / _ \ | |\/| | / _ \ | \| | | | | |_| | / _ \ ""\n"
r" ___) / ___ \| | | |/ ___ \| |\ | | | | _ |/ ___ \ ""\n"
r" |____/_/ \_\_| |_/_/ \_\_| \_| |_| |_| |_/_/ \_\ ""\n"
" hi~ ""\n"
" Starting up!\n")
self.connect()
def postloop(self):
"""Runs after the loop."""
LOGGER.debug("Running the postloop-function, saying bye.")
print("\n"
" ____ _ __ __ _ _ _ _____ _ _ _ ""\n"
r" / ___| / \ | \/ | / \ | \ | |_ _| | | | / \ ""\n"
r" \___ \ / _ \ | |\/| | / _ \ | \| | | | | |_| | / _ \ ""\n"
r" ___) / ___ \| | | |/ ___ \| |\ | | | | _ |/ ___ \ ""\n"
r" |____/_/ \_\_| |_/_/ \_\_| \_| |_| |_| |_/_/ \_\ ""\n"
" bye~ ")
def parseline(self, line):
"""Parses a line
TODO: actually send the command to the server."""
LOGGER.debug("Parsing '%s'.", line)
ret = cmd.Cmd.parseline(self, line)
try:
LOGGER.info("Attempting to send '%s' to the server.", ret)
requests.post("http://{url}:{port}/command"
.format(**self.connection),
{"key": ret[0], "params": ret[1], "comm": ret[2]})
except requests.ConnectionError:
LOGGER.exception("Connection lost.")
print "Connection lost."
self.connection_error()
return ("exit", "", "exit")
print "processing " + str(ret)
return ret
def emptyline(self):
pass
def default(self, line):
pass
def precmd(self, line):
LOGGER.debug("Running the precmd-function")
return cmd.Cmd.precmd(self, line)
def postcmd(self, stop, line):
LOGGER.debug("Running the postcmd-function")
return cmd.Cmd.postcmd(self, stop, line)
def do_EOF(self, line):
"""Exit the interface"""
return self.do_exit(line)
def do_exit(self, line):
"""Exit the interface"""
LOGGER.info("Received the command '%s'. Exiting", line)
return True
def connect(self):
"""attept connecting to an instance of Samantha"""
LOGGER.info("Attempting to connect to 'http://%(url)s:%(port)s'",
self.connection)
print("Attempting to connect to 'http://{url}:{port}'"
.format(**self.connection))
try:
requests.get("http://{url}:{port}/status"
.format(**self.connection))
self.connection_attempts = 0
LOGGER.info("Connection successful. "
"Connection-attempts reset to 0.")
print "Connection available."
except requests.ConnectionError:
LOGGER.exception("Could not connect!")
self.connection_error()
def connection_error(self):
"""Handle a failed connection. The program will abort after 3
failed attempts to the same server."""
self.connection_attempts += 1
if self.connection_attempts >= 3:
LOGGER.fatal("Couldn't connect 3 times in a row. Exiting.")
print "The connection failed 3 times in a row. Exiting."
self.postloop()
exit()
LOGGER.info("Connection failed. Attempt(%d/3)",
self.connection_attempts)
print("The Connection to 'http://{url}:{port}/status' failed."
.format(**self.connection))
LOGGER.debug("Requiring userinput whether to try starting the server "
"manually.")
var = raw_input("Try to start the server remotely? (y/n) \n>>> ")
LOGGER.debug("Userinput was '%s'.", var)
while var not in ["y", "n"]:
var = raw_input("Please use 'y' for yes or 'n' for no. \n>>> ")
if var == "y":
LOGGER.info("Attempting to start the Server remotely.")
# TODO Start the server remotely
elif var == "n":
LOGGER.debug("Requiring userinput whether to change the server's "
"address.")
var = raw_input("Enter a new host? (y/n) \n>>> ")
LOGGER.debug("Userinput was '%s'.", var)
while var not in ["y", "n"]:
var = raw_input(
"Please use 'y' for yes or 'n' for no. \n>>> ")
if var == "y":
self.connection_attempts = 0
self.connection["url"] = raw_input(
"Please enter the new host: ")
LOGGER.info("Address changed to '%s'. Connection-attempts "
"reset to 0", self.connection["url"])
LOGGER.info("Attempting to reconnect.")
self.connect()
def start():
"""Starts the interface"""
CommandLineInterface().cmdloop("Please enter your command:")
if __name__ == "__main__":
print ("This application is not meant to be executed on its own. To start "
"it, please run '__main__.py' in it's parent directory, or the cli-"
"command 'python interface' in the directory above (that should be "
"'/PersonalAssistant_Interfaces').\n")
var = raw_input("Press the enter-key to exit.\n")
| {
"repo_name": "Sirs0ri/PersonalAssistant_Interfaces",
"path": "interface/simple_cli/__init__.py",
"copies": "1",
"size": "6234",
"license": "mit",
"hash": -2969702089134548000,
"line_mean": 40.0131578947,
"line_max": 79,
"alpha_frac": 0.4767404556,
"autogenerated": false,
"ratio": 3.8720496894409937,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9847160637243723,
"avg_score": 0.000325901559454191,
"num_lines": 152
} |
"""A simple command line SRT convertor tool. Apply shift and factor to SRT timings."""
__author__ = "Gerard van Helden <drm@melp.n>"
import re
import sys
import argparse
class TimeParseError:
'Thrown whenever a parse error occurs in Time.parse'
def __init__(self, msg, time):
self._msg = msg
self._time = time
def __str__(self):
return "%s (%s)" % (self._msg, self._time)
class Time:
'''A Time abstraction class, mapping time values to milliseconds internally and representing it
as strings. The class implements adding, substracting, multiplication and division through
arithmetic operators'''
_HOURS = 3600000
_MINS = 60000
_SECS = 1000
_MSECS = 1
PARTS = {
'h': _HOURS,
'm': _MINS,
's': _SECS,
'ms': _MSECS
}
PARTS_V = PARTS.values()
PARTS_V.sort(reverse=True)
RE_TIME = re.compile(r'(\d{1,2}):(\d{1,2}):(\d{1,2}),(\d+)')
RE_OFFSET = re.compile(r'^-?(\d+)(ms|[hms])-?')
@classmethod
def parse(cls, time):
"""Parses a string representation of time and returns a Time instance. Valid formats are:
- 01:02:03,004
1 hour, 2 minutes, 3 seconds and 4 milliseconds
- 1h2m3s4ms
Same value
Any combination of 'h', 'm', 's', or 'ms' suffixed values. Values prefixed or suffixed by a dash are
considered negative values."""
time = str(time)
offs = cls.RE_OFFSET.match(time)
if offs:
mapping = cls.PARTS
negative = time[0] == "-" or time[-1] == "-"
msecs = 0
while offs:
if offs.group(2) in mapping:
msecs += mapping[offs.group(2)] * float(offs.group(1))
else:
msecs += mapping['s'] * float(offs.group(1))
time = time[len(offs.group(0)):]
if len(time):
offs = cls.RE_OFFSET.match(time)
else:
offs = False
if negative:
msecs = -msecs
else:
try:
t = map(int, cls.RE_TIME.match(time).group(1, 2, 3, 4))
except AttributeError:
raise TimeParseError("Invalid format, could not parse", time)
msecs = 0
for i, v in enumerate(cls.PARTS_V):
msecs += v * t[i]
return Time(msecs)
def __init__(self, ms):
self.ms = int(ms)
self._ms = None
def __str__(self):
ret = ""
if self.ms < 0:
ret += "-"
ret += ":".join(map(lambda d: "%02d" % abs(d), self._asdict().values()[0:3]))
ret += ',%03d' % abs(self._asdict()[self._MSECS])
return ret
def __int__(self):
return self.ms
def __add__(self, ms):
if isinstance(ms, str):
ms = Time.parse(ms)
if isinstance(ms, Time):
ms = ms.ms
return Time(self.ms + int(ms))
def __mul__(self, factor):
return Time(self.ms * factor)
def _asdict(self):
if None == self.ms or self.ms != self._ms:
self._ms = self.ms
self._d = {}
rest = abs(self.ms)
for i in Time.PARTS_V:
self._d[i] = int(rest / i)
if self._ms < 0:
self._d[i] *= -1
rest %= i
return self._d
class Span:
SEP = " --> "
@classmethod
def parse(cls, line):
return Span(*map(Time.parse, map(str.strip, line.split(cls.SEP))))
def __init__(self, stime, etime):
self.stime = stime
self.etime = etime
def __str__(self):
return Span.SEP.join(map(str, (self.stime, self.etime)))
def __add__(self, time):
return Span(self.stime + time, self.etime + time)
def __mul__(self, factor):
return Span(self.stime * factor, self.etime * factor)
class Entry:
RE_NUMBER = re.compile(r'^\d+$')
@classmethod
def group_lines(cls, lines):
group = []
index = 0
for line in lines:
m = cls.RE_NUMBER.match(line)
if m:
if len(group) > 0:
yield (index, group)
group = []
index = int(m.group(0))
else:
group.append(line)
if len(group):
yield (index, group)
def __init__(self, index, span, data):
self.index = index
self.span = span
self.data = data
def __str__(self):
return "\r\n".join([
str(self.index),
str(self.span),
str(self.data)
]) + "\r\n"
def __add__(self, ms):
return Entry(self.index, self.span + ms, self.data)
def __mul__(self, factor):
return Entry(self.index, self.span * factor, self.data)
class EntryList:
@classmethod
def parse(cls, lines):
ret = cls()
for i, entry in Entry.group_lines(map(str.strip, lines)):
ret.append(Entry(i, Span.parse(entry[0]), "\r\n".join(entry[1:])))
return ret
def __init__(self):
self.entries = {}
def append(self, entry):
self.entries[entry.index]=entry
def __iter__(self):
return iter(self.entries)
def __getitem__(self, index):
return self.entries[index]
def __add__(self, time):
ret = EntryList()
for i in self.entries:
ret.append(self.entries[i] + time)
return ret
def __mul__(self, factor):
ret = EntryList()
for i in self.entries:
ret.append(self.entries[i] * factor)
return ret
def __str__(self):
return "".join(map(str, self.entries.values()))
def main():
parser = argparse.ArgumentParser(description="Fix an SRT file's timings")
parser.add_argument(
'-i',
dest='input',
metavar="INPUT",
type=str,
nargs=1,
default='-',
help="Input file (omit for stdin)"
)
parser.add_argument(
'-o',
dest='output',
metavar="OUTPUT",
type=str,
nargs=1,
default='-',
help="Output file (omit for stdout)"
)
parser.add_argument(
'-s',
dest='shift',
type=str,
nargs=1,
default=0,
help="Shift the subtitles by number of hours, minutes, seconds or milliseconds. The format is either hh:mm:ss,ms or 01h02m03s04ms, whereas the latter can be provided in any combination. A minus can be appended to do a negative shift"
)
parser.add_argument(
'-f',
dest='convert_framerate',
type=str,
nargs=1,
default=1.0,
help="Apply framerate conversion. Format is -f 25/24 or -f 0.9"
)
o = parser.parse_args()
if o.input[0] == '-':
ifile = sys.stdin
else:
ifile = open(o.input[0], 'r')
if o.output[0] == '-':
ofile = sys.stdout
else:
ofile = open(o.output[0], 'w')
data = EntryList.parse(iter(ifile))
if o.shift:
data += o.shift[0]
if o.convert_framerate:
try:
(iframes, oframes) = map(float, o.convert_framerate[0].split('/'))
o.convert_framerate = iframes/oframes
except:
pass
data *= float(o.convert_framerate)
ofile.write(str(data))
if __name__ == "__main__":
main()
| {
"repo_name": "drm/srtfix.py",
"path": "srtfix.py",
"copies": "1",
"size": "7649",
"license": "mit",
"hash": -9129723328593208000,
"line_mean": 26.8145454545,
"line_max": 241,
"alpha_frac": 0.4957510786,
"autogenerated": false,
"ratio": 3.7077072224915173,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47034583010915176,
"avg_score": null,
"num_lines": null
} |
"""A simple completer for the qtconsole"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012, IPython Development Team.$
#
# Distributed under the terms of the Modified BSD License.$
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------------------------
# System library imports
from IPython.external.qt import QtCore, QtGui
import IPython.utils.text as text
class CompletionPlain(QtGui.QWidget):
""" A widget for tab completion, navigable by arrow keys """
#--------------------------------------------------------------------------
# 'QObject' interface
#--------------------------------------------------------------------------
def __init__(self, console_widget):
""" Create a completion widget that is attached to the specified Qt
text edit widget.
"""
assert isinstance(console_widget._control, (QtGui.QTextEdit, QtGui.QPlainTextEdit))
super(CompletionPlain, self).__init__()
self._text_edit = console_widget._control
self._console_widget = console_widget
self._text_edit.installEventFilter(self)
def eventFilter(self, obj, event):
""" Reimplemented to handle keyboard input and to auto-hide when the
text edit loses focus.
"""
if obj == self._text_edit:
etype = event.type()
if etype in( QtCore.QEvent.KeyPress, QtCore.QEvent.FocusOut ):
self.cancel_completion()
return super(CompletionPlain, self).eventFilter(obj, event)
#--------------------------------------------------------------------------
# 'CompletionPlain' interface
#--------------------------------------------------------------------------
def cancel_completion(self):
"""Cancel the completion, reseting internal variable, clearing buffer """
self._console_widget._clear_temporary_buffer()
def show_items(self, cursor, items):
""" Shows the completion widget with 'items' at the position specified
by 'cursor'.
"""
if not items :
return
self.cancel_completion()
strng = text.columnize(items)
self._console_widget._fill_temporary_buffer(cursor, strng, html=False)
| {
"repo_name": "initNirvana/Easyphotos",
"path": "env/lib/python3.4/site-packages/IPython/qt/console/completion_plain.py",
"copies": "12",
"size": "2362",
"license": "mit",
"hash": -5489927382213950000,
"line_mean": 37.0967741935,
"line_max": 91,
"alpha_frac": 0.5207451312,
"autogenerated": false,
"ratio": 5.202643171806168,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0033561963453533025,
"num_lines": 62
} |
"""A simple completer for the qtconsole"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from qtpy import QtCore, QtGui, QtWidgets
import ipython_genutils.text as text
class CompletionPlain(QtWidgets.QWidget):
""" A widget for tab completion, navigable by arrow keys """
#--------------------------------------------------------------------------
# 'QObject' interface
#--------------------------------------------------------------------------
def __init__(self, console_widget):
""" Create a completion widget that is attached to the specified Qt
text edit widget.
"""
assert isinstance(console_widget._control, (QtWidgets.QTextEdit, QtWidgets.QPlainTextEdit))
super(CompletionPlain, self).__init__()
self._text_edit = console_widget._control
self._console_widget = console_widget
self._text_edit.installEventFilter(self)
def eventFilter(self, obj, event):
""" Reimplemented to handle keyboard input and to auto-hide when the
text edit loses focus.
"""
if obj == self._text_edit:
etype = event.type()
if etype in( QtCore.QEvent.KeyPress, QtCore.QEvent.FocusOut ):
self.cancel_completion()
return super(CompletionPlain, self).eventFilter(obj, event)
#--------------------------------------------------------------------------
# 'CompletionPlain' interface
#--------------------------------------------------------------------------
def cancel_completion(self):
"""Cancel the completion, reseting internal variable, clearing buffer """
self._console_widget._clear_temporary_buffer()
def show_items(self, cursor, items, prefix_length=0):
""" Shows the completion widget with 'items' at the position specified
by 'cursor'.
"""
if not items :
return
self.cancel_completion()
strng = text.columnize(items)
# Move cursor to start of the prefix to replace it
# when a item is selected
cursor.movePosition(QtGui.QTextCursor.Left, n=prefix_length)
self._console_widget._fill_temporary_buffer(cursor, strng, html=False)
| {
"repo_name": "sserrot/champion_relationships",
"path": "venv/Lib/site-packages/qtconsole/completion_plain.py",
"copies": "1",
"size": "2289",
"license": "mit",
"hash": -4263386089636586000,
"line_mean": 37.15,
"line_max": 99,
"alpha_frac": 0.5578855395,
"autogenerated": false,
"ratio": 4.901498929336189,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.595938446883619,
"avg_score": null,
"num_lines": null
} |
"""A simple counter with App Engine pull queue."""
import logging
import os
import time
import jinja2
import webapp2
from google.appengine.api import taskqueue
from google.appengine.ext import ndb
from google.appengine.runtime import apiproxy_errors
JINJA_ENV = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
class Counter(ndb.Model):
count = ndb.IntegerProperty(indexed=False)
class CounterHandler(webapp2.RequestHandler):
def get(self):
template_values = {'counters': Counter.query()}
counter_template = JINJA_ENV.get_template('counter.html')
self.response.out.write(counter_template.render(template_values))
def post(self):
key = self.request.get('key')
if key:
q = taskqueue.Queue('pullq')
q.add(taskqueue.Task(payload='', method='PULL', tag=key))
self.redirect('/')
class CounterWorker(webapp2.RequestHandler):
def get(self):
"""Indefinitely fetch tasks and update the datastore."""
q = taskqueue.Queue('pullq')
while True:
try:
tasks = q.lease_tasks_by_tag(3600, 1000, deadline=60)
except (taskqueue.TransientError,
apiproxy_errors.DeadlineExceededError) as e:
logging.exception(e)
time.sleep(1)
continue
if tasks:
key = tasks[0].tag
@ndb.transactional
def update_counter():
counter = Counter.get_or_insert(key, count=0)
counter.count += len(tasks)
counter.put()
try:
update_counter()
except Exception as e:
logging.exception(e)
else:
q.delete_tasks(tasks)
time.sleep(1)
APP = webapp2.WSGIApplication(
[
('/', CounterHandler),
('/_ah/start', CounterWorker)
], debug=True)
| {
"repo_name": "GoogleCloudPlatform/appengine-pullqueue-counter",
"path": "main.py",
"copies": "1",
"size": "2012",
"license": "apache-2.0",
"hash": 3008660511240462300,
"line_mean": 28.1594202899,
"line_max": 73,
"alpha_frac": 0.5730616302,
"autogenerated": false,
"ratio": 4.218029350104822,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5291090980304822,
"avg_score": null,
"num_lines": null
} |
#A simple counting sort - probablythe cleanest solution I ever wrote!
#Does not take into account stability and order.
#No array checking yet for integer type.
#Assuming incoming array is strictly an integer array/list
#NOTE: LAST CHECKED - This implementation beats python's out of place sorted()
# for integer sorting. Perhaps this implementation using radix sort beats
# general numeral sorting vs. sorted() in general.
def store(alist):
"""increment counter in a counter array for every integer encountered"""
klist = [0] * (max(alist)+1) #O(n)
#O(n)
for i in alist:
klist[i] += 1
return klist
def execute(klist):
"""create a list and extend every encountered indexin a list by the count"""
output = []
for l in xrange(len(klist)):
if klist[l]:
output += [l]*klist[l]
return output
def execute_clr(alist, klist):
"""you dont wana know. inplace klist manipulation. creates new sorted list."""
output = [0] * len(alist)
sm = 0
#update klist according to the wierd logic
for index in xrange(len(klist)):
klist[index] += sm
sm = klist[index]
for index in xrange(len(alist)-1, -1, -1):
a_index = alist[index]
klist[a_index] -= 1
kval = klist[a_index]
output[kval] = a_index
return output
def count_int_sort(alist):
"""Sort an integer array using counting sort"""
return execute(store(alist)) #O(len(klist))
def count_int_clr_sort(alist):
"""Sort an integer array using weird counting sort logic"""
return execute_clr(alist, store(alist))
#quick profiling test
if __name__ == "__main__":
from cProfile import run
from numpy.random import randint
x = randint(0, 30000000, 1000000)
run("count_int_clr_sort(x)")
run("x.sort()") | {
"repo_name": "codecakes/random_games",
"path": "counting_sort.py",
"copies": "1",
"size": "1830",
"license": "mit",
"hash": -7673593203770854000,
"line_mean": 29.5166666667,
"line_max": 82,
"alpha_frac": 0.6453551913,
"autogenerated": false,
"ratio": 3.5812133072407044,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4726568498540704,
"avg_score": null,
"num_lines": null
} |
"""A simple crawler."""
import os
import sys
import urllib2
import urlparse
import socket # to catch any socket.timeout exceptions read() might throw
import sys # to get the sys.stdout handle
import pickle
# modules I've written:
from html_parser import SimpleHTMLParser
PAGE_SIZE = 40000
class OutOfUrlsError(Exception):
"""Custom exception raised when the set of urls to crawl is empty."""
def __init__(self):
pass
def __str__(self):
return 'The set of urls to crawl is empty!'
class Crawler:
"""A simple crawler."""
def __init__(self, num_pages=None, min_page_size=None, seeds=None):
"""Initialize an object."""
self._to_crawl = set([]) # urls to crawl
self._crawled = set([]) # urls of crawled pages
self._url = [] # urls of saved pages
# number of pages to download:
if num_pages is not None:
self._num_pages = num_pages
else:
self._num_pages = 1000
# minimum page size (in characters)
if min_page_size is not None:
self._min_page_size = min_page_size
else:
self._min_page_size = 40000
# initial crawl frontier
if seeds is not None:
self._seeds = set(seeds)
else:
self._seeds = \
set(['http://www.brighthub.com/',
'http://www.physicscentral.com/',
'http://www.candlelightstories.com/',
'http://www.anandtech.com/',
'http://www.cnet.com/'])
def reset(self):
self.__init__()
def crawl(self):
"""
Find and save 'self._num_pages' html pages, each at least
'self._min_page_size' characters long.
seeds (list): start crawling from these urls
"""
# open './log.txt'
try:
log = open('./log.txt', 'w')
except Exception:
print "Couldn't open log.txt. All output will go to the screen."
log = sys.stdout
# set the crawler's seeds
self._to_crawl = set(self._seeds)
# make a directory to save the pages in
os.mkdir('./html')
# create a parser (to get each page's links)
parser = SimpleHTMLParser()
# start gathering pages
try:
while len(self._url) < self._num_pages:
try:
crawling = self._to_crawl.pop()
print >>log, crawling
except KeyError as e:
# out of urls
raise OutOfUrlsError
url = urlparse.urlsplit(crawling)
try:
page_handle = urllib2.urlopen(crawling, timeout=2)
except:
print >>log, ' exception while opening!'
continue
if page_handle.getcode() > 399:
# got an HTTP error code, continue to the next link
print >>log, ' got HTTP error code!'
continue
# check url in case there was a redirection and we ended up on
# a forbidden page
if is_no_go_link(urlparse.urlsplit(page_handle.geturl())):
print >>log, ' redirected to forbidden page!'
continue
# add 'crawling' to the set of all crawled urls
self._crawled.add(crawling)
# add page_handle.geturl() too in case we were redirected
self._crawled.add(page_handle.geturl())
# read page text
try:
page_html = page_handle.read()
except socket.timeout:
print >>log, ' socket timeout!'
continue
except Exception:
print >>log, ' problem during page_handle.read()!'
continue
# parse the page
parser.reset()
try:
parser.parse(page_html)
except Exception as e:
print >>log, ' parser exception! --- ' + str(e)
continue
# extract hyperlinks
extract_new_links(url, parser.get_hyperlinks(), self._to_crawl,
self._crawled)
# do the checks (at least 'self._min_page_size' chars, english, etc.)
ok = self._check_page(page_handle, len(page_html))
if ok:
# give the page an id and save it
# the page's position in the _url list will be it's id
self._url.append(crawling)
save_page(page_html, len(self._url) - 1)
# print the number of pages gathered so far
print str(len(self._url)) + ' pages'
else:
print >>log, ' page not ok!'
page_handle.close()
except KeyboardInterrupt:
# remember that the while loop was in this try-except block
# did this to close the log file if an ctrl-c was pressed
if log is not sys.stdout:
log.close()
return False
# if everything went well close the log file and exit True
if log is not sys.stdout:
log.close()
return True
def get_crawl_frontier(self):
"""Get the crawl frontier - links about to be crawled."""
return self._to_crawl
def get_crawled_links(self):
"""Get all the crawled links."""
return self._crawled
def get_page_urls(self):
"""Get the list mapping ids to page urls."""
return self._url
def get_seeds(self):
"""Get the seeds - the links to start crawling from."""
return self._seeds
def set_seeds(self, seeds):
"""Set a list of seeds - links to start crawling from."""
self._seeds = seeds
return True
def dump_ids_and_urls(self):
"""
Export self._url as 'urls.pickle' using pickle. Also create a text
file, 'ids_and_urls.txt', mapping page ids to urls.
"""
with open('urls.pickle', 'w') as f:
pickle.dump(self._url, f)
with open('ids_and_urls.txt', 'w') as f:
for id, url in enumerate(self._url):
f.write('%-5s %s\n' % (id, url))
def _check_page(self, page_handle, page_length):
"""
Return True if the downloaded page is at least 'self._min_page_size'
characters long, pure html, in english and can be stored,
False otherwise.
page_handle: the handle urllib2.urlopen() returns
page_length: the page's length in characters
"""
# are we allowed to store the page?
try:
if 'no-store' in page_handle.headers.dict['cache-control']:
return False
except KeyError:
pass
# is the page over self._min_page_size characters long?
if page_length < self._min_page_size:
return False
# is the page pure html?
if page_handle.info().type != 'text/html':
return False
# is the page in english?
try:
if page_handle.info().dict['content-language'][0:2] != 'en':
return False
except KeyError:
pass
return True
def save_page(page_html, page_id):
"""
Save the downloaded page on the local file ./html/'page_id'.html.
page_html (string) : the page's html
page_id (int) : the id we gave the page
"""
with open('./html/' + str(page_id) + '.html', 'w') as f:
f.write(page_html)
return True
def extract_new_links(url, links, to_crawl, crawled):
"""
Add all links in 'links' (except those in 'crawled') into 'to_crawl'.
Before adding a link check if it's acceptable.
url (like a list) : the current page's split url
links (list) : a list of the extracted links
to_crawl (set) : links not yet crawled
crawled (set) : links already crawled
"""
for link in links:
# print >>log, 'found link: ' + link
try:
linkurl = urlparse.urlsplit(link.lower())
except Exception:
continue
if is_no_go_link(linkurl):
continue
elif not linkurl[1]:
if link.startswith('/'):
link = 'http://' + url[1] + link
else:
link = 'http://' + url[1] + '/' + link
elif not linkurl[0]:
link = 'http://' + link
if link not in crawled:
to_crawl.add(link)
return True
def is_no_go_link(linkurl):
"""
Return True if the link must be avoided (e.g. a 'mailto:' or '.gov' link).
linkurl (like list) : the split link
"""
# block links starting with 'ftp://', 'mailto:' etc.
if linkurl[0] and not linkurl[0] == 'http':
return True
# block anchor urls
if not linkurl[1] and not linkurl[2]:
return True
# block domains other than '.com'
if linkurl[1]:
if not linkurl[1].endswith('.com') and \
not linkurl[1].endswith('.co.uk'):
return True
# block '.gov' domains (if anyone passed the previous tests)
if '.gov' in linkurl[1]:
return True
# block wikipedia, twitter and facebook
if 'twitter.com' in linkurl[1] or \
'facebook.com' in linkurl[1] or \
'wikipedia' in linkurl[1] or \
'imdb' in linkurl[1]:
return True
# only allow html pages
if linkurl[2]:
if not linkurl[2].endswith('.html') and \
not linkurl[2].endswith('.htm') and \
not linkurl[2].endswith('/'):
return True
return False
def main():
"""Download 1000 html pages into './html/'."""
c = Crawler()
status = c.crawl()
c.dump_ids_and_urls()
return status
if __name__ == '__main__':
status = main()
sys.exit(status)
| {
"repo_name": "nitsas/simple-web-search-engine",
"path": "crawler.py",
"copies": "1",
"size": "10379",
"license": "mit",
"hash": 8569786264207396000,
"line_mean": 34.0641891892,
"line_max": 85,
"alpha_frac": 0.5095866654,
"autogenerated": false,
"ratio": 4.207134171057965,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5216720836457965,
"avg_score": null,
"num_lines": null
} |
"""A simple CSS progress bar to be rendered in the IPython Notebook.
"""
#-----------------------------------------------------------------------------
# Authors: Ruaridh Thomson <echelous@me.com>
# License: MIT License
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import uuid
import struct
import seaborn as sns
from IPython.display import HTML, Javascript, display
#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------
HTML_TEMPLATE = """
<style>
/*
* Copyright (c) 2012-2013 Thibaut Courouble
* http://www.cssflow.com
*
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* View the Sass/SCSS source at:
* http://www.cssflow.com/snippets/animated-progress-bar/demo/scss
*
* Original PSD by Vin Thomas: http://goo.gl/n1M2e
*/
.contanya {
margin: 10px auto;
width: auto;
text-align: center;
}
.contanya .progress-%s {
margin: 0 5% auto;
width: auto;
}
.progress-%s {
padding: 4px;
background: rgba(0, 0, 0, 0.25);
color: rgba(0, 0, 0, 0.5);
border-radius: 6px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.25), 0 1px rgba(255, 255, 255, 0.08);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.25), 0 1px rgba(255, 255, 255, 0.08);
}
.progress-bar-%s {
height: 16px;
border-radius: 4px;
background-image: -webkit-linear-gradient(top, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.05));
background-image: -moz-linear-gradient(top, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.05));
background-image: -o-linear-gradient(top, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.05));
background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.05));
-webkit-transition: 0.4s linear;
-moz-transition: 0.4s linear;
-o-transition: 0.4s linear;
transition: 0.4s linear;
-webkit-transition-property: width, background-color;
-moz-transition-property: width, background-color;
-o-transition-property: width, background-color;
transition-property: width, background-color;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.25), inset 0 1px rgba(255, 255, 255, 0.1);
box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.25), inset 0 1px rgba(255, 255, 255, 0.1);
}
.progress-%s > .progress-bar-%s {
width: 10%;
background-color: #fee493;
}
</style>
<div class="contanya">
<div class="progress-%s">
<div id="progress-bar-%s" class="progress-bar-%s"></div>
</div>
</div>
"""
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
class SimpleColorProgressBar(object):
""" SimpleColorBar creates and renders a simple, yet pretty, progress bar
that is easy to use.
Parameters
----------
color_palette : String
Name of the color palette to be used for the bar. Any palette available
in Seaborn or matplotlib can be used.
num_iterations : int
The number of iterations that the progressbar is tracking.
Examples
--------
>>> pb = SimpleColorProgressBar(color_palette='winter', num_iterations=100)
>>> for i in range(100):
... time.sleep(0.1)
... pb.update()
"""
def __init__(self, color_palette='RdYlGn', num_iterations=100):
self.colors = self._get_color_palette(name=color_palette)
self.num_iterations = num_iterations
self.update_weight = 100.0 / num_iterations
self.loop_count = 0
self.prev_update_count = 0
self._setup_progress_bar()
def _setup_progress_bar(self):
"""
Setup the HTML, CSS and JS content of the progress bar and display it in
the notebook.
"""
self.divid = str(uuid.uuid4())
html_body = HTML_TEMPLATE.replace('%s', self.divid)
pb = HTML(html_body)
display(pb)
def _get_color_palette(self, name='RdYlGn', n_colors=100):
"""
A bit of information telling us what this function does. Example
parameter and return decriptions below.
Parameters
----------
name : String, default 'RdYlGn'
Name of the color palette to be loaded.
n_colors : int, default 100
Number of colours to be loaded into the palette.
Returns
-------
palette_strings : list
"""
palette = sns.color_palette(name=name, n_colors=n_colors)
palette_strings = []
for r, g, b in palette:
r_val = r * 255.0
g_val = g * 255.0
b_val = b * 255.0
colour_string = struct.pack('BBB', r_val,
g_val, b_val).encode('hex')
palette_strings.append(colour_string)
return palette_strings
def update(self):
"""
Update the progress bar, taking into account the current loop count.
"""
update_count = int(self.loop_count * self.update_weight)
if self.loop_count == self.num_iterations-1:
update_count = 99
self.loop_count += 1
#update_string = str(update_count) + ' / ' + str(self.num_iterations)
js_string = """
var progbar = document.querySelector(".progress-%s > .progress-bar-%s");
progbar.style.width = "%i%%";
progbar.style.backgroundColor = "#%s";
""" % (self.divid, self.divid, update_count+1,
self.colors[update_count])
if update_count > self.prev_update_count:
display(Javascript(js_string))
self.prev_update_count = update_count
| {
"repo_name": "ruaridht/visualprogressbar",
"path": "visualprogressbar/simple_color_progressbar.py",
"copies": "1",
"size": "6028",
"license": "mit",
"hash": -22467947726803204,
"line_mean": 31.2352941176,
"line_max": 104,
"alpha_frac": 0.5359986729,
"autogenerated": false,
"ratio": 3.7027027027027026,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47387013756027024,
"avg_score": null,
"num_lines": null
} |
"""A simple ctypes Wrapper of FlyCapture2_C API. Currently this only works with
graysale cameras in MONO8 or MONO16 pixel format modes.
Use it as follows:
>>> c = Camera()
First you must initialize.. To capture in MONO8 mode and in full resolution
run
>>> c.init() #default to MONO8
Init also turns off all auto features (shutter, exposure, gain..) automatically.
It sets brigtness level to zero and no gamma and sharpness adjustment (for true raw image capture).
If MONO16 is to be used run:
>>> c.init(pixel_format = FC2_PIXEL_FORMAT_MONO16)
To set ROI (crop mode) do
>>> c.init(shape = (256,256)) #crop 256x256 image located around the sensor center.
Additionaly you can specify offset of the cropped image (from the top left corner)
>>> c.init(shape = (256,256), offset = (10,20))
shape and offset default to (None,None), which means that x and y dimensions and offset
are determined automaticaly and default to max image width and height and with offset
set so that crop is made around the sensor center.
So, you can set one of the dimensions in shape to None, which will result in
a full resolution capture in that dimension. To capture a full width horizontal strip
of height 100 pixels located around the sensor center do
>>> c.init(shape = (None,100))
To capture a 256x256 frame located in the center in horizontal direction and at top
in the vertical direction do
>>> c.init(shape = (256,256), offset = (None,0))
Now we can set some parameters.
>>> c.set_shutter(12.) #approx 12 ms
>>> c.get_shutter() #camera actually uses slightly different value
11.979341506958008
>>> c.set_gain(0.) #0dB
>>> c.get_gain()
0.0
Same can be done with (Absolute mode)
>>> c.set_parameter("shutter", 12.)
Or in integer mode
>>> c.set_parameter("shutter", value_int = 285)
>>> c.get_parameter("shutter")
{'value_int': 285L, 'auto': False, 'value': 11.979341506958008, 'on': True}
To capture image just call
>>> im = c.capture()
Actual image data (numpy array) is storred in converted_image attribute...
>>> im is c.converted_image
True
You can use numpy or opencv to save image to file, or use FlyCamera API to do it.
File type is guessed from extensiion..
>>> c.save_raw("raw.pgm") #saves raw image data (that has not yet been converted to numpy array)
>>> c.save_image("converted.pgm") #saves converted image data (that has been converted to numpy array)
These two images should be identical for grayscale cameras
>>> import cv2
>>> raw = cv2.imread("raw.pgm",cv2.IMREAD_GRAYSCALE)
>>> converted = cv2.imread("converted.pgm",cv2.IMREAD_GRAYSCALE)
>>> np.allclose(raw,converted)
True
save_raw, converts raw data to a given file format. To dump true raw data to file use:
>>> c.save_raw("raw.raw") #".raw" extension is meant for true raw data write.
>>> import numpy as np
>>> true_raw = np.fromfile("raw.raw",dtype = "uint8")
>>> np.allclose(true_raw, raw.flatten())
True
To capture video do:
>>> c.set_frame_rate(10.) #10 fps
Then you need to call the video() method. This method returns a generator (for speed).
So you need to iterate over images and do copying if you need to push frames into memory.
To create a list of frames (numpy arrays) do
>>> [(t,im.copy()) for t,im in c.video(10, timestamp = True)] #create a list of 10 frames video with timestamp
You should close when done:
>>> c.close()
"""
from ctypes import *
import logging as logger
import platform,os
import numpy as np
import warnings
import time
import cv2
from camera.base_camera import BaseCamera
#logger.basicConfig(level = logger.DEBUG)
logger.basicConfig(level = logger.INFO)
if platform.architecture()[0] == '64bit':
LIBNAME = 'FlyCapture2_C'
else:
LIBNAME = 'FlyCapture2_C'
flylib = cdll.LoadLibrary(LIBNAME)
#constants from #defines and enum constants inFlyCapture2Defs_C.h
FC2_ERROR_OK = 0
MAX_STRING_LENGTH = 512
FULL_32BIT_VALUE = 0x7FFFFFFF
#fc2ImageFileFormat enum
FC2_FROM_FILE_EXT = -1#, /**< Determine file format from file extension. */
FC2_PGM = 0#, /**< Portable gray map. */
FC2_PPM = 1#, /**< Portable pixmap. */
FC2_BMP = 2#, /**< Bitmap. */
FC2_JPEG = 3#, /**< JPEG. */
FC2_JPEG2000 = 4#, /**< JPEG 2000. */
FC2_TIFF = 5#, /**< Tagged image file format. */
FC2_PNG = 6#, /**< Portable network graphics. */
FC2_RAW = 7 #, /**< Raw data. */
FC2_IMAGE_FILE_FORMAT_FORCE_32BITS = FULL_32BIT_VALUE
#fc2PixelFormat enums
FC2_PIXEL_FORMAT_MONO8 = 0x80000000#, /**< 8 bits of mono information. */
FC2_PIXEL_FORMAT_411YUV8 = 0x40000000#, /**< YUV 4:1:1. */
FC2_PIXEL_FORMAT_422YUV8 = 0x20000000#, /**< YUV 4:2:2. */
FC2_PIXEL_FORMAT_444YUV8 = 0x10000000#, /**< YUV 4:4:4. */
FC2_PIXEL_FORMAT_RGB8 = 0x08000000#, /**< R = G = B = 8 bits. */
FC2_PIXEL_FORMAT_MONO16 = 0x04000000#, /**< 16 bits of mono information. */
FC2_PIXEL_FORMAT_RGB16 = 0x02000000#, /**< R = G = B = 16 bits. */
FC2_PIXEL_FORMAT_S_MONO16 = 0x01000000#, /**< 16 bits of signed mono information. */
FC2_PIXEL_FORMAT_S_RGB16 = 0x00800000#, /**< R = G = B = 16 bits signed. */
FC2_PIXEL_FORMAT_RAW8 = 0x00400000#, /**< 8 bit raw data output of sensor. */
FC2_PIXEL_FORMAT_RAW16 = 0x00200000#, /**< 16 bit raw data output of sensor. */
FC2_PIXEL_FORMAT_MONO12 = 0x00100000#, /**< 12 bits of mono information. */
FC2_PIXEL_FORMAT_RAW12 = 0x00080000#, /**< 12 bit raw data output of sensor. */
FC2_PIXEL_FORMAT_BGR = 0x80000008#, /**< 24 bit BGR. */
FC2_PIXEL_FORMAT_BGRU = 0x40000008#, /**< 32 bit BGRU. */
FC2_PIXEL_FORMAT_RGB = FC2_PIXEL_FORMAT_RGB8#, /**< 24 bit RGB. */
FC2_PIXEL_FORMAT_RGBU = 0x40000002#, /**< 32 bit RGBU. */
FC2_PIXEL_FORMAT_BGR16 = 0x02000001#, /**< R = G = B = 16 bits. */
FC2_PIXEL_FORMAT_BGRU16 = 0x02000002#, /**< 64 bit BGRU. */
FC2_PIXEL_FORMAT_422YUV8_JPEG = 0x40000001#, /**< JPEG compressed stream. */
FC2_NUM_PIXEL_FORMATS = 20#, /**< Number of pixel formats. */
FC2_UNSPECIFIED_PIXEL_FORMAT = 0 #/**< Unspecified pixel format. */
#fc2PropertyType enums
FC2_BRIGHTNESS = 0
FC2_AUTO_EXPOSURE = 1
FC2_SHARPNESS = 2
FC2_WHITE_BALANCE = 3
FC2_HUE = 4
FC2_SATURATION = 5
FC2_GAMMA = 6
FC2_IRIS = 7
FC2_FOCUS = 8
FC2_ZOOM = 9
FC2_PAN = 10
FC2_TILT = 11
FC2_SHUTTER = 12
FC2_GAIN = 13
FC2_TRIGGER_MODE = 14
FC2_TRIGGER_DELAY = 15
FC2_FRAME_RATE = 16
FC2_TEMPERATURE = 17
FC2_UNSPECIFIED_PROPERTY_TYPE = 18
FC2_PROPERTY_TYPE_FORCE_32BITS = FULL_32BIT_VALUE
#parameter name map. These are names as defined in FlyCapteure software
PARAMETER = {"brightness" : FC2_BRIGHTNESS,
"exposure" : FC2_AUTO_EXPOSURE,
"sharpness" : FC2_SHARPNESS,
"gamma" : FC2_GAMMA,
"shutter" : FC2_SHUTTER,
"gain" : FC2_GAIN,
"frame_rate" : FC2_FRAME_RATE}
#c_types of typedefs and typdef enums in FlyCapture2Defs_C.h
BOOL = c_int
fc2PropertyType = c_int
fc2Mode = c_int
fc2InterfaceType = c_int
fc2DriverType = c_int
fc2BusSpeed = c_int
fc2PCIeBusSpeed = c_int
fc2BayerTileFormat = c_int
fc2PixelFormat = c_int
fc2ImageFileFormat = c_int
fc2Context = c_void_p
fc2ImageImpl = c_void_p
class fc2Format7Info(Structure):
_fields_ = [("mode", fc2Mode),
("maxWidth", c_uint),
("maxHeight", c_uint),
("offsetHStepSize", c_uint),
("offsetVStepSize", c_uint),
("imagetHStepSize", c_uint),
("imageVStepSize", c_uint),
("pixelFormatBitField", c_uint),
("vendorPixelFormatBitField", c_uint),
("packetSize", c_uint),
("minPacketSize", c_uint),
("maxPacketSize", c_uint),
("percentage", c_float),
("reserved", c_uint*16)]
class fc2Format7ImageSettings(Structure):
_fields_ = [("mode", fc2Mode),
("offsetX", c_uint),
("offsetY", c_uint),
("width", c_uint),
("height", c_uint),
("pixelFormat", fc2PixelFormat),
("reserved", c_uint*8)]
class fc2Format7PacketInfo(Structure):
_fields_ = [("recommendedBytesPerPacket", c_uint),
("maxBytesPerPacket", c_uint),
("unitBytesPerPacket", c_uint),
("reserved", c_uint*8)]
class fc2EmbeddedImageInfoProperty(Structure):
_fields_ = [("available", BOOL),
("onOff", BOOL)]
class fc2EmbeddedImageInfo(Structure):
_fields_ = [("timestamp", fc2EmbeddedImageInfoProperty),
("gain", fc2EmbeddedImageInfoProperty),
("shutter", fc2EmbeddedImageInfoProperty),
("shutter", fc2EmbeddedImageInfoProperty),
("brightness", fc2EmbeddedImageInfoProperty),
("exposure", fc2EmbeddedImageInfoProperty),
("whiteBalance", fc2EmbeddedImageInfoProperty),
("frameCounter", fc2EmbeddedImageInfoProperty),
("strobePattern", fc2EmbeddedImageInfoProperty),
("GPIOPinState",fc2EmbeddedImageInfoProperty),
("ROIPosition",fc2EmbeddedImageInfoProperty)
]
class fc2TimeStamp(Structure):
_fields_ = [("seconds", c_longlong),
("microSeconds", c_uint),
("cycleSeconds", c_uint),
("cycleCount", c_uint),
("cycleOffset", c_uint),
("reserved", c_uint*8)]
flylib.fc2GetImageTimeStamp.restype = fc2TimeStamp
#structures of typdef struct in FlyCapture2Defs_C.h
class fc2PGRGuid(Structure):
_fields_ = [('value', c_uint*4)]
class fc2ConfigROM(Structure):
_fields_ = [("nodeVendorId", c_uint),
("chipIdHi", c_uint),
("chipIdLo", c_uint),
("unitSpecId", c_uint),
("unitSWVer", c_uint),
("unitSubSWVer", c_uint),
("vendorUniqueInfo_0", c_uint),
("vendorUniqueInfo_1", c_uint),
("vendorUniqueInfo_2", c_uint),
("vendorUniqueInfo_3", c_uint),
("pszKeyword", c_char*MAX_STRING_LENGTH),
("reserved", c_uint*16)]
class fc2MACAddress(Structure):
_fields_ = [("octets", c_ubyte*6)]
class fc2IPAddress(Structure):
_fields_ = [("octets", c_ubyte*4)]
class fc2CameraInfo(Structure):
_fields_ = [("serialNumber", c_uint),
("interfaceType",fc2InterfaceType),
("driverType", fc2DriverType),
("isColorCamera", BOOL),
("modelName", c_char*MAX_STRING_LENGTH),
("vendorName", c_char*MAX_STRING_LENGTH),
("sensorInfo", c_char*MAX_STRING_LENGTH),
("sensorResolution", c_char*MAX_STRING_LENGTH),
("driverName", c_char*MAX_STRING_LENGTH),
("firmwareVersion", c_char*MAX_STRING_LENGTH),
("firmwareBuildTime", c_char*MAX_STRING_LENGTH),
("maximumBusSpeed", fc2BusSpeed),
("pcieBusSpeed", fc2PCIeBusSpeed),
("bayerTileFormat", fc2BayerTileFormat),
("busNumber", c_ushort),
("nodeNumber", c_ushort),
# IIDC specific information
("iidcVer", c_uint),
("configRom",fc2ConfigROM),
#GigE specific information
("gigEMajorVersion", c_uint),
("gigEMinorVersion", c_uint),
("userDefinedName", c_char*MAX_STRING_LENGTH),
("xmlURL1", c_char*MAX_STRING_LENGTH),
("xmlURL2", c_char*MAX_STRING_LENGTH),
("macAddress", fc2MACAddress),
("ipAddress", fc2IPAddress),
("subnetMask", fc2IPAddress),
("defaultGateway", fc2IPAddress),
("ccpStatus", c_uint),
("applicationIPAddress", c_uint),
("applicationPort", c_uint),
("reserved", c_uint*16)]
class Property(Structure):
_fields_ = [("type", fc2PropertyType),
("present", BOOL),
("absControl", BOOL),
("onePush", BOOL),
("onOff", BOOL),
("autoManualMode", BOOL),
("valueA", c_uint),
("valueB", c_uint),
("absValue", c_float),
("reserved", c_uint)]
class fc2Image(Structure):
_fields_ = [("rows", c_uint),
("cols", c_uint),
("stride", c_uint),
("pData", c_char_p),
("dataSize", c_uint),
("receivedDataSize", c_uint),
("format", fc2PixelFormat),
("bayerFormat", fc2BayerTileFormat),
("imageImpl", fc2ImageImpl)]
class FlyLibError(Exception):
"""Exception raised when FlyCapture functions fails with a non-zero exit code"""
pass
def execute(function, *args):
"""For internal use. Executes a function with given arguments. It raises Exception if there is an error."""
logger.debug('Executing %s with args %s' % (function.__name__, args))
value = function(*args)
if value != FC2_ERROR_OK:
message = function.__name__ + ' failed with exit code %s.' % value
raise FlyLibError(message)
PIXEL_FORMAT = {"MONO16": FC2_PIXEL_FORMAT_MONO16, "MONO8" : FC2_PIXEL_FORMAT_MONO8}
class FlyCamera(BaseCamera):
"""Main object for FlyCamera control. Currently it supports only grayscale cameras
and adjust settings that are found under the "camera settings" tab in FlyCapture
software...
"""
_initialized = False
def __init__(self):
#allocate memory for C structures. This must be within __init__
#so if multiple Cameras are created each has a different context?.
self.info = fc2CameraInfo() #camera info is here, filled when init is called
self.format7_info = fc2Format7Info()
self.format7_image_settings = fc2Format7ImageSettings()
self.format7_packet_info = fc2Format7PacketInfo()
self.embedded_image_info = fc2EmbeddedImageInfo()
self._context = fc2Context()
self._guid = fc2PGRGuid()
self._raw_image = fc2Image()
self._converted_image = fc2Image()
def init(self,id = 0, format = "MONO8", shape = (None,None), offset = (None,None), timestamp = False):
"""Initialize camera with index id. It creates context, connects to camera,
allocates image memory, sets default camera parameters and reads and
fills camera info. pixel_format should be either 'MONO8' or FC2_PIXEL_FORMAT_MONO8
for 8bit raw data, pr 'MONO16' or FC2_PIXEL_FORMAT_MONO16 for 16 bit raw data,
Parameter shape determins image size in (rows, columns), offset tuple is a position
of top left corner."""
id = c_uint(id)
info = pointer(self.info)
self._close()
if isinstance(format,int):
pixel_format = format
else:
pixel_format = PIXEL_FORMAT[format]
try:
execute(flylib.fc2CreateContext,byref(self._context))
execute(flylib.fc2GetCameraFromIndex, self._context, id, byref(self._guid) )
execute(flylib.fc2Connect, self._context, byref(self._guid))
execute(flylib.fc2GetCameraInfo, self._context, info )
self._set_format7_image_settings(pixel_format, shape, offset)
self.set_chunkdata(timestamp)
#self.set_parameter("exposure", on = False, auto = False) #set autoexposure auto False and onOff False
self.set_parameter("brightness", 0.) #brightness should be zero
self.set_parameter("sharpness", on = False, auto = False) #no sharpness!
self.set_parameter("gamma", on = False)
self.set_parameter("shutter", auto = False)
self.set_parameter("gain",0., auto = False)#
self._initialized = True
except FlyLibError:
self._initialized = False
self._close()
raise
def set_chunkdata(self, timestamp = True):
"""Set embeded image info. Currently only timestamp can be turned on or off"""
info = self.embedded_image_info
execute(flylib.fc2GetEmbeddedImageInfo, self._context, byref(info))
if bool(info.timestamp.available) == True:
info.timestamp.onOff = timestamp
execute(flylib.fc2SetEmbeddedImageInfo, self._context, byref(info))
self._timestamp = timestamp
def _set_format7_image_settings(self, pixel_format = FC2_PIXEL_FORMAT_MONO8, shape = (None,None), offset = (None,None), mode = 0):
ok = c_int()
self.format7_info.mode = mode# format7 mode setting
execute(flylib.fc2GetFormat7Info,self._context,byref(self.format7_info), byref(ok))
if bool(ok) != True:
raise FlyLibError("Format7 mode %s not supported" % self.format7_info.mode)
self.format7_image_settings.mode = self.format7_info.mode
height, width = shape
if width is None:
width = self.format7_info.maxWidth
self.format7_image_settings.width = width
if height is None:
height = self.format7_info.maxHeight
self.format7_image_settings.height = height
shape = height, width
x0,y0 = offset
if x0 is None:
x0 = self.format7_info.maxWidth/2-width/2
if y0 is None:
y0 = self.format7_info.maxHeight/2-height/2
self.format7_image_settings.offsetX = x0
self.format7_image_settings.offsetY = y0
self.format7_image_settings.pixelFormat = pixel_format
execute(flylib.fc2ValidateFormat7Settings,self._context,byref(self.format7_image_settings), byref(ok), byref(self.format7_packet_info))
if bool(ok) != True:
raise FlyLibError("Format7 image setting is not valid")
perc = c_float(self.format7_info.percentage)#not sure what this is
execute(flylib.fc2SetFormat7Configuration,self._context,byref(self.format7_image_settings),perc)
if pixel_format == FC2_PIXEL_FORMAT_MONO8:
self._pixel_format = pixel_format
self.converted_image = np.empty(shape = shape, dtype = "uint8")
elif pixel_format == FC2_PIXEL_FORMAT_MONO16:
#warnings.warn("MONO16 only works if you set it with FlyCapture software")
self._pixel_format = pixel_format
self.converted_image = np.empty(shape = shape, dtype = "uint16")
else:
raise Exception("Unsupported pixel format %s" % pixel_format)
#image_settings = fc2Format7ImageSettings()
#packet_size = c_uint()
#percentage = c_uint()
#execute(flylib.fc2GetFormat7Configuration, self._context, byref(image_settings), byref(packet_size), byref(percentage))
#print image_settings.mode, percentage
execute(flylib.fc2CreateImage,byref(self._raw_image))
execute(flylib.fc2CreateImage,byref(self._converted_image))
#self._raw_image_memory = self.raw_image.ctypes.data_as(POINTER(c_ubyte))
#self._raw_image_memory_size = c_int(self.raw_image.nbytes)
self._converted_image_memory = self.converted_image.ctypes.data_as(POINTER(c_ubyte))
self._converted_image_memory_size = c_uint(self.converted_image.nbytes)
execute(flylib.fc2SetImageData,byref(self._converted_image),self._converted_image_memory,self._converted_image_memory_size)
if self._pixel_format == FC2_PIXEL_FORMAT_MONO8:
execute(flylib.fc2SetImageDimensions,byref(self._converted_image),shape[0],shape[1],shape[1],self._pixel_format,0)
else: #MONO16
execute(flylib.fc2SetImageDimensions,byref(self._converted_image),shape[0],shape[1],shape[1]*2,self._pixel_format,0)
def set_format(self, format = "MONO8", shape = (None, None), offset = (None,None), mode = 0):
if isinstance(format,int):
pixel_format = format
else:
pixel_format = PIXEL_FORMAT[format]
flylib.fc2DestroyImage(byref(self._converted_image))
flylib.fc2DestroyImage(byref(self._raw_image))
self._set_format7_image_settings(pixel_format = pixel_format, shape = shape, offset = offset, mode = mode)
@property
def sensor_shape(self):
return self.format7_info.maxHeight, self.format7_info.maxWidth
def set_property(self, prop):
"""Set camera property. Parameter prop must be an instance of Property class"""
p = prop
if not isinstance(p, Property):
raise Exception("Parameter prop must be an instance of Property class")
execute(flylib.fc2SetProperty,self._context,byref(p))
def get_property(self, prop):
"""Get camera property. Parameter prop must be an instance of Property class"""
p = prop
if not isinstance(p, Property):
raise Exception("prop must be an instance of Property class")
execute(flylib.fc2GetProperty,self._context,byref(p))
return p
def set_parameter(self, name, value = None, value_int = None, on = None, auto = None):
"""Sets camera parameter. Parameters that can be set are those of PARAMETER.keys()
parammeter value must be a float or None (if it is not going to be changed)
if value_int is specified, parameter value is treated as an integer (absControl = 0)
if either "on" or "auto" is specified it sets autoManualMode and onOff values...
See FlyCamera software how this works..
"""
type = PARAMETER[name]
p = Property(type = type)
p = self.get_property(p) #get current camera settings
if auto is not None:
p.autoManualMode = int(auto)
if on is not None:
p.onOff = int(on)
if value is not None:
value = float(value) #make sure it can be converted to float
p.absValue = value
p.absControl = 1
elif value_int is not None:
value_int = int(value_int)
p.valueA = value_int
p.absControl = 0
self.set_property(p)
#return p
def get_parameter(self,name):
type = PARAMETER[name]
p = Property(type = type)
self.get_property(p)
return {"value" : p.absValue, "value_int" : p.valueA,
"auto" : bool(p.autoManualMode), "on" : bool(p.onOff)}
def set_exposure(self, value = None, on = True):
"""Sets exposure in EV, or set auto exposure if value is None """
if value is None:
self.set_parameter("exposure", auto = True, on = on)
else:
self.set_parameter("exposure", value, auto = False, on = on)
def set_frame_rate(self, value = None, on = True):
"""Sets exposure in EV, or set auto exposure if value is None """
if value is None:
self.set_parameter("frame_rate", auto = True, on = on)
else:
self.set_parameter("frame_rate", value, auto = False, on = on)
def set_shutter(self, value = None):
"""Set shutter in miliseconds, or set auto shutter (if value is None)"""
if value is None:
shutter_old = self.get_shutter()
self.set_parameter("shutter", auto = True)
while True:
print shutter_old
time.sleep(shutter_old/1000.)
shutter_new = self.get_shutter()
if shutter_new == shutter_old:
break
shutter_old = shutter_new
else:
self.set_parameter("shutter", value)
def get_shutter(self):
"""Get shutter value in miliseconds"""
return self.get_parameter("shutter")["value"]
def getp(self,name):
return self.get_parameter(name)["value"]
def setp(self,name, value):
return self.set_parameter(name,value, on = True, auto = False)
def set_gain(self, value = None):
"""Set gain value in dB or set auto gain (if value is None)"""
if value is None:
self.set_parameter("gain", auto = True)
else:
self.set_parameter("gain", value)
def get_gain(self):
"""Get current gain value in dB"""
return self.get_parameter("gain")["value"]
def capture(self):
"""Captures raw image. Note that returned image is a view of internal converted_image attribute.
This data is rewritten after next call of capture( method. You need to copy data if you wish
to preserve it, eg.:
#>>> im = c.capture().copy()
"""
execute(flylib.fc2StartCapture, self._context)
execute(flylib.fc2RetrieveBuffer, self._context, byref(self._raw_image))
execute(flylib.fc2ConvertImageTo,self._pixel_format, byref(self._raw_image), byref(self._converted_image))
execute(flylib.fc2StopCapture, self._context)
return self.converted_image
def video(self, n, timestamp = False, show = False, callback = None):
"""Captures a set of n images. This function returns a generator. If
parameter timestamp is specified the yielded data is a tuple consisting
of frame timestamp and frame image. If timestamp is set to False (default)
only image is returned. If show is set to True, video is displayed through
cv2.show method (which results in a slower framerate)
Note that each image is a view of internal
converted_image attribute. This data is rewritten after each frame grab.
You need to copy data if you wish to preserve it. eg:
>>> [im.copy() for im in c.video(100)] #generate 100 frames video
To generate a 100 frame video with timestamps do
>>> [(t,im.copy()) for t, im in c.video(100, timestamp = True)]
"""
execute(flylib.fc2StartCapture, self._context)
def next():
tinfo = {}
execute(flylib.fc2RetrieveBuffer, self._context, byref(self._raw_image))
execute(flylib.fc2ConvertImageTo,self._pixel_format, byref(self._raw_image), byref(self._converted_image))
if show == True:
cv2.imshow('image',self.converted_image)
if cv2.waitKey(1) & 0xFF == ord('q'):
return
if self._timestamp == False:
tinfo["time"] = time.time()
#tinfo["id"] = i
else:
ts = flylib.fc2GetImageTimeStamp( byref(self._raw_image))
tinfo["time"] = float(ts.seconds)*1000000 + ts.microSeconds
#tinfo["id"] = i
return [tinfo, self.converted_image]
try:
if n > 0:
for i in range(n):
out = next()
if out:
if callback is not None:
if not callback(out):
break
yield out
else:
break
else:
while True:
out = next()
if out:
if callback is not None:
if not callback(out):
break
yield out
else:
break
finally:
execute(flylib.fc2StopCapture, self._context)
if show == True:
cv2.destroyAllWindows()
#return self.converted_image
def save_raw(self, fname):
"""Saves raw image data to a file"""
if os.path.splitext(fname)[1] == ".raw":
execute(flylib.fc2SaveImage, byref(self._raw_image), fname, FC2_RAW )
else:
execute(flylib.fc2SaveImage, byref(self._raw_image), fname, FC2_FROM_FILE_EXT )
def save_image(self, fname):
"""Use Flylib to save converted image to a file"""
execute(flylib.fc2SaveImage, byref(self._converted_image), fname, FC2_FROM_FILE_EXT )
def close(self):
"""Disconnects camera from context and destroys context and frees all data."""
if self._initialized:
self._initialized = False
self._close()
def _close(self):
#Clean up silently.. free all data, no error checking
flylib.fc2DestroyImage(byref(self._converted_image))
flylib.fc2DestroyImage(byref(self._raw_image))
flylib.fc2Disconnect(self._context)
flylib.fc2DestroyContext(self._context)
def __del__(self):
self.close()
def test():
import matplotlib.pyplot as plt
c = Camera()
c.init()
c.set_exposure() #set auto exposure
c.set_shutter() #set shutter for given exposure
im = c.capture()
c.save_im
age("test.jpg")
plt.imshow(im)
plt.show()
c.close()
def test_video(n = 100, show = False, framerate = 100., shape = (384,384)):
import matplotlib.pyplot as plt
import time
c = Camera()
c.init(shape = shape, pixel_format = FC2_PIXEL_FORMAT_MONO16)
c.set_frame_rate(framerate)
images = np.empty(shape = (shape[0],shape[1],n), dtype = "uint16")
#imagesf =np.empty(shape = (shape[0]/2,shape[1]/2,n), dtype = "complex64")
#c.set_parameter("frame_rate", value_int =479, auto = False, on = True)
data = []
print "Video capture started"
for i,d in enumerate(c.video(n, timestamp = False, show = show)):
t, im = d
images[:,:,i] = im
#imagesf[:,:,i] = np.fft.fft2(im)[:shape[0]/2,:shape[1]/2]
data.append((t,images[:,:,i].mean()))
print "compress and dump to disk"
folder = "C:\\Users\\Mikroskop\\Data\\"
#np.savez_compressed(folder + "images_compressed.npz",images)
#np.savez_compressed("c:\\Users\\LCD\\ffts_compressed.npz",imagesf)
print "dump to disk"
np.save(folder + "images.npy",images)
#np.save("c:\\Users\\LCD\\ffts.npy",imagesf)
x = [(d[0]-data[0][0]) for d in data]
x2 = np.arange(0,n*1./framerate,1./framerate)
y = [d[1].mean() for d in data]
print y[0].max()
print "Avg. framerate %f, delta_t_max %f, delta_t_min %f" % ((n-1)/x[-1],np.diff(x).max(), np.diff(x).min())
plt.plot(x,y,"o-")
plt.plot(x2,y,"o-")
#plt.plot(np.diff(x))
plt.show()
c.close()
def test_256x256(n = 100, show = True, framerate = 100.):
"""For this test ROI should be set to 256x256 in Flycapture software"""
import matplotlib.pyplot as plt
import time
c = Camera()
c.init(shape = (256,256),pixel_format = FC2_PIXEL_FORMAT_MONO16)
c.set_frame_rate(framerate)
#c.set_parameter("frame_rate", value_int =479, auto = False, on = True)
data = [(t,im.mean()) for t, im in c.video(n, timestamp = False, show = show)]
x = [(d[0]-data[0][0]) for d in data]
x2 = np.arange(0,n*1./framerate,1./framerate)
y = [d[1].mean() for d in data]
print y[0].max()
print "Avg. framerate %f, delta_t_max %f, delta_t_min %f" % ((n-1)/x[-1],np.diff(x).max(), np.diff(x).min())
plt.plot(x,y,"o-")
plt.plot(x2,y,"o-")
#plt.plot(np.diff(x))
plt.show()
c.close()
if __name__ == "__main__":
import doctest
#doctest.testmod()
#test()
| {
"repo_name": "andrej5elin/camera",
"path": "camera/bfly.py",
"copies": "1",
"size": "32554",
"license": "mit",
"hash": -1682668629913730000,
"line_mean": 38.8994974874,
"line_max": 143,
"alpha_frac": 0.5788843153,
"autogenerated": false,
"ratio": 3.5955378838082614,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46744221991082613,
"avg_score": null,
"num_lines": null
} |
# a simple cubic spline example.
#
# generate some random data in 10 intervals -- note the data changes
# each time this is run.
#
# Our form of the spline polynomial comes from Pang, Ch. 2
#
# in this version, we use an iterative method to solve the tridiagonal system
#
# plot the splines
#
# M. Zingale (2013-03-03)
import numpy
import pylab
import math
from scipy import linalg # scipy modules need to be imported separately
# Jacobi tolerance
tol = 1.e-12
# plot a spline
def plot_spline(x0, x1, f0, f1, ppp0, ppp1):
# lots of points for a smooth plot
x = numpy.linspace(x0, x1, 100)
dx = x1-x0
alpha = ppp1/(6.0*dx)
beta = -ppp0/(6.0*dx)
gamma = (-ppp1*dx*dx/6.0 + f1)/dx
eta = (ppp0*dx*dx/6.0 - f0)/dx
p = alpha*(x-x0)**3 + beta*(x-x1)**3 + gamma*(x-x0) + eta*(x-x1)
pylab.plot(x, p)
# number of intervals
n = 20
xmin = 0.0
xmax = 1.0
# coordinates of the data locations
x = numpy.linspace(xmin, xmax, n+1)
dx = x[1] - x[0]
# random data
f = numpy.random.rand(n+1)
# we are solving for n-1 unknowns
# setup the righthand side of our matrix equation
b = numpy.zeros(n+1)
# b_i = (6/dx) * (f_{i-1} - 2 f_i + f_{i+1})
# here we do this with slice notation to fill the
# inner n-1 slots of b
b[1:n] = (6.0/dx)*(f[0:n-1] - 2.0*f[1:n] + f[2:n+1])
# use Jacobi iteration to solve this system. Note, we don't need to
# write down the matrix for this, we know that the form of the system
# we are solving is:
#
# dx x_{i-1} + 4 dx x_i + dx_{i+1} = b_i
#
# we only solve for i = 1, ..., n-1, and we impose the boundary
# conditions: x[0] = x[n] = 0
# allocate space for the solution and old value
xold = numpy.zeros(n+1)
xsol = numpy.zeros(n+1)
# note that the BCs: x[0] = x[n] = 0 are already initialized
# iterate
err = 1.e30
iter = 0
while (err > tol):
# xsol_i = (b_i - dx x_{i-1} - dx x_{i+1})/(4dx)
xsol[1:n] = (b[1:n] - dx*xold[0:n-1] - dx*xold[2:n+1])/(4.0*dx)
iter += 1
err = numpy.max(numpy.abs((xsol[1:n] - xold[1:n])/xsol[1:n]))
print iter, err
xold = xsol.copy()
# for debugging, use the built-in banded solver from numpy
u = numpy.zeros(n-1)
d = numpy.zeros(n-1)
l = numpy.zeros(n-1)
d[:] = 4.0*dx
u[:] = dx; u[0] = 0.0
l[:] = dx; l[n-2] = 0.0
# create a banded matrix -- this doesn't store every element -- just
# the diagonal and one above and below and solve
A = numpy.matrix([u,d,l])
xsol_np = linalg.solve_banded((1,1), A, b[1:n])
# xsol_np now hold all the second derivatives for points 1 to n-1.
# Natural boundary conditions are imposed here
xsol_np = numpy.insert(xsol_np, 0, 0)
xsol_np = numpy.insert(xsol_np, n, 0) # insert at the end
# report error from our iterative method vs. direct solve
err = numpy.max(numpy.abs((xsol[1:n] - xsol_np[1:n])/xsol_np[1:n]))
print "relative error of iterative solution compared to direct: ", err
# go ahead with our iterative solution -- natural boundary conditions are
# already in place for this
ppp = xsol
# now plot -- data points first
pylab.scatter(x, f, marker="x", color="r")
# plot the splines
i = 0
while i < n:
# working on interval [i,i+1]
ppp_i = ppp[i]
ppp_ip1 = ppp[i+1]
f_i = f[i]
f_ip1 = f[i+1]
x_i = x[i]
x_ip1 = x[i+1]
plot_spline(x_i, x_ip1, f_i, f_ip1, ppp_i, ppp_ip1)
i += 1
pylab.savefig("spline-iterative.png")
# note: we could have done this all through scipy -- here is their
# spline, but it doesn't seem to support natural boundary conditions
#s = interpolate.InterpolatedUnivariateSpline(x, f, k=3)
#xx = numpy.linspace(xmin, xmax, 1000)
#pylab.plot(xx, s(xx), color="k", ls=":")
# old way from scipy -- this raises a NotImplementedError for natural
#spl1 = interpolate.splmake(x, f, order=3, kind="natural")
#xx = numpy.linspace(xmin, xmax, 1000)
#yy = interpolate.spleval(spl1, xx)
#pylab.plot(xx, yy, color="k", ls=":")
#pylab.savefig("spline-scipy.png")
| {
"repo_name": "bt3gl/Numerical-Methods-for-Physics",
"path": "others/lin_algebra/cubic-spline-iterate.py",
"copies": "1",
"size": "3908",
"license": "apache-2.0",
"hash": 7753582859668590000,
"line_mean": 21.9882352941,
"line_max": 77,
"alpha_frac": 0.6348515865,
"autogenerated": false,
"ratio": 2.559266535690897,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8643978816893925,
"avg_score": 0.010027861059394409,
"num_lines": 170
} |
# a simple cubic spline example.
#
# generate some random data in 10 intervals -- note the data changes
# each time this is run.
#
# Our form of the spline polynomial comes from Pang, Ch. 2
#
# solve the matrix system for the splines
#
# plot the splines
#
# M. Zingale (2013-02-10)
import numpy
import pylab
import math
from scipy import linalg # scipy modules need to be imported separately
from scipy import interpolate # scipy modules need to be imported separately
# plot a spline
def plot_spline(x0, x1, f0, f1, ppp0, ppp1):
# lots of points for a smooth plot
x = numpy.linspace(x0, x1, 100)
dx = x1-x0
alpha = ppp1/(6.0*dx)
beta = -ppp0/(6.0*dx)
gamma = (-ppp1*dx*dx/6.0 + f1)/dx
eta = (ppp0*dx*dx/6.0 - f0)/dx
p = alpha*(x-x0)**3 + beta*(x-x1)**3 + gamma*(x-x0) + eta*(x-x1)
pylab.plot(x, p)
# number of intervals
n = 20
xmin = 0.0
xmax = 1.0
# coordinates of the data locations
x = numpy.linspace(xmin, xmax, n+1)
dx = x[1] - x[0]
# random data
f = numpy.random.rand(n+1)
# we are solving for n-1 unknowns
# setup the righthand side of our matrix equation
b = numpy.zeros(n+1)
# b_i = (6/dx) * (f_{i-1} - 2 f_i + f_{i+1})
# here we do this with slice notation to fill the
# inner n-1 slots of b
b[1:n] = (6.0/dx)*(f[0:n-1] - 2.0*f[1:n] + f[2:n+1])
# we only care about the inner n-1 quantities
b = b[1:n]
# the matrix A is tridiagonal. Create 3 arrays which will represent
# the diagonal (d), the upper diagonal (u), and the lower diagnonal
# (l). l and u will have 1 less element. For u, we will pad this at
# the beginning and for l we will pad at the end.
#
# see http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_banded.html#scipy.linalg.solve_banded
# for the description of a banded matrix
u = numpy.zeros(n-1)
d = numpy.zeros(n-1)
l = numpy.zeros(n-1)
d[:] = 4.0*dx
u[:] = dx
u[0] = 0.0
l[:] = dx
l[n-2] = 0.0
# create a banded matrix -- this doesn't store every element -- just
# the diagonal and one above and below
A = numpy.matrix([u,d,l])
# solve Ax = b using the scipy banded solver -- the (1,1) here means
# that there is one diagonal above the main diagonal, and one below.
xsol = linalg.solve_banded((1,1), A, b)
# x now hold all the second derivatives for points 1 to n-1. Natural
# boundary conditions set p'' = 0 at i = 0 and n
# ppp will be our array of second derivatives
ppp = numpy.insert(xsol, 0, 0) # insert before the first element
ppp = numpy.insert(ppp, n, 0) # insert at the end
# now plot -- data points first
pylab.scatter(x, f, marker="x", color="r")
# plot the splines
i = 0
while i < n:
# working on interval [i,i+1]
ppp_i = ppp[i]
ppp_ip1 = ppp[i+1]
f_i = f[i]
f_ip1 = f[i+1]
x_i = x[i]
x_ip1 = x[i+1]
plot_spline(x_i, x_ip1, f_i, f_ip1, ppp_i, ppp_ip1)
i += 1
pylab.savefig("spline.png")
# note: we could have done this all through scipy -- here is their
# spline, but it doesn't seem to support natural boundary conditions
#s = interpolate.InterpolatedUnivariateSpline(x, f, k=3)
#xx = numpy.linspace(xmin, xmax, 1000)
#pylab.plot(xx, s(xx), color="k", ls=":")
# old way from scipy -- this raises a NotImplementedError for natural
#spl1 = interpolate.splmake(x, f, order=3, kind="natural")
#xx = numpy.linspace(xmin, xmax, 1000)
#yy = interpolate.spleval(spl1, xx)
#pylab.plot(xx, yy, color="k", ls=":")
#pylab.savefig("spline-scipy.png")
| {
"repo_name": "bt3gl/Numerical-Methods-for-Physics",
"path": "others/interpolation_root-finding/cubic-spline.py",
"copies": "1",
"size": "3443",
"license": "apache-2.0",
"hash": -1330329724600383500,
"line_mean": 22.2635135135,
"line_max": 114,
"alpha_frac": 0.6520476329,
"autogenerated": false,
"ratio": 2.6982758620689653,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8797964961320677,
"avg_score": 0.010471706729657705,
"num_lines": 148
} |
"""A simple database connection API with some helpful decorators.
"""
import atexit
import sqlite3
import os
from functools import wraps
from .logger import logger
from . import settings
class db:
"""Singleton pattern type database connection helper.
"""
__instance = None
def __new__(cls, path_to_db=settings.DATA_PATH):
"""Abuse the __new__ function to allow instance persistance.
Singleton hacks.
"""
if db.__instance is None:
db.__instance = object.__new__(cls)
db.__instance.connection = sqlite3.connect(os.path.join(path_to_db, settings.DB_NAME))
atexit.register(db.__instance.connection.close)
return db.__instance
@staticmethod
def use(func):
"""Wraps a specified function with connection/cursor interfaces.
"""
@logger.log
@wraps(func)
def wrapped(*args, **kwargs):
# Pass the wrapped function some required arguments
# for database use.
connection = db().connection
cursor = connection.cursor()
func(connection, cursor, *args, **kwargs)
return wrapped
| {
"repo_name": "SeedyROM/kalci",
"path": "kalci/database.py",
"copies": "1",
"size": "1178",
"license": "mit",
"hash": 5113851417890490000,
"line_mean": 27.0476190476,
"line_max": 98,
"alpha_frac": 0.6137521222,
"autogenerated": false,
"ratio": 4.4961832061068705,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5609935328306871,
"avg_score": null,
"num_lines": null
} |
# A simple data generator file with 3 params - (temp, wind, humidity)
import bisect
import random
# Temperature phrases & upper bounds
temp_phrases = ["It is going to be " + s + "." for s in
["a cold day today", "a cool day today", "a warm day today", "a hot day today"]];
temp_upper_bounds = [0.25, 0.50, 0.75, 1.0];
# Wind phrases & upper bounds
wind_phrases = ["It is going to be " + s + "." for s in
["a very still day today", "a calm day today", "a windy day today", "a cyclonic day today"]]
wind_upper_bounds = [0.25, 0.50, 0.75, 1.0]
# Humidity phrases & upper bounds
humid_phrases = ["It is going to be " + s + "." for s in
["a very dry day today", "a dry day today", "a humid day today", "a very humid day today"]]
humid_upper_bounds = [0.25, 0.50, 0.75, 1.0]
if __name__ == "__main__":
op_file = "data/targets"
ip_file = "data/xs"
num_paragraphs = 1000
f = open(op_file + str(num_paragraphs) + ".txt", "w")
f2 = open(ip_file + str(num_paragraphs) + ".txt", "w")
for k in range(num_paragraphs):
# Generate three random numbers
rand_temp = random.uniform(0, 1)
rand_wind = random.uniform(0, 1)
rand_humid = random.uniform(0, 1)
# Obtain selector idxs
temp_idx = bisect.bisect(temp_upper_bounds, rand_temp)
wind_idx = bisect.bisect(wind_upper_bounds, rand_wind)
humid_idx = bisect.bisect(humid_upper_bounds, rand_humid)
# Obtain phrases
temp = temp_phrases[temp_idx]
wind = wind_phrases[wind_idx]
humid = humid_phrases[humid_idx]
# Print concatenated paragraph to STDOUT
paragraph = temp + " " + wind + " " + humid
f.write(paragraph + "\n")
f2.write("%0.4f %0.4f %0.4f\n" % (rand_temp, rand_wind, rand_humid))
f.close()
f2.close()
| {
"repo_name": "bitesandbytes/upgraded-system",
"path": "data_gen/simple_3_gen.py",
"copies": "1",
"size": "1857",
"license": "mit",
"hash": -3047857848538141000,
"line_mean": 36.14,
"line_max": 108,
"alpha_frac": 0.5885837372,
"autogenerated": false,
"ratio": 2.9759615384615383,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9058447374727465,
"avg_score": 0.001219580186814787,
"num_lines": 50
} |
"""A simple declarative layer for SQLAlchemy ORM.
SQLAlchemy object-relational configuration involves the usage of Table,
mapper(), and class objects to define the three areas of configuration.
declarative moves these three types of configuration underneath the
individual mapped class. Regular SQLAlchemy schema and ORM constructs are
used in most cases::
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite://')
Base = declarative_base(engine)
class SomeClass(Base):
__tablename__ = 'some_table'
id = Column('id', Integer, primary_key=True)
name = Column('name', String(50))
Above, the ``declarative_base`` callable produces a new base class from
which all mapped classes inherit from. When the class definition is
completed, a new ``Table`` and ``mapper()`` have been generated, accessible
via the ``__table__`` and ``__mapper__`` attributes on the ``SomeClass``
class.
You may omit the names from the Column definitions. Declarative will fill
them in for you.
class SomeClass(Base):
__tablename__ = 'some_table'
id = Column(Integer, primary_key=True)
name = Column(String(50))
Attributes may be added to the class after its construction, and they will
be added to the underlying ``Table`` and ``mapper()`` definitions as
appropriate::
SomeClass.data = Column('data', Unicode)
SomeClass.related = relation(RelatedInfo)
Classes which are mapped explicitly using ``mapper()`` can interact freely
with declarative classes. The ``declarative_base`` base class contains a
``MetaData`` object as well as a dictionary of all classes created against
the base. So to access the above metadata and create tables we can say::
Base.metadata.create_all()
The ``declarative_base`` can also receive a pre-created ``MetaData``
object::
mymetadata = MetaData()
Base = declarative_base(metadata=mymetadata)
Relations to other classes are done in the usual way, with the added feature
that the class specified to ``relation()`` may be a string name. The "class
registry" associated with ``Base`` is used at mapper compilation time to
resolve the name into the actual class object, which is expected to have
been defined once the mapper configuration is used::
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
addresses = relation("Address", backref="user")
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
email = Column(String(50))
user_id = Column(Integer, ForeignKey('users.id'))
Column constructs, since they are just that, are immediately usable, as
below where we define a primary join condition on the ``Address`` class
using them::
class Address(Base)
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
email = Column(String(50))
user_id = Column(Integer, ForeignKey('users.id'))
user = relation(User, primaryjoin=user_id==User.id)
Synonyms are one area where ``declarative`` needs to slightly change the
usual SQLAlchemy configurational syntax. To define a getter/setter which
proxies to an underlying attribute, use ``synonym`` with the ``descriptor``
argument::
class MyClass(Base):
__tablename__ = 'sometable'
_attr = Column('attr', String)
def _get_attr(self):
return self._some_attr
def _set_attr(self, attr)
self._some_attr = attr
attr = synonym('_attr', descriptor=property(_get_attr, _set_attr))
The above synonym is then usable as an instance attribute as well as a
class-level expression construct::
x = MyClass()
x.attr = "some value"
session.query(MyClass).filter(MyClass.attr == 'some other value').all()
As an alternative to ``__tablename__``, a direct ``Table`` construct may be
used::
class MyClass(Base):
__table__ = Table('my_table', Base.metadata,
Column(Integer, primary_key=True),
Column(String(50))
)
This is the preferred approach when using reflected tables, as below::
class MyClass(Base):
__table__ = Table('my_table', Base.metadata, autoload=True)
Mapper arguments are specified using the ``__mapper_args__`` class variable.
Note that the column objects declared on the class are immediately usable,
as in this joined-table inheritance example::
class Person(Base):
__tablename__ = 'people'
id = Column(Integer, primary_key=True)
discriminator = Column(String(50))
__mapper_args__ = {'polymorphic_on':discriminator}
class Engineer(Person):
__tablename__ = 'engineers'
__mapper_args__ = {'polymorphic_identity':'engineer'}
id = Column(Integer, ForeignKey('people.id'), primary_key=True)
primary_language = Column(String(50))
For single-table inheritance, the ``__tablename__`` and ``__table__`` class
variables are optional on a class when the class inherits from another
mapped class.
As a convenience feature, the ``declarative_base()`` sets a default
constructor on classes which takes keyword arguments, and assigns them to
the named attributes::
e = Engineer(primary_language='python')
Note that ``declarative`` has no integration built in with sessions, and is
only intended as an optional syntax for the regular usage of mappers and
Table objects. A typical application setup using ``scoped_session`` might
look like::
engine = create_engine('postgres://scott:tiger@localhost/test')
Session = scoped_session(sessionmaker(transactional=True, autoflush=False, bind=engine))
Base = declarative_base()
Mapped instances then make usage of ``Session`` in the usual way.
"""
from sqlalchemy.schema import Table, Column, MetaData
from sqlalchemy.orm import synonym as _orm_synonym, mapper, comparable_property
from sqlalchemy.orm.interfaces import MapperProperty
from sqlalchemy.orm.properties import PropertyLoader, ColumnProperty
from sqlalchemy import util, exceptions
__all__ = ['declarative_base', 'synonym_for', 'comparable_using',
'declared_synonym']
class DeclarativeMeta(type):
def __init__(cls, classname, bases, dict_):
if '_decl_class_registry' in cls.__dict__:
return type.__init__(cls, classname, bases, dict_)
cls._decl_class_registry[classname] = cls
our_stuff = util.OrderedDict()
for k in dict_:
value = dict_[k]
if (isinstance(value, tuple) and len(value) == 1 and
isinstance(value[0], (Column, MapperProperty))):
util.warn("Ignoring declarative-like tuple value of attribute "
"%s: possibly a copy-and-paste error with a comma "
"left at the end of the line?" % k)
continue
if not isinstance(value, (Column, MapperProperty)):
continue
prop = _deferred_relation(cls, value)
our_stuff[k] = prop
table = None
if '__table__' not in cls.__dict__:
if '__tablename__' in cls.__dict__:
tablename = cls.__tablename__
autoload = cls.__dict__.get('__autoload__')
if autoload:
table_kw = {'autoload': True}
else:
table_kw = {}
cols = []
for key, c in our_stuff.iteritems():
if isinstance(c, ColumnProperty):
for col in c.columns:
if isinstance(col, Column) and col.table is None:
_undefer_column_name(key, col)
cols.append(col)
elif isinstance(c, Column):
_undefer_column_name(key, c)
cols.append(c)
cls.__table__ = table = Table(tablename, cls.metadata,
*cols, **table_kw)
else:
table = cls.__table__
mapper_args = getattr(cls, '__mapper_args__', {})
if 'inherits' not in mapper_args:
inherits = cls.__mro__[1]
inherits = cls._decl_class_registry.get(inherits.__name__, None)
mapper_args['inherits'] = inherits
if hasattr(cls, '__mapper_cls__'):
mapper_cls = util.unbound_method_to_callable(cls.__mapper_cls__)
else:
mapper_cls = mapper
cls.__mapper__ = mapper_cls(cls, table, properties=our_stuff, **mapper_args)
return type.__init__(cls, classname, bases, dict_)
def __setattr__(cls, key, value):
if '__mapper__' in cls.__dict__:
if isinstance(value, Column):
_undefer_column_name(key, value)
cls.__table__.append_column(value)
cls.__mapper__.add_property(key, value)
elif isinstance(value, MapperProperty):
cls.__mapper__.add_property(key, _deferred_relation(cls, value))
else:
type.__setattr__(cls, key, value)
else:
type.__setattr__(cls, key, value)
def _deferred_relation(cls, prop):
if isinstance(prop, PropertyLoader) and isinstance(prop.argument, basestring):
arg = prop.argument
def return_cls():
try:
return cls._decl_class_registry[arg]
except KeyError:
raise exceptions.InvalidRequestError("When compiling mapper %s, could not locate a declarative class named %r. Consider adding this property to the %r class after both dependent classes have been defined." % (prop.parent, arg, prop.parent.class_))
prop.argument = return_cls
return prop
def declared_synonym(prop, name):
"""Deprecated. Use synonym(name, descriptor=prop)."""
return _orm_synonym(name, descriptor=prop)
declared_synonym = util.deprecated(None, False)(declared_synonym)
def synonym_for(name, map_column=False):
"""Decorator, make a Python @property a query synonym for a column.
A decorator version of [sqlalchemy.orm#synonym()]. The function being
decorated is the 'descriptor', otherwise passes its arguments through
to synonym()::
@synonym_for('col')
@property
def prop(self):
return 'special sauce'
The regular ``synonym()`` is also usable directly in a declarative
setting and may be convenient for read/write properties::
prop = synonym('col', descriptor=property(_read_prop, _write_prop))
"""
def decorate(fn):
return _orm_synonym(name, map_column=map_column, descriptor=fn)
return decorate
def comparable_using(comparator_factory):
"""Decorator, allow a Python @property to be used in query criteria.
A decorator front end to [sqlalchemy.orm#comparable_property()], passes
throgh the comparator_factory and the function being decorated::
@comparable_using(MyComparatorType)
@property
def prop(self):
return 'special sauce'
The regular ``comparable_property()`` is also usable directly in a
declarative setting and may be convenient for read/write properties::
prop = comparable_property(MyComparatorType)
"""
def decorate(fn):
return comparable_property(comparator_factory, fn)
return decorate
def declarative_base(engine=None, metadata=None, mapper=None):
lcl_metadata = metadata or MetaData()
if engine:
lcl_metadata.bind = engine
class Base(object):
__metaclass__ = DeclarativeMeta
metadata = lcl_metadata
if mapper:
__mapper_cls__ = mapper
_decl_class_registry = {}
def __init__(self, **kwargs):
for k in kwargs:
if not hasattr(type(self), k):
raise TypeError('%r is an invalid keyword argument for %s' %
(k, type(self).__name__))
setattr(self, k, kwargs[k])
return Base
def _undefer_column_name(key, column):
if column.key is None:
column.key = key
if column.name is None:
column.name = key
| {
"repo_name": "santisiri/popego",
"path": "envs/ALPHA-POPEGO/lib/python2.5/site-packages/SQLAlchemy-0.4.5-py2.5.egg/sqlalchemy/ext/declarative.py",
"copies": "1",
"size": "12263",
"license": "bsd-3-clause",
"hash": -4247977103249374700,
"line_mean": 36.9659442724,
"line_max": 264,
"alpha_frac": 0.6321454783,
"autogenerated": false,
"ratio": 4.29076277116865,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.542290824946865,
"avg_score": null,
"num_lines": null
} |
# A simple demo for working with SparkSQL and Tweets
from pyspark import SparkContext, SparkConf
from pyspark.sql import HiveContext, Row, IntegerType
import json
import sys
if __name__ == "__main__":
inputFile = sys.argv[1]
conf = SparkConf().setAppName("SparkSQLTwitter")
sc = SparkContext()
hiveCtx = HiveContext(sc)
print "Loading tweets from " + inputFile
input = hiveCtx.jsonFile(inputFile)
input.registerTempTable("tweets")
topTweets = hiveCtx.sql("SELECT text, retweetCount FROM tweets ORDER BY retweetCount LIMIT 10")
print topTweets.collect()
topTweetText = topTweets.map(lambda row : row.text)
print topTweetText.collect()
# Make a happy person row
happyPeopleRDD = sc.parallelize([Row(name="holden", favouriteBeverage="coffee")])
happyPeopleSchemaRDD = hiveCtx.inferSchema(happyPeopleRDD)
happyPeopleSchemaRDD.registerTempTable("happy_people")
# Make a UDF to tell us how long some text is
hiveCtx.registerFunction("strLenPython", lambda x: len(x), IntegerType())
lengthSchemaRDD = hiveCtx.sql("SELECT strLenPython('text') FROM tweets LIMIT 10")
print lengthSchemaRDD.collect()
sc.stop()
| {
"repo_name": "obulpathi/spark",
"path": "python/SparkSQLTwitter.py",
"copies": "1",
"size": "1181",
"license": "apache-2.0",
"hash": 4833822594423833000,
"line_mean": 42.7407407407,
"line_max": 99,
"alpha_frac": 0.7298899238,
"autogenerated": false,
"ratio": 3.5253731343283583,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47552630581283584,
"avg_score": null,
"num_lines": null
} |
# A simple demo for working with SparkSQL and Tweets
from pyspark import SparkContext, SparkConf
from pyspark.sql import HiveContext, Row
from pyspark.sql.types import IntegerType
import json
import sys
if __name__ == "__main__":
inputFile = sys.argv[1]
conf = SparkConf().setAppName("SparkSQLTwitter")
sc = SparkContext()
hiveCtx = HiveContext(sc)
print "Loading tweets from " + inputFile
input = hiveCtx.jsonFile(inputFile)
input.registerTempTable("tweets")
topTweets = hiveCtx.sql("SELECT text, retweetCount FROM tweets ORDER BY retweetCount LIMIT 10")
print topTweets.collect()
topTweetText = topTweets.map(lambda row : row.text)
print topTweetText.collect()
# Make a happy person row
happyPeopleRDD = sc.parallelize([Row(name="holden", favouriteBeverage="coffee")])
happyPeopleSchemaRDD = hiveCtx.inferSchema(happyPeopleRDD)
happyPeopleSchemaRDD.registerTempTable("happy_people")
# Make a UDF to tell us how long some text is
hiveCtx.registerFunction("strLenPython", lambda x: len(x), IntegerType())
lengthSchemaRDD = hiveCtx.sql("SELECT strLenPython('text') FROM tweets LIMIT 10")
print lengthSchemaRDD.collect()
sc.stop()
| {
"repo_name": "ellis429/learning-spark",
"path": "src/python/SparkSQLTwitter.py",
"copies": "41",
"size": "1210",
"license": "mit",
"hash": 6566359725863214000,
"line_mean": 42.2142857143,
"line_max": 99,
"alpha_frac": 0.7330578512,
"autogenerated": false,
"ratio": 3.538011695906433,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0018254627432368296,
"num_lines": 28
} |
"""A simple demonstration of LKD to activate PEBS and BTS feature from intel CPU"""
import ctypes
import sys
import os
if os.getcwd().endswith("example"):
sys.path.append(os.path.realpath(".."))
else:
sys.path.append(os.path.realpath("."))
from windows.generated_def.winstructs import *
from dbginterface import LocalKernelDebugger
# What is BTS?:
# Branch Trace Store (BTS) is an intel's CPU feature that allows to
# store all the branches (src and dst) taken on a CPU to a buffer
#
# To activate the BTS you need to:
# setup the Debug Store (DS) Area
# setup the BTS related fields in DS
# activate BTS
# see in man intel:
# http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-manual-325462.pdf
# Volume 3B: System Programming Guide 17.4.5 (Branch Trace Store (BTS))
# Volume 3B: System Programming Guide 17.4.9 (BTS and DS area)
# !! BTS buffer can be configured to be circular or not (see 17.4.9.3 (Setting Up the BTS Buffer))
# What is PEBS?:
# Precise Event Based Sampling (PEBS) is an intel's CPU feature that allows to
# store the CPU states (general purpose registers) at a given event.
# This feature rely on the performance counter
# To activate the PEBS you need to:
# Setup the Debug Store (DS) Area
# Setup the PEBS related fields in DS
# Setup the performance counter that will trigger the PEBS (PERFEVTSE0) here
# Activate PEBS
# Activate the counter
# see in man intel: (lot of micro-architecture stuff here)
# http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-manual-325462.pdf
# Volume 3B: System Programming Guide 18.4 (PERFORMANCE MONITORING (PROCESSORS BASED ON INTELCORE MICROARCHITECTURE)
# Volume 3B: System Programming Guide 18.4.4 (Precise Event Based Sampling (PEBS))
# Volume 3B: System Programming Guide 18.7 (PERFORMANCE MONITORING FOR PROCESSORS BASED ON INTEL MICROARCHITECTURE CODE NAME NEHALEM)
# Volume 3B: System Programming Guide 18.7.1.1 (Precise Event Based Sampling (PEBS))
# TLDR:
# PEBS will trigger a dump of the PEBSRecord (general purpose registers + some other info) when
# the associated performance counter overflow (PERFEVTSE0 in this code) then
# the performance counter value is reset to DsManagementAreaStruct.PEBSCounterResetValue
# So if you want to dump the state of the proc often you should set this to a high value
# !! THE PEBS BUFFER IS NOT circular
# you need the reset it manually when the good interrupt is raise (see 18.4.4.3 (Writing a PEBS Interrupt Service Routine))
# This require to inject some code in kerneland (not done in this example)
DEBUG_STORE_MSR_VALUE = 0x600
IA32_DEBUGCTL_MSR_VALUE = 0x1D9
IA32_MISC_ENABLE = 0x1A0
MSR_PEBS_ENABLED = 0x3F1
MSR_PERF_GLOBAL_CTRL = 0x38f
PERF_CAPABILITIES = 0x345
IA32_PMC0 = 0xC1
PERFEVTSE0 = 0x186
PERFEVTSE1 = 0x186 + 1
PERFEVTSE2 = 0x186 + 2
PERFEVTSE3 = 0x186 + 3
PEBS_RECORD_COUNTER_VALUE = 0xffffffffff920000
# Mask for IA32_MISC_ENABLE
# YES this is really BTS_UNAVILABLE in the intel man :D
BTS_UNAVILABLE = 1 << 11
PEBS_UNAVILABLE = 1 << 12
UMON_AVAILABLE = 1 << 7
class DsManagementAreaStruct(ctypes.Structure):
"""The DS management area for 64bits processors"""
_fields_ = [("BtsBufferBase", ULONG64),
("BtsIndex", ULONG64),
("BtsAbsoluteMaximum", ULONG64),
("BTSThresholdinterupt", ULONG64),
("PEBSBufferBase", ULONG64),
("PEBSIndex", ULONG64),
("PEBSAbsoluteMaximum", ULONG64),
("PEBSThresholdinterupt", ULONG64),
("PEBSCounterResetValue", ULONG64), # should be 40bits field
("PEBSCounterResetValue2", ULONG64), # hack to set it to 0
("Stuff1", ULONG64),
("Stuff2", ULONG64),
]
class BtsRecord(ctypes.Structure):
_fields_ = [("BranchFrom", ULONG64),
("BranchTo", ULONG64),
("Stuff", ULONG64)
]
# 18-58 in http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-vol-3b-part-2-manual.html
# Thanks to https://github.com/andikleen/pmu-tools/blob/master/pebs-grabber/pebs-grabber.c
class PEBSRecordV0(ctypes.Structure):
_fields_ = [("rflags", ULONG64),
("rip", ULONG64),
("rax", ULONG64),
("rbx", ULONG64),
("rcx", ULONG64),
("rdx", ULONG64),
("rsi", ULONG64),
("rdi", ULONG64),
("rbp", ULONG64),
("rsp", ULONG64),
("r8", ULONG64),
("r9", ULONG64),
("r10", ULONG64),
("r11", ULONG64),
("r12", ULONG64),
("r13", ULONG64),
("r14", ULONG64),
("r15", ULONG64)
]
class PEBSRecordV1(PEBSRecordV0):
_fields_ = [("IA32_PERF_FLOBAL_STATUS", ULONG64),
("DataLinearAddress", ULONG64),
("DaaSourceEncoding", ULONG64),
("LatencyValue", ULONG64),
]
class PEBSRecordV2(PEBSRecordV1):
_fields_ = [("EventingIP", ULONG64),
("TXAbortInformation", ULONG64),
]
def check_feature(kdbg):
"""Check that BTS and PEBS features are available"""
misc_enabled = kdbg.read_msr(IA32_MISC_ENABLE)
if misc_enabled & BTS_UNAVILABLE:
print("NO BTS")
if misc_enabled & PEBS_UNAVILABLE:
print("NO PEBS")
if not misc_enabled & UMON_AVAILABLE:
print("UMON NOT AVAILABLE")
# ================================= BTS
class BTSManager(object):
def __init__(self, kdbg):
self.kdbg = kdbg
def setup_DsManagementArea(self, proc_nb):
"""Setup the setup_DsManagementArea for the proc `proc_nb`
proc_nb must be the number of the current processor
The write to nt!VfBTSDataManagementArea is where ntokrnl store this information"""
ds_addr, ds_content = self.get_DsManagementArea(proc_nb)
if ds_addr:
return
ds_management_area_addr = self.kdbg.alloc_memory(0x1000)
kdbg.write_virtual_memory(ds_management_area_addr, "\x00" * 0x1000)
VfBTSDataManagementArea = kdbg.get_symbol_offset("nt!VfBTSDataManagementArea")
kdbg.write_ptr(VfBTSDataManagementArea + proc_nb * ctypes.sizeof(PVOID), ds_management_area_addr)
kdbg.write_msr(DEBUG_STORE_MSR_VALUE, ds_management_area_addr)
def get_DsManagementArea(self, proc_nb):
"""Return the DsManagementAreaStruct and address for the `proc_nb` processor"""
VfBTSDataManagementArea = kdbg.get_symbol_offset("nt!VfBTSDataManagementArea")
DataManagementAreaProcX = kdbg.read_ptr(VfBTSDataManagementArea + proc_nb * ctypes.sizeof(PVOID))
if DataManagementAreaProcX == 0:
return 0, None
DsManagementAreaContent = DsManagementAreaStruct()
self.kdbg.read_virtual_memory_into(DataManagementAreaProcX, DsManagementAreaContent)
return (DataManagementAreaProcX, DsManagementAreaContent)
def setup_BTS(self, proc_nb, buffer_size=0x1000):
"""Setup the DsManagementArea BTS fields for proc `proc_nb`"""
ds_addr, ds_content = self.get_DsManagementArea(proc_nb)
buffer_addr = kdbg.alloc_memory(buffer_size)
ds_content.BtsBufferBase = buffer_addr
ds_content.BtsIndex = buffer_addr
ds_content.BtsAbsoluteMaximum = buffer_addr + buffer_size + 1
ds_content.BtsThresholdinterupt = 0 # or buffer_addr + buffer_size + 1 to trigger it
self.kdbg.write_virtual_memory(ds_addr, ds_content)
def stop_BTS(self):
"""Stop BTS on current processor"""
kdbg.write_msr(IA32_DEBUGCTL_MSR_VALUE, 0x0)
def start_BTS(self, enable, off_user=0, off_os=0):
"""Start the BTS (see 17.4.1 IA32_DEBUGCTL MSR) as circular buffer"""
value = enable << 6 | enable << 7 | off_user << 10 | off_os << 9
kdbg.write_msr(IA32_DEBUGCTL_MSR_VALUE, value)
def get_number_bts_records(self, proc_nb):
"""Get the number of BTS entries stored in the buffer for proc `proc_nb`"""
ds_addr, ds_content = self.get_DsManagementArea(proc_nb)
return (ds_content.BtsIndex - ds_content.BtsBufferBase) / ctypes.sizeof(BtsRecord)
def get_bts_records(self, proc_nb, max_dump=0xffffffffffffffff):
"""Get the BTS entries stored in the buffer for proc `proc_nb`"""
ds_addr, ds_content = self.get_DsManagementArea(proc_nb)
nb_bts_entry = self.get_number_bts_records(proc_nb)
print("Buffer contains {0} entries".format(nb_bts_entry))
nb_bts_entry = min(nb_bts_entry, max_dump)
print("Dumping {0} first entries".format(nb_bts_entry))
bts_entries_buffer = (BtsRecord * nb_bts_entry)()
kdbg.read_virtual_memory_into(ds_content.BtsBufferBase, bts_entries_buffer)
return bts_entries_buffer
def dump_bts(self):
ds_addr, ds_content = self.get_DsManagementArea(0)
print("BtsBufferBase = {0}".format(hex(ds_content.BtsBufferBase)))
records = self.get_bts_records(0, max_dump=20)
for rec in records:
from_sym, from_disp = kdbg.get_symbol(rec.BranchFrom)
from_disp = hex(from_disp) if from_disp is not None else None
from_str = "Jump {0} ({1} + {2})".format(hex(rec.BranchFrom), from_sym, from_disp)
to_sym, to_disp = kdbg.get_symbol(rec.BranchTo)
to_disp = hex(to_disp) if to_disp is not None else None
to_str = "Jump {0} ({1} + {2})".format(hex(rec.BranchTo), to_sym, to_disp)
print("{0} -> {1}".format(from_str, to_str))
# ================================= PEBS
class PEBSManager(object):
def __init__(self, kdbg):
self.kdbg = kdbg
pebs_record_v = self.get_pebs_records_version()
if pebs_record_v == 0:
self.PEBSRecord = PEBSRecordV0
elif pebs_record_v == 1:
self.PEBSRecord = PEBSRecordV1
elif pebs_record_v == 2:
self.PEBSRecord = PEBSRecordV2
else:
raise ValueError("Don't know the format of PEBS Records of version {0}".format(pebs_record_v))
def setup_perfevtsel0(self, enable, mask=0, eventselect=0xc0, user_mod=1, os_mod=1):
"""Setup the PERFEVTSE0 MSR to manage the IA32_PMC0 perf counter
Default eventselect 0xc0 is 'Instruction retired'"""
# Instruction retired
MASK = mask << 8
EVENTSELECT = eventselect << 0
USER_MOD = user_mod << 16
OS_MOD = os_mod << 17
ENABLE = enable << 22
value = MASK | EVENTSELECT | USER_MOD | OS_MOD | ENABLE
self.kdbg.write_msr(PERFEVTSE0, value)
def get_pebs_records_version(self):
return (self.kdbg.read_msr(PERF_CAPABILITIES) >> 8) & 0xf
def setup_DsManagementArea(self, proc_nb):
"""Setup the setup_DsManagementArea for the proc `proc_nb`
proc_nb must be the number of the current processor
The write to nt!VfBTSDataManagementArea is where ntokrnl store this information"""
ds_addr, ds_content = self.get_DsManagementArea(proc_nb)
if ds_addr:
return
ds_management_area_addr = self.kdbg.alloc_memory(0x1000)
self.kdbg.write_virtual_memory(ds_management_area_addr, "\x00" * 0x1000)
VfBTSDataManagementArea = kdbg.get_symbol_offset("nt!VfBTSDataManagementArea")
kdbg.write_ptr(VfBTSDataManagementArea + proc_nb * ctypes.sizeof(PVOID), ds_management_area_addr)
kdbg.write_msr(DEBUG_STORE_MSR_VALUE, ds_management_area_addr)
def get_DsManagementArea(self, proc_nb):
"""Return the DsManagementAreaStruct and address for the `proc_nb` processor"""
VfBTSDataManagementArea = kdbg.get_symbol_offset("nt!VfBTSDataManagementArea")
DataManagementAreaProcX = kdbg.read_ptr(VfBTSDataManagementArea + proc_nb * ctypes.sizeof(PVOID))
if DataManagementAreaProcX == 0:
return 0, None
DsManagementAreaContent = DsManagementAreaStruct()
self.kdbg.read_virtual_memory_into(DataManagementAreaProcX, DsManagementAreaContent)
return (DataManagementAreaProcX, DsManagementAreaContent)
def setup_pebs(self, proc_nb, buffer_size=0x1000):
"""Setup de DsManagementArea PEBS fields for proc `proc_nb`"""
ds_addr, ds_content = self.get_DsManagementArea(proc_nb)
buffer_addr = kdbg.alloc_memory(buffer_size)
ds_content.PEBSBufferBase = buffer_addr
ds_content.PEBSIndex = buffer_addr
ds_content.PEBSAbsoluteMaximum = buffer_addr + buffer_size + 1
ds_content.PEBSThresholdinterupt = 0 # or buffer_addr + buffer_size + 1 to trigger it
ds_content.PEBSThresholdinterupt = 0
ds_content.PEBSCounterResetValue = PEBS_RECORD_COUNTER_VALUE
ds_content.PEBSCounterResetValue2 = 0xffffffffffffffff
self.kdbg.write_virtual_memory(ds_addr, ds_content)
def stop_PEBS(self):
# Does the second line is enough ?
self.kdbg.write_msr(PERFEVTSE0, 0)
self.kdbg.write_msr(MSR_PERF_GLOBAL_CTRL, 0)
self.kdbg.write_msr(MSR_PEBS_ENABLED, 0)
def start_PEBS(self):
"""Start the PEBS by:
Setup the event counter associated with PEBS (perfevtsel0)
Enable PEBS
Enable the counter perfevtsel0
"""
# Stop counter IA32_PMC0 (needed to write it)
self.stop_PEBS()
# 0xc0 -> Instruction retired
self.setup_perfevtsel0(enable=1, mask=0, eventselect=0xc0, user_mod=1, os_mod=1)
# TODO: change counter value (sign extended)
kdbg.write_msr(IA32_PMC0, 0xfffa0000)
# Activate PEBS
kdbg.write_msr(MSR_PEBS_ENABLED, 1)
# Re-activate IA32_PMC0
kdbg.write_msr(MSR_PERF_GLOBAL_CTRL, 1)
# PEBS records getters
def get_number_pebs_records(self, proc_nb):
"""Get the number of PEBS entries stored in the buffer for proc `proc_nb`"""
ds_addr, ds_content = self.get_DsManagementArea(proc_nb)
return (ds_content.PEBSIndex - ds_content.PEBSBufferBase) / ctypes.sizeof(self.PEBSRecord)
def get_pebs_records(self, proc_nb, max_dump=0xffffffffffffffff):
"""Get the PEBS entries stored in the buffer for proc `proc_nb`"""
ds_addr, ds_content = self.get_DsManagementArea(proc_nb)
nb_pebs_entry = self.get_number_pebs_records(proc_nb)
print("Buffer contains {0} entries".format(nb_pebs_entry))
nb_pebs_entry = min(nb_pebs_entry, max_dump)
print("Dumping {0} first entries".format(nb_pebs_entry))
pebs_entries_buffer = (self.PEBSRecord * nb_pebs_entry)()
kdbg.read_virtual_memory_into(ds_content.PEBSBufferBase, pebs_entries_buffer)
return pebs_entries_buffer
def dump_PEBS_records(self):
ds_addr, ds_content = self.get_DsManagementArea(proc_nb)
print("PEBSBufferBase = {0}".format(hex(ds_content.PEBSBufferBase)))
x = self.get_pebs_records(0)
for pebs_record in x:
print(" {0} = {1}".format("rip", hex(pebs_record.rip)))
# BTS
kdbg = LocalKernelDebugger()
check_feature(kdbg)
kdbg.reload()
kdbg.set_current_processor(0)
btsm = BTSManager(kdbg)
btsm.setup_DsManagementArea(0)
btsm.setup_BTS(0, buffer_size=0x100000)
btsm.start_BTS(enable=1)
import time
time.sleep(1)
btsm.stop_BTS()
btsm.dump_bts()
# # PEBS
# kdbg = LocalKernelDebugger()
# check_feature(kdbg)
# kdbg.set_current_processor(0)
# pebsm = PEBSManager(kdbg)
# pebsm.setup_DsManagementArea(0)
# pebsm.setup_pebs(0, buffer_size=0x1000)
# pebsm.start_PEBS()
# pebsm.dump_PEBS_records()
# import time
# time.sleep(1)
# pebsm.dump_PEBS_records()
# pebsm.stop_PEBS()
| {
"repo_name": "sogeti-esec-lab/LKD",
"path": "example/PEBS_BTS_demo.py",
"copies": "1",
"size": "15967",
"license": "bsd-3-clause",
"hash": -8204539970150006000,
"line_mean": 41.4654255319,
"line_max": 145,
"alpha_frac": 0.6478987913,
"autogenerated": false,
"ratio": 3.217207334273625,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9348323132966302,
"avg_score": 0.0033565985214646216,
"num_lines": 376
} |
"""A simple demonstration of LKD to display IDT and KINTERRUPT associated"""
import sys
import ctypes
import os
if os.getcwd().endswith("example"):
sys.path.append(os.path.realpath(".."))
else:
sys.path.append(os.path.realpath("."))
import windows
from windows.generated_def.winstructs import *
from dbginterface import LocalKernelDebugger
# lkd> dt nt!_KIDTENTRY
# +0x000 Offset : Uint2B
# +0x002 Selector : Uint2B
# +0x004 Access : Uint2B
# +0x006 ExtendedOffset : Uint2B
# Struct _IDT32 definitions
class _IDT32(ctypes.Structure):
_fields_ = [
("Offset", WORD),
("Selector", WORD),
("Access", WORD),
("ExtendedOffset", WORD)
]
PIDT32 = POINTER(_IDT32)
IDT32 = _IDT32
# lkd> dt nt!_KIDTENTRY64
# +0x000 OffsetLow : Uint2B
# +0x002 Selector : Uint2B
# +0x004 IstIndex : Pos 0, 3 Bits
# +0x004 Reserved0 : Pos 3, 5 Bits
# +0x004 Type : Pos 8, 5 Bits
# +0x004 Dpl : Pos 13, 2 Bits
# +0x004 Present : Pos 15, 1 Bit
# +0x006 OffsetMiddle : Uint2B
# +0x008 OffsetHigh : Uint4B
# +0x00c Reserved1 : Uint4B
# +0x000 Alignment : Uint8B
# Struct _IDT64 definitions
class _IDT64(ctypes.Structure):
_fields_ = [
("OffsetLow", WORD),
("Selector", WORD),
("IstIndex", WORD),
("OffsetMiddle", WORD),
("OffsetHigh", DWORD),
("Reserved1", DWORD)
]
PIDT64 = POINTER(_IDT64)
IDT64 = _IDT64
# lkd> dt nt!_KINTERRUPT Type DispatchCode
# +0x000 Type : Int2B
# +0x090 DispatchCode : [4] Uint4B
def get_kinterrupt_64(kdbg, addr_entry):
# You can get the type ID of any name from module to which the type belongs
# IDebugSymbols::GetTypeId
# https://msdn.microsoft.com/en-us/library/windows/hardware/ff549376%28v=vs.85%29.aspx
KINTERRUPT = kdbg.get_type_id("nt", "_KINTERRUPT")
# You can get the offset of a symbol identified by its name
# IDebugSymbols::GetOffsetByName
# https://msdn.microsoft.com/en-us/library/windows/hardware/ff548035(v=vs.85).aspx
dispatch_code_offset = kdbg.get_field_offset("nt", KINTERRUPT, "DispatchCode")
type_offset = kdbg.get_field_offset("nt", KINTERRUPT, "Type")
addr_kinterrupt = addr_entry - dispatch_code_offset
# Read a byte from virtual memory
# IDebugDataSpaces::ReadVirtual
# https://msdn.microsoft.com/en-us/library/windows/hardware/ff554359(v=vs.85).aspx
type = kdbg.read_byte(addr_kinterrupt + type_offset)
if type == 0x16:
return addr_kinterrupt
else:
return None
# lkd> dt nt!_KPCR IdtBase
# +0x038 IdtBase : Ptr64 _KIDTENTRY64
# ...
# lkd> dt nt!_UNEXPECTED_INTERRUPT
# +0x000 PushImm : UChar
# +0x001 Vector : UChar
# +0x002 PushRbp : UChar
# +0x003 JmpOp : UChar
# +0x004 JmpOffset : Int4B
def get_idt_64(kdbg, num_proc=0):
l_idt = []
DEBUG_DATA_KPCR_OFFSET = 0
KPCR = kdbg.get_type_id("nt", "_KPCR")
# You can get the number of bytes of memory an instance of the specified type requires
# IDebugSymbols::GetTypeSize
# https://msdn.microsoft.com/en-us/library/windows/hardware/ff549457(v=vs.85).aspx
size_unexpected_interrupt = kdbg.get_type_size("nt", "_UNEXPECTED_INTERRUPT")
idt_base_offset = kdbg.get_field_offset("nt", KPCR, "IdtBase")
# You can get the location (VA) of a symbol identified by its name
# IDebugSymbols::GetOffsetByName
# https://msdn.microsoft.com/en-us/library/windows/hardware/ff548035(v=vs.85).aspx
addr_nt_KxUnexpectedInterrupt0 = kdbg.get_symbol_offset("nt!KxUnexpectedInterrupt0")
# You can data by their type about the specified processor
# IDebugDataSpaces::ReadProcessorSystemData
# https://msdn.microsoft.com/en-us/library/windows/hardware/ff554326(v=vs.85).aspx
kpcr_addr = kdbg.read_processor_system_data(num_proc, DEBUG_DATA_KPCR_OFFSET)
# You can read a pointer-size value, it doesn't depend of the target computer's architecture processor
idt_base = kdbg.read_ptr(kpcr_addr + idt_base_offset)
for i in xrange(0, 0xFF):
idt64 = IDT64()
# You can read data from virtual address into a ctype structure
kdbg.read_virtual_memory_into(idt_base + i * sizeof(IDT64), idt64)
addr = (idt64.OffsetHigh << 32) | (idt64.OffsetMiddle << 16) | idt64.OffsetLow
if addr < addr_nt_KxUnexpectedInterrupt0 or addr > (addr_nt_KxUnexpectedInterrupt0 + 0xFF * size_unexpected_interrupt):
l_idt.append((addr, get_kinterrupt_64(kdbg, addr)))
else:
l_idt.append((None, None))
return l_idt
# lkd> dt nt!_KPCR PrcbData.VectorToInterruptObject
# +0x120 PrcbData :
# +0x41a0 VectorToInterruptObject : [208] Ptr32 _KINTERRUPT
# ...
# lkd> dt nt!_KINTERRUPT Type
# +0x000 Type : Int2B
def get_kinterrupt_32(kdbg, kpcr_addr, index):
KPCR = kdbg.get_type_id("nt", "_KPCR")
KINTERRUPT = kdbg.get_type_id("nt", "_KINTERRUPT")
pcrbdata_offset = kdbg.get_field_offset("nt", KPCR, "PrcbData.VectorToInterruptObject")
type_offset = kdbg.get_field_offset("nt", KINTERRUPT, "Type")
if index < 0x30:
return None
addr_kinterrupt = kdbg.read_ptr(kpcr_addr + pcrbdata_offset + (4 * index - 0xC0))
if addr_kinterrupt == 0:
return None
type = kdbg.read_byte(addr_kinterrupt + type_offset)
if type == 0x16:
return addr_kinterrupt
return None
# lkd> dt nt!_KPCR IDT
# +0x038 IDT : Ptr32 _KIDTENTRY
# +0x120 PrcbData :
# +0x41a0 VectorToInterruptObject : [208] Ptr32 _KINTERRUPT
def get_idt_32(kdbg, num_proc=0):
l_idt = []
DEBUG_DATA_KPCR_OFFSET = 0
KPCR = kdbg.get_type_id("nt", "_KPCR")
idt_base_offset = kdbg.get_field_offset("nt", KPCR, "IDT")
try:
pcrbdata_offset = kdbg.get_field_offset("nt", KPCR, "PrcbData.VectorToInterruptObject")
except WindowsError:
pcrbdata_offset = 0
addr_nt_KiStartUnexpectedRange = kdbg.get_symbol_offset("nt!KiStartUnexpectedRange")
addr_nt_KiEndUnexpectedRange = kdbg.get_symbol_offset("nt!KiEndUnexpectedRange")
if pcrbdata_offset == 0:
get_kinterrupt = lambda kdbg, addr, kpcr, i: get_kinterrupt_64(kdbg, addr)
else:
get_kinterrupt = lambda kdbg, addr, kpcr, i: get_kinterrupt_32(kdbg, kpcr, i)
kpcr_addr = kdbg.read_processor_system_data(num_proc, DEBUG_DATA_KPCR_OFFSET)
idt_base = kdbg.read_ptr(kpcr_addr + idt_base_offset)
for i in xrange(0, 0xFF):
idt32 = IDT32()
kdbg.read_virtual_memory_into(idt_base + i * sizeof(IDT32), idt32)
if (idt32.ExtendedOffset == 0 or idt32.Offset == 0):
l_idt.append((None, None))
continue
addr = (idt32.ExtendedOffset << 16) | idt32.Offset
if (addr < addr_nt_KiStartUnexpectedRange or addr > addr_nt_KiEndUnexpectedRange):
l_idt.append((addr, get_kinterrupt(kdbg, addr, kpcr_addr, i)))
else:
addr_kinterrupt = get_kinterrupt(kdbg, addr, kpcr_addr, i)
if addr_kinterrupt is None:
addr = None
l_idt.append((addr, addr_kinterrupt))
return l_idt
if __name__ == '__main__':
kdbg = LocalKernelDebugger()
if windows.current_process.bitness == 32:
l_idt = get_idt_32(kdbg)
else:
l_idt = get_idt_64(kdbg)
for i in range(len(l_idt)):
if l_idt[i][0] is not None:
if l_idt[i][1] is not None:
print("0x{0:02X} {1} {2} (KINTERRUPT {3})".format(i, hex(l_idt[i][0]), kdbg.get_symbol(l_idt[i][0])[0], hex(l_idt[i][1])))
else:
print("0x{0:02X} {1} {2}".format(i, hex(l_idt[i][0]), kdbg.get_symbol(l_idt[i][0])[0]))
| {
"repo_name": "sogeti-esec-lab/LKD",
"path": "example/idt.py",
"copies": "1",
"size": "7877",
"license": "bsd-3-clause",
"hash": 718459165089433200,
"line_mean": 38.1890547264,
"line_max": 138,
"alpha_frac": 0.6252380348,
"autogenerated": false,
"ratio": 2.951292618958411,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9066128651626815,
"avg_score": 0.0020804004263192295,
"num_lines": 201
} |
"""A simple demonstration of the output possibilities of the LDK"""
import sys
import os
if os.getcwd().endswith("example"):
sys.path.append(os.path.realpath(".."))
else:
sys.path.append(os.path.realpath("."))
from dbginterface import LocalKernelDebugger
# A default LKD can be quiet or not
# A quiet LKD will have no output
# A noisy one will have the exact same output as windbg
kdbg = LocalKernelDebugger(quiet=True)
# With a quiet LKD this ligne will have no output
print('Executing "lm m nt*" in quiet LKD')
kdbg.execute("lm m nt*")
# To change the quiet state of the LKD just set the variable 'quiet'
kdbg.quiet = False
print("")
print('Executing "lm m nt*" in noisy LKD')
kdbg.execute("lm m nt*")
# If you want to parse the output of a command, kdbg.execute accept the argument 'to_string'
# A command with to_string=True will have no output, even with quiet=False
print("")
disas = kdbg.execute("u nt!NtCreateFile", to_string=True)
print('Here is the 3rd line of the command "u nt!NtCreateFile"')
print(disas.split("\n")[2])
# You can also register a new output callabck that must respect the interface
# IDebugOutputCallbacks::Output (https://msdn.microsoft.com/en-us/library/windows/hardware/ff550815%28v=vs.85%29.aspx)
def my_output_callback(comobj, mask, text):
print("NEW MESSAGE <{0}>".format(repr(text)))
# mysocket.send(text)
return 0
kdbg.set_output_callbacks(my_output_callback)
print("")
print('Executing "u nt!NtCreateFile L1" with custom output callback')
kdbg.execute("u nt!NtCreateFile L1")
| {
"repo_name": "sogeti-esec-lab/LKD",
"path": "example/output_demo.py",
"copies": "1",
"size": "1542",
"license": "bsd-3-clause",
"hash": -1595088525799796000,
"line_mean": 34.0454545455,
"line_max": 118,
"alpha_frac": 0.7328145266,
"autogenerated": false,
"ratio": 3.146938775510204,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9375106122570276,
"avg_score": 0.0009294359079855326,
"num_lines": 44
} |
"""A simple demo of new RNN cell with PTB language model."""
import os
import argparse
import numpy as np
import mxnet as mx
from bucket_io import MyBucketSentenceIter, BucketSentenceIter, default_build_vocab
#os.environ["MXNET_CUDNN_AUTOTUNE_DEFAULT"] = "1"
#data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))
def Perplexity(label, pred):
# collapse the time, batch dimension
label = label.reshape((-1,))
pred = pred.reshape((-1, pred.shape[-1]))
loss = 0.
for i in range(pred.shape[0]):
loss += -np.log(max(1e-10, pred[i][int(label[i])]))
return np.exp(loss / label.size)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='train rnn lstm with ptb')
parser.add_argument('--data-dir', type=str, help='the input data directory')
parser.add_argument('--gpus', type=str,
help='the gpus will be used, e.g "0,1,2,3"')
parser.add_argument('--sequence-lens', type=str, default="32",
help='the sequence lengths, e.g "8,16,32,64,128"')
parser.add_argument('--batch-size', type=int, default=128,
help='the batch size')
parser.add_argument('--num-hidden', type=int, default=256,
help='size of the state for each lstm layer')
parser.add_argument('--num-embed', type=int, default=256,
help='dim of embedding')
parser.add_argument('--num-lstm-layer', type=int, default=2,
help='the numebr of lstm layers')
parser.add_argument('--lr', type=float, default=0.01,
help='learning rate')
parser.add_argument('--model-prefix', type=str,
help='the prefix of the model to load')
parser.add_argument('--num-examples', type=str,
help='Flag for consistancy, no use in rnn')
parser.add_argument('--save-model-prefix', type=str,
help='the prefix of the model to save')
parser.add_argument('--num-epochs', type=int, default=20,
help='the number of training epochs')
parser.add_argument('--load-epoch', type=int,
help='load the model on an epoch using the model-prefix')
parser.add_argument('--kv-store', type=str, default='local',
help='the kvstore type')
args = parser.parse_args()
data_dir = os.environ['HOME'] + "/data/mxnet/ptb/" if args.data_dir is None else args.data_dir
batch_size = args.batch_size
#buckets = [64] #[10, 20, 30, 40, 50, 60]
buckets = [int(i) for i in args.sequence_lens.split(',')] #[8,16,32,64,128]
num_hidden = args.num_hidden
num_embed = args.num_embed
num_lstm_layer = args.num_lstm_layer
num_epoch = args.num_epochs
learning_rate = args.lr
momentum = 0.0
contexts = mx.context.cpu() if args.gpus is None else [mx.context.gpu(int(i)) for i in args.gpus.split(',')]
vocab = default_build_vocab(os.path.join(data_dir, 'ptb.train.txt'))
print("Size of ptb.train.txt vocab: " + str(len(vocab)))
init_h = [('LSTM_state', (num_lstm_layer, batch_size, num_hidden))]
init_c = [('LSTM_state_cell', (num_lstm_layer, batch_size, num_hidden))]
init_states = init_c + init_h
data_train = MyBucketSentenceIter(os.path.join(data_dir, 'ptb.train.txt'),
vocab, buckets, batch_size, init_states,
time_major=True)
#data_val = MyBucketSentenceIter(os.path.join(data_dir, 'ptb.valid.txt'), vocab, buckets, batch_size, init_states, time_major=True)
sample_size = 0
for x in data_train.data:
sample_size += len(x)
print("len of data train===================== " + str(sample_size))
def sym_gen(seq_len):
data = mx.sym.Variable('data')
label = mx.sym.Variable('softmax_label')
embed = mx.sym.Embedding(data=data, input_dim=len(vocab),
output_dim=num_embed, name='embed')
# TODO(tofix)
# currently all the LSTM parameters are concatenated as
# a huge vector, and named '<name>_parameters'. By default
# mxnet initializer does not know how to initilize this
# guy because its name does not ends with _weight or _bias
# or anything familiar. Here we just use a temp workaround
# to create a variable and name it as LSTM_bias to get
# this demo running. Note by default bias is initialized
# as zeros, so this is not a good scheme. But calling it
# LSTM_weight is not good, as this is 1D vector, while
# the initialization scheme of a weight parameter needs
# at least two dimensions.
rnn_params = mx.sym.Variable('LSTM_bias')
# RNN cell takes input of shape (time, batch, feature)
rnn = mx.sym.RNN(data=embed, state_size=num_hidden,
num_layers=num_lstm_layer, mode='lstm',
name='LSTM',
# The following params can be omitted
# provided we do not need to apply the
# workarounds mentioned above
parameters=rnn_params)
# the RNN cell output is of shape (time, batch, dim)
# if we need the states and cell states in the last time
# step (e.g. when building encoder-decoder models), we
# can set state_outputs=True, and the RNN cell will have
# extra outputs: rnn['LSTM_output'], rnn['LSTM_state']
# and for LSTM, also rnn['LSTM_state_cell']
# now we collapse the time and batch dimension to do the
# final linear logistic regression prediction
hidden = mx.sym.Reshape(data=rnn, shape=(-1, num_hidden))
pred = mx.sym.FullyConnected(data=hidden, num_hidden=len(vocab),
name='pred')
# reshape to be of compatible shape as labels
pred_tm = mx.sym.Reshape(data=pred, shape=(seq_len, -1, len(vocab)))
sm = mx.sym.SoftmaxOutput(data=pred_tm, label=label, preserve_shape=True,
name='softmax')
data_names = ['data', 'LSTM_state', 'LSTM_state_cell']
label_names = ['softmax_label']
return (sm, data_names, label_names)
if len(buckets) == 1:
mod = mx.mod.Module(*sym_gen(buckets[0]), context=contexts)
else:
mod = mx.mod.BucketingModule(sym_gen,
default_bucket_key=data_train.default_bucket_key,
context=contexts)
print(args)
print("Start training...")
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
mod.fit(
data_train,
# eval_data=data_val,
num_epoch=num_epoch,
eval_metric=mx.metric.np(Perplexity),
#batch_end_callback=mx.callback.Speedometer(batch_size, int((sample_size-1)/batch_size)),
batch_end_callback=mx.callback.Speedometer(batch_size, 1),
#initializer=mx.init.Xavier(factor_type="in", magnitude=2.34),
initializer=mx.init.Uniform(scale=0.1),
optimizer='sgd',
optimizer_params={'learning_rate': learning_rate, 'momentum': momentum, 'wd': 0.00001, 'clip_gradient': 5.0})
| {
"repo_name": "linmajia/dlbench",
"path": "synthetic/experiments/mxnet/rnn/train_rnn.py",
"copies": "2",
"size": "7465",
"license": "mit",
"hash": 1671669399580043000,
"line_mean": 44.7975460123,
"line_max": 135,
"alpha_frac": 0.5845947756,
"autogenerated": false,
"ratio": 3.7493721747865396,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.533396695038654,
"avg_score": null,
"num_lines": null
} |
"""A simple demo of new RNN cell with PTB language model."""
import os
import numpy as np
import mxnet as mx
from bucket_io import BucketSentenceIter, default_build_vocab
data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))
def Perplexity(label, pred):
# TODO(tofix): we make a transpose of label here, because when
# using the RNN cell, we called swap axis to the data.
label = label.T.reshape((-1,))
loss = 0.
for i in range(pred.shape[0]):
loss += -np.log(max(1e-10, pred[i][int(label[i])]))
return np.exp(loss / label.size)
if __name__ == '__main__':
batch_size = 128
buckets = [10, 20, 30, 40, 50, 60]
num_hidden = 200
num_embed = 200
num_lstm_layer = 2
num_epoch = 2
learning_rate = 0.01
momentum = 0.0
contexts = [mx.context.gpu(i) for i in range(4)]
vocab = default_build_vocab(os.path.join(data_dir, 'ptb.train.txt'))
init_h = [('LSTM_init_h', (batch_size, num_lstm_layer, num_hidden))]
init_c = [('LSTM_init_c', (batch_size, num_lstm_layer, num_hidden))]
init_states = init_c + init_h
data_train = BucketSentenceIter(os.path.join(data_dir, 'ptb.train.txt'),
vocab, buckets, batch_size, init_states)
data_val = BucketSentenceIter(os.path.join(data_dir, 'ptb.valid.txt'),
vocab, buckets, batch_size, init_states)
def sym_gen(seq_len):
data = mx.sym.Variable('data')
label = mx.sym.Variable('softmax_label')
embed = mx.sym.Embedding(data=data, input_dim=len(vocab),
output_dim=num_embed, name='embed')
# TODO(tofix)
# The inputs and labels from IO are all in batch-major.
# We need to transform them into time-major to use RNN cells.
embed_tm = mx.sym.SwapAxis(embed, dim1=0, dim2=1)
label_tm = mx.sym.SwapAxis(label, dim1=0, dim2=1)
# TODO(tofix)
# Create transformed RNN initial states. Normally we do
# no need to do this. But the RNN symbol expects the state
# to be time-major shape layout, while the current mxnet
# IO and high-level training logic assume everything from
# the data iter have batch_size as the first dimension.
# So until we have extended our IO and training logic to
# support this more general case, this dummy axis swap is
# needed.
rnn_h_init = mx.sym.SwapAxis(mx.sym.Variable('LSTM_init_h'),
dim1=0, dim2=1)
rnn_c_init = mx.sym.SwapAxis(mx.sym.Variable('LSTM_init_c'),
dim1=0, dim2=1)
# TODO(tofix)
# currently all the LSTM parameters are concatenated as
# a huge vector, and named '<name>_parameters'. By default
# mxnet initializer does not know how to initilize this
# guy because its name does not ends with _weight or _bias
# or anything familiar. Here we just use a temp workaround
# to create a variable and name it as LSTM_bias to get
# this demo running. Note by default bias is initialized
# as zeros, so this is not a good scheme. But calling it
# LSTM_weight is not good, as this is 1D vector, while
# the initialization scheme of a weight parameter needs
# at least two dimensions.
rnn_params = mx.sym.Variable('LSTM_bias')
# RNN cell takes input of shape (time, batch, feature)
rnn = mx.sym.RNN(data=embed_tm, state_size=num_hidden,
num_layers=num_lstm_layer, mode='lstm',
name='LSTM',
# The following params can be omitted
# provided we do not need to apply the
# workarounds mentioned above
state=rnn_h_init,
state_cell=rnn_c_init,
parameters=rnn_params)
# the RNN cell output is of shape (time, batch, dim)
# if we need the states and cell states in the last time
# step (e.g. when building encoder-decoder models), we
# can set state_outputs=True, and the RNN cell will have
# extra outputs: rnn['LSTM_output'], rnn['LSTM_state']
# and for LSTM, also rnn['LSTM_state_cell']
# now we collapse the time and batch dimension to do the
# final linear logistic regression prediction
hidden = mx.sym.Reshape(data=rnn, shape=(-1, num_hidden))
label_cl = mx.sym.Reshape(data=label_tm, shape=(-1,))
pred = mx.sym.FullyConnected(data=hidden, num_hidden=len(vocab),
name='pred')
sm = mx.sym.SoftmaxOutput(data=pred, label=label_cl, name='softmax')
data_names = ['data', 'LSTM_init_h', 'LSTM_init_c']
label_names = ['softmax_label']
return (sm, data_names, label_names)
if len(buckets) == 1:
mod = mx.mod.Module(*sym_gen(buckets[0]), context=contexts)
else:
mod = mx.mod.BucketingModule(sym_gen, default_bucket_key=data_train.default_bucket_key,
context=contexts)
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
mod.fit(data_train, eval_data=data_val, num_epoch=num_epoch,
eval_metric=mx.metric.np(Perplexity),
batch_end_callback=mx.callback.Speedometer(batch_size, 50),
initializer=mx.init.Xavier(factor_type="in", magnitude=2.34),
optimizer='sgd',
optimizer_params={'learning_rate': learning_rate,
'momentum': momentum, 'wd': 0.00001})
| {
"repo_name": "pluskid/mxnet",
"path": "example/rnn/old/rnn_cell_demo.py",
"copies": "15",
"size": "5755",
"license": "apache-2.0",
"hash": -7743223845540183000,
"line_mean": 41.6296296296,
"line_max": 95,
"alpha_frac": 0.5899218071,
"autogenerated": false,
"ratio": 3.737012987012987,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""A simple demo of new RNN cell with PTB language model."""
################################################################################
# Speed test (time major is 1.5~2 times faster than batch major).
#
# -- This script (time major) -----
# 2016-10-10 18:43:21,890 Epoch[0] Batch [50] Speed: 1717.76 samples/sec Train-Perplexity=4311.345018
# 2016-10-10 18:43:25,959 Epoch[0] Batch [100] Speed: 1573.17 samples/sec Train-Perplexity=844.092421
# 2016-10-10 18:43:29,807 Epoch[0] Batch [150] Speed: 1663.17 samples/sec Train-Perplexity=498.080716
# 2016-10-10 18:43:33,871 Epoch[0] Batch [200] Speed: 1574.84 samples/sec Train-Perplexity=455.051252
# 2016-10-10 18:43:37,720 Epoch[0] Batch [250] Speed: 1662.87 samples/sec Train-Perplexity=410.500066
# 2016-10-10 18:43:40,766 Epoch[0] Batch [300] Speed: 2100.81 samples/sec Train-Perplexity=274.317460
# 2016-10-10 18:43:44,571 Epoch[0] Batch [350] Speed: 1682.45 samples/sec Train-Perplexity=350.132577
# 2016-10-10 18:43:48,377 Epoch[0] Batch [400] Speed: 1681.41 samples/sec Train-Perplexity=320.674884
# 2016-10-10 18:43:51,253 Epoch[0] Train-Perplexity=336.210212
# 2016-10-10 18:43:51,253 Epoch[0] Time cost=33.529
# 2016-10-10 18:43:53,373 Epoch[0] Validation-Perplexity=282.453883
#
# -- ../rnn/rnn_cell_demo.py (batch major) -----
# 2016-10-10 18:44:34,133 Epoch[0] Batch [50] Speed: 1004.50 samples/sec Train-Perplexity=4398.428571
# 2016-10-10 18:44:39,874 Epoch[0] Batch [100] Speed: 1114.85 samples/sec Train-Perplexity=771.401960
# 2016-10-10 18:44:45,528 Epoch[0] Batch [150] Speed: 1132.03 samples/sec Train-Perplexity=525.207444
# 2016-10-10 18:44:51,564 Epoch[0] Batch [200] Speed: 1060.37 samples/sec Train-Perplexity=453.741140
# 2016-10-10 18:44:57,865 Epoch[0] Batch [250] Speed: 1015.78 samples/sec Train-Perplexity=411.914237
# 2016-10-10 18:45:04,032 Epoch[0] Batch [300] Speed: 1037.92 samples/sec Train-Perplexity=381.302188
# 2016-10-10 18:45:10,153 Epoch[0] Batch [350] Speed: 1045.49 samples/sec Train-Perplexity=363.326871
# 2016-10-10 18:45:16,062 Epoch[0] Batch [400] Speed: 1083.21 samples/sec Train-Perplexity=377.929014
# 2016-10-10 18:45:19,993 Epoch[0] Train-Perplexity=294.675899
# 2016-10-10 18:45:19,993 Epoch[0] Time cost=52.604
# 2016-10-10 18:45:21,401 Epoch[0] Validation-Perplexity=294.345659
################################################################################
import os
import numpy as np
import mxnet as mx
from bucket_io import BucketSentenceIter, default_build_vocab
data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))
def Perplexity(label, pred):
# collapse the time, batch dimension
label = label.reshape((-1,))
pred = pred.reshape((-1, pred.shape[-1]))
loss = 0.
for i in range(pred.shape[0]):
loss += -np.log(max(1e-10, pred[i][int(label[i])]))
return np.exp(loss / label.size)
if __name__ == '__main__':
batch_size = 128
buckets = [10, 20, 30, 40, 50, 60]
num_hidden = 200
num_embed = 200
num_lstm_layer = 2
num_epoch = 2
learning_rate = 0.01
momentum = 0.0
contexts = [mx.context.gpu(i) for i in range(1)]
vocab = default_build_vocab(os.path.join(data_dir, 'ptb.train.txt'))
init_h = [mx.io.DataDesc('LSTM_state', (num_lstm_layer, batch_size, num_hidden), layout='TNC')]
init_c = [mx.io.DataDesc('LSTM_state_cell', (num_lstm_layer, batch_size, num_hidden), layout='TNC')]
init_states = init_c + init_h
data_train = BucketSentenceIter(os.path.join(data_dir, 'ptb.train.txt'),
vocab, buckets, batch_size, init_states,
time_major=True)
data_val = BucketSentenceIter(os.path.join(data_dir, 'ptb.valid.txt'),
vocab, buckets, batch_size, init_states,
time_major=True)
def sym_gen(seq_len):
data = mx.sym.Variable('data')
label = mx.sym.Variable('softmax_label')
embed = mx.sym.Embedding(data=data, input_dim=len(vocab),
output_dim=num_embed, name='embed')
# TODO(tofix)
# currently all the LSTM parameters are concatenated as
# a huge vector, and named '<name>_parameters'. By default
# mxnet initializer does not know how to initilize this
# guy because its name does not ends with _weight or _bias
# or anything familiar. Here we just use a temp workaround
# to create a variable and name it as LSTM_bias to get
# this demo running. Note by default bias is initialized
# as zeros, so this is not a good scheme. But calling it
# LSTM_weight is not good, as this is 1D vector, while
# the initialization scheme of a weight parameter needs
# at least two dimensions.
rnn_params = mx.sym.Variable('LSTM_bias')
# RNN cell takes input of shape (time, batch, feature)
rnn = mx.sym.RNN(data=embed, state_size=num_hidden,
num_layers=num_lstm_layer, mode='lstm',
name='LSTM',
# The following params can be omitted
# provided we do not need to apply the
# workarounds mentioned above
parameters=rnn_params)
# the RNN cell output is of shape (time, batch, dim)
# if we need the states and cell states in the last time
# step (e.g. when building encoder-decoder models), we
# can set state_outputs=True, and the RNN cell will have
# extra outputs: rnn['LSTM_output'], rnn['LSTM_state']
# and for LSTM, also rnn['LSTM_state_cell']
# now we collapse the time and batch dimension to do the
# final linear logistic regression prediction
hidden = mx.sym.Reshape(data=rnn, shape=(-1, num_hidden))
pred = mx.sym.FullyConnected(data=hidden, num_hidden=len(vocab),
name='pred')
# reshape to be of compatible shape as labels
pred_tm = mx.sym.Reshape(data=pred, shape=(seq_len, -1, len(vocab)))
sm = mx.sym.SoftmaxOutput(data=pred_tm, label=label, preserve_shape=True,
name='softmax')
data_names = ['data', 'LSTM_state', 'LSTM_state_cell']
label_names = ['softmax_label']
return (sm, data_names, label_names)
if len(buckets) == 1:
mod = mx.mod.Module(*sym_gen(buckets[0]), context=contexts)
else:
mod = mx.mod.BucketingModule(sym_gen,
default_bucket_key=data_train.default_bucket_key,
context=contexts)
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
mod.fit(data_train, eval_data=data_val, num_epoch=num_epoch,
eval_metric=mx.metric.np(Perplexity),
batch_end_callback=mx.callback.Speedometer(batch_size, 50),
initializer=mx.init.Xavier(factor_type="in", magnitude=2.34),
optimizer='sgd',
optimizer_params={'learning_rate': learning_rate,
'momentum': momentum, 'wd': 0.00001})
| {
"repo_name": "hotpxl/mxnet",
"path": "example/rnn-time-major/rnn_cell_demo.py",
"copies": "15",
"size": "7381",
"license": "apache-2.0",
"hash": -6287642168328642000,
"line_mean": 47.880794702,
"line_max": 110,
"alpha_frac": 0.6024928871,
"autogenerated": false,
"ratio": 3.2688219663418954,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
# A simple demo of the mesh manager.
# Generates and renders a single tile with some ferns and trees
#
# INSTRUCTIONS:
#
# Launch from outside terrain, meaning launch with:
# python terrain/meshManager/main.py
import sys
sys.path.append(".")
from panda3d.core import *
from panda3d.core import Light,AmbientLight,DirectionalLight
from panda3d.core import NodePath
from panda3d.core import Vec3,Vec4,Mat4,VBase4,Point3
from direct.task.Task import Task
from direct.showbase.ShowBase import ShowBase
from terrain.meshManager import meshManager
from terrain.meshManager import treeFactory
from terrain.meshManager import fernFactory
base = ShowBase()
base.disableMouse()
class Flat():
def height(self,x,y): return 0
factories=[treeFactory.TreeFactory(),fernFactory.FernFactory()]
t=meshManager.MeshManager(factories)
tf=treeFactory.TreeFactory()
ff=fernFactory.FernFactory()
factories=[tf,ff]
meshManager=meshManager.MeshManager(factories)
size=600.0
tileFactory=meshManager.tileFactory(size)
x=0.0
y=0.0
tile=Flat()
tileNode=tileFactory(x,y,tile)
tileNode.reparentTo(base.render)
dlight = DirectionalLight('dlight')
dlnp = render.attachNewNode(dlight)
dlnp.setHpr(0, 0, 0)
render.setLight(dlnp)
alight = AmbientLight('alight')
alnp = render.attachNewNode(alight)
render.setLight(alnp)
#rotating light to show that normals are calculated correctly
def updateLight(task):
base.camera.setHpr(task.time/50.0*360,0,0)
#base.camera.setP(0)
base.camera.setPos(size/2,size/2,5)
#base.camera.setPos(tileNode,2,task.time*4,5)
base.camera.setP(8)
#t.update(base.camera)
h=task.time/20.0*360+180
dlnp.setHpr(0,h,0)
h=h+90
h=h%360
h=min(h,360-h)
#h is now angle from straight up
hv=h/180.0
hv=1-hv
sunset=max(0,1.0-abs(hv-.5)*8)
sunset=min(1,sunset)
if hv>.5: sunset=1
#sunset=sunset**.2
sunset=VBase4(0.8, 0.5, 0.0, 1)*sunset
sun=max(0,hv-.5)*2*4
sun=min(sun,1)
dColor=(VBase4(0.8, 0.7, 0.7, 1)*sun*2+sunset)
dlight.setColor(dColor)
aColor=VBase4(0.1, 0.3, 0.8, 1)*sun*2.6+VBase4(0.2, 0.2, 0.3, 1)*2.0
alight.setColor(aColor*(5-dColor.length())*(1.0/5))
return Task.cont
taskMgr.add(updateLight, "rotating Light")
base.run() | {
"repo_name": "Craig-Macomber/Panda3D-Terrain-System",
"path": "meshManager/main.py",
"copies": "1",
"size": "2269",
"license": "bsd-2-clause",
"hash": -7914525908556483000,
"line_mean": 21.7,
"line_max": 72,
"alpha_frac": 0.7130894667,
"autogenerated": false,
"ratio": 2.6170703575547867,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.38301598242547863,
"avg_score": null,
"num_lines": null
} |
"""A simple demo that allows the user to drive the 'Robot Arm H25' located
here: http://robotsquare.com/2013/10/01/education-ev3-45544-instruction/
The program waits for key presses and responds to the following keys:
'w' - Raises the claw
's' - Lowers the claw
'a' - Swivels the claw left
'd' - Swivels the claw right
'c' - Opens the claw
'v' - Closes the claw
'q' - Exits the program
Before running the program ensure that you have binded the brick to rfcomm0
(i.e. 'sudo rfcomm bind /dev/rfcomm0 XX:XX:XX:XX:XX:XX').
"""
import sys
import tty
import termios
from ev3 import *
def getch():
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
return sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
# Ensures that the claw is firmly closed.
close_claw_cmd = direct_command.DirectCommand()
close_claw_cmd.add_output_speed(direct_command.OutputPort.PORT_D, 10)
close_claw_cmd.add_output_start(direct_command.OutputPort.PORT_D)
close_claw_cmd.add_timer_wait(1000)
close_claw_cmd.add_output_stop(direct_command.OutputPort.PORT_D,
direct_command.StopType.BRAKE)
# Opens the claw about half way.
open_claw_cmd = direct_command.DirectCommand()
open_claw_cmd.add_output_speed(direct_command.OutputPort.PORT_D, -10)
open_claw_cmd.add_output_start(direct_command.OutputPort.PORT_D)
open_claw_cmd.add_timer_wait(600)
open_claw_cmd.add_output_stop(direct_command.OutputPort.PORT_D,
direct_command.StopType.BRAKE)
raise_claw_cmd = direct_command.DirectCommand()
raise_claw_cmd.add_output_step_speed(direct_command.OutputPort.PORT_B,
-15,
0,
20,
10,
direct_command.StopType.BRAKE)
raise_claw_cmd.add_output_ready(direct_command.OutputPort.PORT_B)
raise_claw_cmd.add_keep_alive()
lower_claw_cmd = direct_command.DirectCommand()
lower_claw_cmd.add_output_step_speed(direct_command.OutputPort.PORT_B,
15,
0,
20,
10,
direct_command.StopType.BRAKE)
lower_claw_cmd.add_output_ready(direct_command.OutputPort.PORT_B)
lower_claw_cmd.add_keep_alive()
swivel_left_cmd = direct_command.DirectCommand()
swivel_left_cmd.add_output_step_speed(direct_command.OutputPort.PORT_C,
-15,
0,
20,
10,
direct_command.StopType.BRAKE)
swivel_left_cmd.add_output_ready(direct_command.OutputPort.PORT_C)
swivel_left_cmd.add_keep_alive()
swivel_right_cmd = direct_command.DirectCommand()
swivel_right_cmd.add_output_step_speed(direct_command.OutputPort.PORT_C,
15,
0,
20,
10,
direct_command.StopType.BRAKE)
swivel_right_cmd.add_output_ready(direct_command.OutputPort.PORT_C)
swivel_right_cmd.add_keep_alive()
if ("__main__" == __name__):
with ev3.EV3() as brick:
print "Connection opened (press 'q' to quit)."
while (True):
c = getch()
if ('c' == c):
print 'Opening claw.'
open_claw_cmd.send(brick)
elif ('v' == c):
print 'Closing claw.'
close_claw_cmd.send(brick)
elif ('w' == c):
print 'Raising claw.'
raise_claw_cmd.send(brick)
elif ('s' == c):
print 'Lowering claw.'
lower_claw_cmd.send(brick)
elif ('a' == c):
print 'Swivel left.'
swivel_left_cmd.send(brick)
elif ('d' == c):
print 'Swivel right.'
swivel_right_cmd.send(brick)
elif ('q' == c):
break
| {
"repo_name": "inductivekickback/ev3",
"path": "Robot_Arm_H25_demo.py",
"copies": "1",
"size": "4442",
"license": "mit",
"hash": 6446883914242306000,
"line_mean": 34.8225806452,
"line_max": 75,
"alpha_frac": 0.5159837911,
"autogenerated": false,
"ratio": 3.7047539616346956,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9704033880039427,
"avg_score": 0.003340774539053782,
"num_lines": 124
} |
"""A simple densely connected baseline model."""
import keras.layers
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine import hyper_spaces
class DenseBaseline(BaseModel):
"""
A simple densely connected baseline model.
Examples:
>>> model = DenseBaseline()
>>> model.params['mlp_num_layers'] = 2
>>> model.params['mlp_num_units'] = 300
>>> model.params['mlp_num_fan_out'] = 128
>>> model.params['mlp_activation_func'] = 'relu'
>>> model.guess_and_fill_missing_params(verbose=0)
>>> model.build()
>>> model.compile()
"""
@classmethod
def get_default_params(cls) -> ParamTable:
""":return: model default parameters."""
params = super().get_default_params(with_multi_layer_perceptron=True)
params['mlp_num_units'] = 256
params.get('mlp_num_units').hyper_space = \
hyper_spaces.quniform(16, 512)
params.get('mlp_num_layers').hyper_space = \
hyper_spaces.quniform(1, 5)
return params
def build(self):
"""Model structure."""
x_in = self._make_inputs()
x = keras.layers.concatenate(x_in)
x = self._make_multi_layer_perceptron_layer()(x)
x_out = self._make_output_layer()(x)
self._backend = keras.models.Model(inputs=x_in, outputs=x_out)
| {
"repo_name": "faneshion/MatchZoo",
"path": "matchzoo/models/dense_baseline.py",
"copies": "1",
"size": "1420",
"license": "apache-2.0",
"hash": 2840813650883551700,
"line_mean": 32.023255814,
"line_max": 77,
"alpha_frac": 0.611971831,
"autogenerated": false,
"ratio": 3.5588972431077694,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4670869074107769,
"avg_score": null,
"num_lines": null
} |
"""A simple dense neural network search space.
Copyright 2018 The AdaNet Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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.
"""
import functools
import adanet
import tensorflow.compat.v2 as tf
_NUM_LAYERS_KEY = "num_layers"
class _SimpleDNNBuilder(adanet.subnetwork.Builder):
"""Builds a DNN subnetwork for AdaNet."""
def __init__(self, feature_columns, optimizer, layer_size, num_layers,
learn_mixture_weights, dropout, seed):
"""Initializes a `_DNNBuilder`.
Args:
feature_columns: An iterable containing all the feature columns used by
the model. All items in the set should be instances of classes derived
from `FeatureColumn`.
optimizer: An `Optimizer` instance for training both the subnetwork and
the mixture weights.
layer_size: The number of nodes to output at each hidden layer.
num_layers: The number of hidden layers.
learn_mixture_weights: Whether to solve a learning problem to find the
best mixture weights, or use their default value according to the
mixture weight type. When `False`, the subnetworks will return a no_op
for the mixture weight train op.
dropout: The dropout rate, between 0 and 1. E.g. "rate=0.1" would drop out
10% of input units.
seed: A random seed.
Returns:
An instance of `_DNNBuilder`.
"""
self._feature_columns = feature_columns
self._optimizer = optimizer
self._layer_size = layer_size
self._num_layers = num_layers
self._learn_mixture_weights = learn_mixture_weights
self._dropout = dropout
self._seed = seed
def build_subnetwork(self,
features,
logits_dimension,
training,
iteration_step,
summary,
previous_ensemble=None):
"""See `adanet.subnetwork.Builder`."""
input_layer = tf.compat.v1.feature_column.input_layer(
features=features, feature_columns=self._feature_columns)
last_layer = input_layer
for _ in range(self._num_layers):
last_layer = tf.compat.v1.layers.dense(
last_layer,
units=self._layer_size,
activation=tf.nn.relu,
kernel_initializer=tf.compat.v1.glorot_uniform_initializer(
seed=self._seed))
last_layer = tf.compat.v1.layers.dropout(
last_layer, rate=self._dropout, seed=self._seed, training=training)
logits = tf.compat.v1.layers.dense(
last_layer,
units=logits_dimension,
kernel_initializer=tf.compat.v1.glorot_uniform_initializer(
seed=self._seed))
# Approximate the Rademacher complexity of this subnetwork as the square-
# root of its depth.
complexity = tf.sqrt(tf.cast(self._num_layers, dtype=tf.float32))
with tf.name_scope(""):
summary.scalar("complexity", complexity)
summary.scalar("num_layers", self._num_layers)
shared = {_NUM_LAYERS_KEY: self._num_layers}
return adanet.Subnetwork(
last_layer=last_layer,
logits=logits,
complexity=complexity,
shared=shared)
def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels,
iteration_step, summary, previous_ensemble):
"""See `adanet.subnetwork.Builder`."""
# NOTE: The `adanet.Estimator` increments the global step.
update_ops = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
return self._optimizer.minimize(loss=loss, var_list=var_list)
# TODO: Delete deprecated build_mixture_weights_train_op method.
# Use adanet.ensemble.Ensembler instead.
def build_mixture_weights_train_op(self, loss, var_list, logits, labels,
iteration_step, summary):
"""See `adanet.subnetwork.Builder`."""
if not self._learn_mixture_weights:
return tf.no_op("mixture_weights_train_op")
# NOTE: The `adanet.Estimator` increments the global step.
return self._optimizer.minimize(loss=loss, var_list=var_list)
@property
def name(self):
"""See `adanet.subnetwork.Builder`."""
if self._num_layers == 0:
# A DNN with no hidden layers is a linear model.
return "linear"
return "{}_layer_dnn".format(self._num_layers)
class Generator(adanet.subnetwork.Generator):
"""Generates a two DNN subnetworks at each iteration.
The first DNN has an identical shape to the most recently added subnetwork
in `previous_ensemble`. The second has the same shape plus one more dense
layer on top. This is similar to the adaptive network presented in Figure 2 of
[Cortes et al. ICML 2017](https://arxiv.org/abs/1607.01097), without the
connections to hidden layers of networks from previous iterations.
"""
def __init__(self,
feature_columns,
optimizer,
layer_size=32,
initial_num_layers=0,
learn_mixture_weights=False,
dropout=0.,
seed=None):
"""Initializes a DNN `Generator`.
Args:
feature_columns: An iterable containing all the feature columns used by
DNN models. All items in the set should be instances of classes derived
from `FeatureColumn`.
optimizer: An `Optimizer` instance for training both the subnetwork and
the mixture weights.
layer_size: Number of nodes in each hidden layer of the subnetwork
candidates. Note that this parameter is ignored in a DNN with no hidden
layers.
initial_num_layers: Minimum number of layers for each DNN subnetwork. At
iteration 0, the subnetworks will be `initial_num_layers` deep.
Subnetworks at subsequent iterations will be at least as deep.
learn_mixture_weights: Whether to solve a learning problem to find the
best mixture weights, or use their default value according to the
mixture weight type. When `False`, the subnetworks will return a no_op
for the mixture weight train op.
dropout: The dropout rate, between 0 and 1. E.g. "rate=0.1" would drop out
10% of input units.
seed: A random seed.
Returns:
An instance of `Generator`.
Raises:
ValueError: If feature_columns is empty.
ValueError: If layer_size < 1.
ValueError: If initial_num_layers < 0.
"""
if not feature_columns:
raise ValueError("feature_columns must not be empty")
if layer_size < 1:
raise ValueError("layer_size must be >= 1")
if initial_num_layers < 0:
raise ValueError("initial_num_layers must be >= 0")
self._initial_num_layers = initial_num_layers
self._dnn_builder_fn = functools.partial(
_SimpleDNNBuilder,
feature_columns=feature_columns,
optimizer=optimizer,
layer_size=layer_size,
learn_mixture_weights=learn_mixture_weights,
dropout=dropout,
seed=seed)
def generate_candidates(self, previous_ensemble, iteration_number,
previous_ensemble_reports, all_reports):
"""See `adanet.subnetwork.Generator`."""
num_layers = self._initial_num_layers
if previous_ensemble:
num_layers = previous_ensemble.weighted_subnetworks[-1].subnetwork.shared[
_NUM_LAYERS_KEY]
return [
self._dnn_builder_fn(num_layers=num_layers),
self._dnn_builder_fn(num_layers=num_layers + 1),
]
| {
"repo_name": "tensorflow/adanet",
"path": "adanet/examples/simple_dnn.py",
"copies": "1",
"size": "8005",
"license": "apache-2.0",
"hash": -4427142556880277000,
"line_mean": 36.5821596244,
"line_max": 80,
"alpha_frac": 0.6615865084,
"autogenerated": false,
"ratio": 4.02463549522373,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.003058639434164429,
"num_lines": 213
} |
""" A simple directory watcher
Credit: ronedg @ http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python
"""
import os, time
import gevent
class DirWatcher(object):
""" A simple directory watcher """
def __init__(self, path):
""" Initialize the Directory Watcher
Args:
path: path of the directory to watch
"""
self.path = path
self.on_create = None
self.on_modify = None
self.on_delete = None
self.jobs = None
def register_callbacks(self, on_create, on_modify, on_delete):
""" Register callbacks for file creation, modification, and deletion """
self.on_create = on_create
self.on_modify = on_modify
self.on_delete = on_delete
def start_monitoring(self):
""" Monitor the path given """
self.jobs = [gevent.spawn(self._start_monitoring)]
def _start_monitoring(self):
""" Internal method that monitors the directory for changes """
# Grab all the timestamp info
before = self._file_timestamp_info(self.path)
while True:
gevent.sleep(1)
after = self._file_timestamp_info(self.path)
added = [fname for fname in after.keys() if fname not in before.keys()]
removed = [fname for fname in before.keys() if fname not in after.keys()]
modified = []
for fname in before.keys():
if fname not in removed:
if os.path.getmtime(fname) != before.get(fname):
modified.append(fname)
if added:
self.on_create(added)
if removed:
self.on_delete(removed)
if modified:
self.on_modify(modified)
before = after
def _file_timestamp_info(self, path):
""" Grab all the timestamps for the files in the directory """
files = [os.path.join(path, fname) for fname in os.listdir(path) if '.py' in fname]
return dict ([(fname, os.path.getmtime(fname)) for fname in files])
def __del__(self):
""" Cleanup the DirWatcher instance """
gevent.joinall(self.jobs)
| {
"repo_name": "SuperCowPowers/workbench",
"path": "workbench/server/dir_watcher.py",
"copies": "2",
"size": "2244",
"license": "mit",
"hash": 4096915579050780000,
"line_mean": 33,
"line_max": 109,
"alpha_frac": 0.573083779,
"autogenerated": false,
"ratio": 4.233962264150944,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.012640290391556782,
"num_lines": 66
} |
"""A simple distributed shuffle implementation in Ray.
This utility provides a `simple_shuffle` function that can be used to
redistribute M input partitions into N output partitions. It does this with
a single wave of shuffle map tasks followed by a single wave of shuffle reduce
tasks. Each shuffle map task generates O(N) output objects, and each shuffle
reduce task consumes O(M) input objects, for a total of O(N*M) objects.
To try an example 10GB shuffle, run:
$ python -m ray.experimental.shuffle \
--num-partitions=50 --partition-size=200e6 \
--object-store-memory=1e9
This will print out some statistics on the shuffle execution such as:
--- Aggregate object store stats across all nodes ---
Plasma memory usage 0 MiB, 0 objects, 0.0% full
Spilled 9487 MiB, 2487 objects, avg write throughput 1023 MiB/s
Restored 9487 MiB, 2487 objects, avg read throughput 1358 MiB/s
Objects consumed by Ray tasks: 9537 MiB.
Shuffled 9536 MiB in 16.579771757125854 seconds
"""
import time
from typing import List, Iterable, Tuple, Callable, Any, Union
import ray
from ray.cluster_utils import Cluster
from ray import ObjectRef
# TODO(ekl) why doesn't TypeVar() deserialize properly in Ray?
# The type produced by the input reader function.
InType = Any
# The type produced by the output writer function.
OutType = Any
# Integer identifying the partition number.
PartitionID = int
class ObjectStoreWriter:
"""This class is used to stream shuffle map outputs to the object store.
It can be subclassed to optimize writing (e.g., batching together small
records into larger objects). This will be performance critical if your
input records are small (the example shuffle uses very large records, so
the naive strategy works well).
"""
def __init__(self):
self.results = []
def add(self, item: InType) -> None:
"""Queue a single item to be written to the object store.
This base implementation immediately writes each given item to the
object store as a standalone object.
"""
self.results.append(ray.put(item))
def finish(self) -> List[ObjectRef]:
"""Return list of object refs representing written items."""
return self.results
class ObjectStoreWriterNonStreaming(ObjectStoreWriter):
def __init__(self):
self.results = []
def add(self, item: InType) -> None:
self.results.append(item)
def finish(self) -> List[Any]:
return self.results
def round_robin_partitioner(input_stream: Iterable[InType], num_partitions: int
) -> Iterable[Tuple[PartitionID, InType]]:
"""Round robin partitions items from the input reader.
You can write custom partitioning functions for your use case.
Args:
input_stream: Iterator over items from the input reader.
num_partitions: Number of output partitions.
Yields:
Tuples of (partition id, input item).
"""
i = 0
for item in input_stream:
yield (i, item)
i += 1
i %= num_partitions
@ray.remote
class _StatusTracker:
def __init__(self):
self.num_map = 0
self.num_reduce = 0
def inc(self):
self.num_map += 1
def inc2(self):
self.num_reduce += 1
def get_progress(self):
return self.num_map, self.num_reduce
def render_progress_bar(tracker, input_num_partitions, output_num_partitions):
from tqdm import tqdm
num_map = 0
num_reduce = 0
map_bar = tqdm(total=input_num_partitions, position=0)
map_bar.set_description("Map Progress.")
reduce_bar = tqdm(total=output_num_partitions, position=1)
reduce_bar.set_description("Reduce Progress.")
while (num_map < input_num_partitions
or num_reduce < output_num_partitions):
new_num_map, new_num_reduce = ray.get(tracker.get_progress.remote())
map_bar.update(new_num_map - num_map)
reduce_bar.update(new_num_reduce - num_reduce)
num_map = new_num_map
num_reduce = new_num_reduce
time.sleep(0.1)
map_bar.close()
reduce_bar.close()
def simple_shuffle(*,
input_reader: Callable[[PartitionID], Iterable[InType]],
input_num_partitions: int,
output_num_partitions: int,
output_writer: Callable[
[PartitionID, List[Union[ObjectRef, Any]]], OutType],
partitioner: Callable[[Iterable[InType], int], Iterable[
PartitionID]] = round_robin_partitioner,
object_store_writer: ObjectStoreWriter = ObjectStoreWriter,
tracker: _StatusTracker = None,
streaming: bool = True) -> List[OutType]:
"""Simple distributed shuffle in Ray.
Args:
input_reader: Function that generates the input items for a
partition (e.g., data records).
input_num_partitions: The number of input partitions.
output_num_partitions: The desired number of output partitions.
output_writer: Function that consumes a iterator of items for a
given output partition. It returns a single value that will be
collected across all output partitions.
partitioner: Partitioning function to use. Defaults to round-robin
partitioning of input items.
object_store_writer: Class used to write input items to the
object store in an efficient way. Defaults to a naive
implementation that writes each input record as one object.
tracker: Tracker actor that is used to display the progress bar.
streaming: Whether or not if the shuffle will be streaming.
Returns:
List of outputs from the output writers.
"""
@ray.remote(num_returns=output_num_partitions)
def shuffle_map(i: PartitionID) -> List[List[Union[Any, ObjectRef]]]:
writers = [object_store_writer() for _ in range(output_num_partitions)]
for out_i, item in partitioner(input_reader(i), output_num_partitions):
writers[out_i].add(item)
return [c.finish() for c in writers]
@ray.remote
def shuffle_reduce(
i: PartitionID,
*mapper_outputs: List[List[Union[Any, ObjectRef]]]) -> OutType:
input_objects = []
assert len(mapper_outputs) == input_num_partitions
for obj_refs in mapper_outputs:
for obj_ref in obj_refs:
input_objects.append(obj_ref)
return output_writer(i, input_objects)
shuffle_map_out = [
shuffle_map.remote(i) for i in range(input_num_partitions)
]
shuffle_reduce_out = [
shuffle_reduce.remote(
j, *[shuffle_map_out[i][j] for i in range(input_num_partitions)])
for j in range(output_num_partitions)
]
if tracker:
render_progress_bar(tracker, input_num_partitions,
output_num_partitions)
return ray.get(shuffle_reduce_out)
def build_cluster(num_nodes, num_cpus, object_store_memory):
cluster = Cluster()
for _ in range(num_nodes):
cluster.add_node(
num_cpus=num_cpus, object_store_memory=object_store_memory)
cluster.wait_for_nodes()
return cluster
def main(ray_address=None,
object_store_memory=1e9,
num_partitions=5,
partition_size=200e6,
num_nodes=None,
num_cpus=8,
no_streaming=False,
use_wait=False):
import argparse
import numpy as np
import time
parser = argparse.ArgumentParser()
parser.add_argument("--ray-address", type=str, default=ray_address)
parser.add_argument(
"--object-store-memory", type=float, default=object_store_memory)
parser.add_argument("--num-partitions", type=int, default=num_partitions)
parser.add_argument("--partition-size", type=float, default=partition_size)
parser.add_argument("--num-nodes", type=int, default=num_nodes)
parser.add_argument("--num-cpus", type=int, default=num_cpus)
parser.add_argument(
"--no-streaming", action="store_true", default=no_streaming)
parser.add_argument("--use-wait", action="store_true", default=use_wait)
args = parser.parse_args()
is_multi_node = args.num_nodes
if args.ray_address:
print("Connecting to a existing cluster...")
ray.init(address=args.ray_address)
elif is_multi_node:
print("Emulating a cluster...")
print(f"Num nodes: {args.num_nodes}")
print(f"Num CPU per node: {args.num_cpus}")
print(f"Object store memory per node: {args.object_store_memory}")
cluster = build_cluster(args.num_nodes, args.num_cpus,
args.object_store_memory)
ray.init(address=cluster.address)
else:
print("Start a new cluster...")
ray.init(
num_cpus=args.num_cpus,
object_store_memory=args.object_store_memory)
partition_size = int(args.partition_size)
num_partitions = args.num_partitions
rows_per_partition = partition_size // (8 * 2)
tracker = _StatusTracker.remote()
use_wait = args.use_wait
def input_reader(i: PartitionID) -> Iterable[InType]:
for _ in range(num_partitions):
yield np.ones(
(rows_per_partition // num_partitions, 2), dtype=np.int64)
tracker.inc.remote()
def output_writer(i: PartitionID,
shuffle_inputs: List[ObjectRef]) -> OutType:
total = 0
if not use_wait:
for obj_ref in shuffle_inputs:
arr = ray.get(obj_ref)
total += arr.size * arr.itemsize
else:
while shuffle_inputs:
[ready], shuffle_inputs = ray.wait(
shuffle_inputs, num_returns=1)
arr = ray.get(ready)
total += arr.size * arr.itemsize
tracker.inc2.remote()
return total
def output_writer_non_streaming(i: PartitionID,
shuffle_inputs: List[Any]) -> OutType:
total = 0
for arr in shuffle_inputs:
total += arr.size * arr.itemsize
tracker.inc2.remote()
return total
if args.no_streaming:
output_writer_callable = output_writer_non_streaming
object_store_writer = ObjectStoreWriterNonStreaming
else:
object_store_writer = ObjectStoreWriter
output_writer_callable = output_writer
start = time.time()
output_sizes = simple_shuffle(
input_reader=input_reader,
input_num_partitions=num_partitions,
output_num_partitions=num_partitions,
output_writer=output_writer_callable,
object_store_writer=object_store_writer,
tracker=tracker)
delta = time.time() - start
time.sleep(.5)
print()
print(ray.internal.internal_api.memory_summary(stats_only=True))
print()
print("Shuffled", int(sum(output_sizes) / (1024 * 1024)), "MiB in", delta,
"seconds")
if __name__ == "__main__":
main()
| {
"repo_name": "ray-project/ray",
"path": "python/ray/experimental/shuffle.py",
"copies": "1",
"size": "11151",
"license": "apache-2.0",
"hash": 6537105435780935000,
"line_mean": 34.0660377358,
"line_max": 79,
"alpha_frac": 0.6335754641,
"autogenerated": false,
"ratio": 3.973984319315752,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5107559783415752,
"avg_score": null,
"num_lines": null
} |
# A simple DOC file parser based on pyole
import os
import struct
import logging
import datetime
from pyole import *
class FIBBase(OLEBase):
wIdent = 0
nFib = 0
unused = 0
lid = 0
pnNext = 0
Flags1 = 0
fDot = 0
fGlsy = 0
fComplex = 0
fHasPic = 0
cQuickSaves = 0
fEncrypted = 0
fWhichTblStm = 0
fReadOnlyRecommended = 0
fWriteReservation = 0
fExtChar = 0
fLoadOverride = 0
fFarEast = 0
fObfuscated = 0
nFibBack = 0
lKey = 0
envr = 0
Flag2 = 0
fMac = 0
fEmptySpecial = 0
fLoadOverridePage = 0
reserved1 = 0
reserved2 = 0
fSpare0 = 0
reserved3 = 0
reserved4 = 0
reserved5 = 0
reserved6 = 0
def __init__(self, data):
self.wIdent = 0
self.nFib = 0
self.unused = 0
self.pnNext = 0
self.Flags1 = 0
self.fDot = 0
self.fGlsy = 0
self.fComplex = 0
self.fHasPic = 0
self.cQuickSaves = 0
self.fEncrypted = 0
self.fWhichTblStm = 0
self.fReadOnlyRecommended = 0
self.fWriteReservation = 0
self.fExtChar = 0
self.fLoadOverride = 0
self.fFarEast = 0
self.fObfuscated = 0
self.nFibBack = 0
self.lKey = 0
self.envr = 0
self.Flag2 = 0
self.fMac = 0
self.fEmptySpecial = 0
self.fLoadOverridePage = 0
self.reserved1 = 0
self.reserved2 = 0
self.fSpare0 = 0
self.reserved3 = 0
self.reserved4 = 0
self.reserved5 = 0
self.reserved6 = 0
self.wIdent = struct.unpack('<H', data[0x00:0x02])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.wIdent: ' + str(hex(self.wIdent)))
if self.wIdent != 0xA5EC:
self._raise_exception('DOC.FIB.FIBBase.wIdent has an abnormal value.')
self.nFib = struct.unpack('<H', data[0x02:0x04])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.nFib: ' + str(hex(self.nFib)))
if self.nFib != 0x00C1:
self._raise_exception('DOC.FIB.FIBBase.nFib has an abnormal value.')
self.unused = struct.unpack('<H', data[0x04:0x06])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.unused: ' + str(hex(self.unused)))
#if self.unused != 0:
# self.ole_logger.warning('DOC.FIB.FIBBase.unused is not zero.')
self.lid = struct.unpack('<H', data[0x06:0x08])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.lid: ' + str(hex(self.lid)))
self.pnNext = struct.unpack('<H', data[0x08:0x0A])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.pnNext: ' + str(hex(self.pnNext)))
if self.pnNext != 0:
self.ole_logger.warning('DOC.FIB.FIBBase.pnNext is not zero.')
self.Flags1 = struct.unpack('<H', data[0x0A:0x0C])[0]
self.fDot = self.Flags1 & 0x0001
self.ole_logger.debug('DOC.FIB.FIBBase.fDot: ' + str(self.fDot))
self.fGlsy = (self.Flags1 & 0x0002) >> 1
self.ole_logger.debug('DOC.FIB.FIBBase.fGlsy: ' + str(self.fGlsy))
self.fComplex = (self.Flags1 & 0x0004) >> 2
self.ole_logger.debug('DOC.FIB.FIBBase.fComplex: ' + str(self.fComplex))
self.fHasPic = (self.Flags1 & 0x0008) >> 3
self.ole_logger.debug('DOC.FIB.FIBBase.fHasPic: ' + str(self.fHasPic))
self.cQuickSaves = (self.Flags1 & 0x00F0) >> 4
self.ole_logger.debug('DOC.FIB.FIBBase.cQuickSaves: ' + str(self.cQuickSaves))
self.fEncrypted = (self.Flags1 & 0x0100) >> 8
self.ole_logger.debug('DOC.FIB.FIBBase.fEncrypted: ' + str(self.fEncrypted))
if self.fEncrypted == 1:
self.ole_logger.warning('File is encrypted.')
self.fWhichTblStm = (self.Flags1 & 0x0200) >> 9
self.ole_logger.debug('DOC.FIB.FIBBase.fWhichTblStm: ' + str(self.fWhichTblStm))
self.fReadOnlyRecommended = (self.Flags1 & 0x0400) >> 10
self.ole_logger.debug('DOC.FIB.FIBBase.fReadOnlyRecommended: ' + str(self.fReadOnlyRecommended))
self.fWriteReservation = (self.Flags1 & 0x0800) >> 11
self.ole_logger.debug('DOC.FIB.FIBBase.fWriteReservation: ' + str(self.fWriteReservation))
self.fExtChar = (self.Flags1 & 0x1000) >> 12
self.ole_logger.debug('DOC.FIB.FIBBase.fExtChar: ' + str(self.fExtChar))
if (self.Flags1 & 0x1000) >> 12 != 1:
self._raise_exception('DOC.FIB.FIBBase.fExtChar has an abnormal value.')
self.fLoadOverride = (self.Flags1 & 0x2000) >> 13
self.ole_logger.debug('DOC.FIB.FIBBase.fLoadOverride: ' + str(self.fLoadOverride))
self.fFarEast = (self.Flags1 & 0x4000) >> 14
self.ole_logger.debug('DOC.FIB.FIBBase.fFarEast: ' + str(self.fFarEast))
if self.fFarEast == 1:
self.ole_logger.warning('The installation language of the application that created the document was an East Asian language.')
self.fObfuscated = (self.Flags1 & 0x8000) >> 15
self.ole_logger.debug('DOC.FIB.FIBBase.fObfuscated: ' + str(self.fObfuscated))
if self.fObfuscated == 1:
if self.fEncrypted == 1:
self.ole_logger.warning('File is obfuscated by using XOR obfuscation.')
self.nFibBack = struct.unpack('<H', data[0x0C:0x0E])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.nFibBack: ' + str(hex(self.nFibBack)))
if self.nFibBack != 0x00BF and self.nFibBack != 0x00C1:
self._raise_exception('DOC.FIB.FIBBase.nFibBack has an abnormal value.')
self.lKey = struct.unpack('<I', data[0x0E:0x12])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.lKey: ' + str(hex(self.lKey)))
if self.fEncrypted == 1:
if self.fObfuscated == 1:
self.ole_logger.info('The XOR obfuscation key is: ' + str(hex(self.lKey)))
else:
if self.lKey != 0:
self._raise_exception('DOC.FIB.FIBBase.lKey has an abnormal value.')
self.envr = ord(data[0x12])
self.ole_logger.debug('DOC.FIB.FIBBase.envr: ' + str(hex(self.envr)))
if self.envr != 0:
self._raise_exception('DOC.FIB.FIBBase.envr has an abnormal value.')
self.Flag2 = ord(data[0x13])
self.fMac = self.Flag2 & 0x01
self.ole_logger.debug('DOC.FIB.FIBBase.fMac: ' + str(hex(self.fMac)))
if self.fMac != 0:
self._raise_exception('DOC.FIB.FIBBase.fMac has an abnormal value.')
self.fEmptySpecial = (self.Flag2 & 0x02) >> 1
self.ole_logger.debug('DOC.FIB.FIBBase.fEmptySpecial: ' + str(hex(self.fEmptySpecial)))
if self.fEmptySpecial != 0:
self.ole_logger.warning('DOC.FIB.FIBBase.fEmptySpecial is not zero.')
self.fLoadOverridePage = (self.Flag2 & 0x04) >> 2
self.ole_logger.debug('DOC.FIB.FIBBase.fLoadOverridePage: ' + str(hex(self.fLoadOverridePage)))
self.reserved1 = (self.Flag2 & 0x08) >> 3
self.ole_logger.debug('DOC.FIB.FIBBase.reserved1: ' + str(hex(self.reserved1)))
self.reserved2 = (self.Flag2 & 0x10) >> 4
self.ole_logger.debug('DOC.FIB.FIBBase.reserved2: ' + str(hex(self.reserved2)))
self.fSpare0 = (self.Flag2 & 0xE0) >> 5
self.ole_logger.debug('DOC.FIB.FIBBase.fSpare0: ' + str(hex(self.fSpare0)))
self.reserved3 = struct.unpack('<H', data[0x14:0x16])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.reserved3: ' + str(hex(self.reserved3)))
self.reserved4 = struct.unpack('<H', data[0x16:0x18])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.reserved4: ' + str(hex(self.reserved4)))
self.reserved5 = struct.unpack('<I', data[0x18:0x1C])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.reserved5: ' + str(hex(self.reserved5)))
self.reserved6 = struct.unpack('<I', data[0x1C:0x20])[0]
self.ole_logger.debug('DOC.FIB.FIBBase.reserved6: ' + str(hex(self.reserved6)))
class FibRgFcLcb(OLEBase):
fcSttbfAssoc = 0
lcbSttbfAssoc = 0
fcSttbfRMark = 0
lcbSttbfRMark = 0
fcSttbSavedBy = 0
lcbSttbSavedBy = 0
dwLowDateTime = 0
dwHighDateTime = 0
def __init__(self, data):
self.fcSttbfAssoc = 0
self.lcbSttbfAssoc = 0
self.fcSttbfRMark = 0
self.lcbSttbfRMark = 0
self.fcSttbSavedBy = 0
self.lcbSttbSavedBy = 0
self.dwLowDateTime = 0
self.dwHighDateTime = 0
self.fcSttbfAssoc = struct.unpack('<I', data[0x100:0x104])[0]
self.ole_logger.debug('DOC.FIB.FibRgFcLcb.fcSttbfAssoc: ' + str(hex(self.fcSttbfAssoc)))
self.lcbSttbfAssoc = struct.unpack('<I', data[0x104:0x108])[0]
self.ole_logger.debug('DOC.FIB.FibRgFcLcb.lcbSttbfAssoc: ' + str(hex(self.lcbSttbfAssoc)))
self.fcSttbfRMark = struct.unpack('<I', data[0x198:0x19C])[0]
self.ole_logger.debug('DOC.FIB.FibRgFcLcb.fcSttbfRMark: ' + str(hex(self.fcSttbfRMark)))
self.lcbSttbfRMark = struct.unpack('<I', data[0x19C:0x1A0])[0]
self.ole_logger.debug('DOC.FIB.FibRgFcLcb.lcbSttbfRMark: ' + str(hex(self.lcbSttbfRMark)))
self.fcSttbSavedBy = struct.unpack('<I', data[0x238:0x23C])[0]
self.ole_logger.debug('DOC.FIB.FibRgFcLcb.fcSttbSavedBy: ' + str(hex(self.fcSttbSavedBy)))
self.lcbSttbSavedBy = struct.unpack('<I', data[0x23C:0x240])[0]
self.ole_logger.debug('DOC.FIB.FibRgFcLcb.lcbSttbSavedBy: ' + str(hex(self.lcbSttbSavedBy)))
self.dwLowDateTime = struct.unpack('<I', data[0x2B8:0x2BC])[0]
self.ole_logger.debug('DOC.FIB.FibRgFcLcb.dwLowDateTime: ' + str(hex(self.dwLowDateTime)))
self.dwHighDateTime = struct.unpack('<I', data[0x2BC:0x2C0])[0]
self.ole_logger.debug('DOC.FIB.FibRgFcLcb.dwHighDateTime: ' + str(hex(self.dwHighDateTime)))
class FIB(OLEBase):
FIBBase = None
csw = 0
fibRgW = ''
cslw = 0
fibRgLw = ''
cbRgFcLcb = 0
fibRgFcLcbBlob = ''
cswNew = 0
def __init__(self, data):
self.FIBBase = None
self.csw = 0
self.fibRgW = ''
self.cslw = 0
self.fibRgLw = ''
self.cbRgFcLcb = 0
self.fibRgFcLcbBlob = ''
self.cswNew = 0
self.ole_logger.debug('######## FIB ########')
self.FIBBase = FIBBase(data[0:0x20])
self.csw = struct.unpack('<H', data[0x20:0x22])[0]
self.ole_logger.debug('DOC.FIB.csw: ' + str(hex(self.csw)))
if self.csw != 0x000E:
self._raise_exception('DOC.FIB.csw has an abnormal value.')
self.fibRgW = data[0x22:0x3E]
self.cslw = struct.unpack('<H', data[0x3E:0x40])[0]
self.ole_logger.debug('DOC.FIB.cslw: ' + str(hex(self.cslw)))
if self.cslw != 0x0016:
self._raise_exception('DOC.FIB.cslw has an abnormal value.')
self.fibRgLw = data[0x40:0x98]
self.cbRgFcLcb = struct.unpack('<H', data[0x98:0x9A])[0]
self.ole_logger.debug('DOC.FIB.cbRgFcLcb: ' + str(hex(self.cbRgFcLcb)))
'''
if self.FIBBase.nFib == 0x00C1 and self.cbRgFcLcb != 0x005D:
self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.')
if self.FIBBase.nFib == 0x00D9 and self.cbRgFcLcb != 0x006C:
self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.')
if self.FIBBase.nFib == 0x0101 and self.cbRgFcLcb != 0x0088:
self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.')
if self.FIBBase.nFib == 0x010C and self.cbRgFcLcb != 0x00A4:
self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.')
if self.FIBBase.nFib == 0x0112 and self.cbRgFcLcb != 0x00B7:
self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.')
'''
self.fibRgFcLcbBlob = FibRgFcLcb(data[0x9A:0x9A+self.cbRgFcLcb*8])
self.cswNew = struct.unpack('<H', data[0x9A+self.cbRgFcLcb*8:0x9A+self.cbRgFcLcb*8+0x02])[0]
self.ole_logger.debug('DOC.FIB.cswNew: ' + str(hex(self.cswNew)))
class DOCFile(OLEBase):
OLE = None
FIB = None
SummaryInfo = None
DocumentSummaryInfo = None
def __init__(self, filename):
self.OLE = None
self.FIB = None
self.SummaryInfo = None
self.DocumentSummaryInfo = None
if os.path.isfile(filename) == False:
self._raise_exception('Invalid file: ' + filename)
self.OLE = OLEFile(filename)
self.ole_logger.debug('***** Parse Word Document *****')
self.FIB = FIB(self.OLE.find_object_by_name('WordDocument'))
def show_rmark_authors(self):
if self.FIB.fibRgFcLcbBlob.fcSttbfRMark != 0:
table_stream = ''
if self.FIB.FIBBase.fWhichTblStm == 1:
table_stream = self.OLE.find_object_by_name('1Table')
elif self.FIB.FIBBase.fWhichTblStm == 1:
table_stream = self.OLE.find_object_by_name('0Table')
else:
print 'DOC.FIB.FIBBase.fWhichTblStm has an abnormal value.'
return
if len(table_stream) > 0:
#print table_stream
offset = self.FIB.fibRgFcLcbBlob.fcSttbfRMark
length = self.FIB.fibRgFcLcbBlob.lcbSttbfRMark
SttbfRMark = table_stream[offset:offset+length]
fExtend = struct.unpack('<H', SttbfRMark[0x00:0x02])[0]
if fExtend != 0xFFFF:
print 'fExtend has an abnormal value.'
return
cbExtra = struct.unpack('<H', SttbfRMark[0x04:0x06])[0]
if cbExtra != 0:
print 'cbExtra has an abnormal value.'
return
cData = struct.unpack('<H', SttbfRMark[0x02:0x04])[0]
offset = 0
for i in range(0, cData):
cchData = struct.unpack('<H', SttbfRMark[0x06+offset:0x08+offset])[0]
Data = SttbfRMark[0x06+offset+0x02:0x08+offset+cchData*2]
print Data.decode('utf-16')
offset = offset + 0x02 + cchData*2
else:
print 'Failed to read the Table Stream.'
else:
print 'No revision marks or comments author information.'
if __name__ == '__main__':
init_logging(True)
try:
docfile = DOCFile('oletest.doc')
docfile.show_rmark_authors()
except Exception as e:
print e
| {
"repo_name": "z3r0zh0u/pyole",
"path": "pydoc.py",
"copies": "1",
"size": "14460",
"license": "mit",
"hash": 3531995812502524400,
"line_mean": 39.2813370474,
"line_max": 137,
"alpha_frac": 0.5933609959,
"autogenerated": false,
"ratio": 2.856014220817697,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3949375216717697,
"avg_score": null,
"num_lines": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.