<commit_before>#!/usr/bin/python
#A simple script to check for AUR package updates
#By Charles Bos

from subprocess import Popen, PIPE
from bs4 import BeautifulSoup
import requests
import os

aurPkgs = Popen(["pacman", "-Qm"], stdout = PIPE).communicate()
aurPkgs = (str(aurPkgs).replace("\\n", " ").replace("b\'", "").replace("\', None", "").strip("()").rstrip(" ")).split(" ")

counter = 0
while counter < len(aurPkgs) - 1 :
    aurPkgs[counter] = (aurPkgs[counter], aurPkgs[counter + 1])
    del aurPkgs[counter + 1]
    counter += 1

updates = []
splitPkgs = []
mismatches = []
failures = []

for x in aurPkgs:
    try :
        response = requests.get("https://aur.archlinux.org/packages/" + x[0])
    except requests.ConnectionError :
        print("Error. Connection to network failed.")
        os._exit(0)
    page = str(BeautifulSoup(response.content, "html.parser"))
    start = page.find("
Package Details: ")
    if start == -1 : failures.append(x[0])
    else :
        end = page.find("
", start)
        version = page[start + 21:end].split(" ")[1]
        if x[1] < version :
            updates.append(str(x[0] + " " +x[1] + " --> " + version))
            pkgBaseStart = page.find('''View PKGBUILD /''')
            pkgBase = page[pkgBaseStart + 64:pkgBaseEnd]
            if x[0] != pkgBase : splitPkgs.append(str(x[0] + " " +x[1] + " --> " + version))
        elif x[1] > version : mismatches.append(str(x[0] + " - (local) " +x[1] + " (AUR) " + version))

if updates == mismatches == failures == [] : print("Everything is up to date.")
else :
    if failures != [] :
        print("The following packages were not found in the AUR:\n-----")
        for x in failures : print(x)
        if (mismatches != []) or (updates != []) : print()
    if mismatches != [] :
        print("The following local packages are more recent than their AUR versions:\n-----")
        for x in mismatches : print(x)
        if updates != [] : print()
    if updates != [] :
        print("The following packages have updates available:\n-----")
        for x in updates : print(x)
        fetch = input("\nFetch updated tarballs? [y/n] ")
        if fetch == "y" :
            homeDir = os.path.expanduser('~')
            if os.path.exists(homeDir + "/Downloads") : downloadsDir = homeDir + "/Downloads"
            else : downloadsDir = homeDir
            for x in updates :
                if x in splitPkgs : continue
                newPkg = x.split(' ')[0]
                pkgUrl = "https://aur.archlinux.org/cgit/aur.git/snapshot/" + newPkg + ".tar.gz"
                Popen(["wget", "-q", pkgUrl, "-P", downloadsDir]).wait()
                if os.path.exists(downloadsDir + "/" + newPkg + ".tar.gz") : completion = "SUCCESS"
                else : completion = "FAILURE"
                print("Fetch: " + newPkg + ".tar.gz - " + completion)
            print("\nDownloads completed. Check: " + downloadsDir)
<commit_msg>aurcheck.py - try and improve version comparison. simple string comparison sometimes gives inconsistent results<commit_after>#!/usr/bin/python
#A simple script to check for AUR package updates
#By Charles Bos

from subprocess import Popen, PIPE
from bs4 import BeautifulSoup
import requests
import os

def versionCheck(localVer, aurVer) :
    #Compare versions by splitting version string at "." and comparing each number in turn -
    #letters will be converted into their ascii codes. If lengths are not equal after
    #splitting, this cannot be don properly so fall back to simple string comparison.
    if localVer == aurVer : return 0
    versions = [localVer, aurVer]
    for x in versions :
        y = list(x)
        for z in y :
            if (z != ".") and (z != "-") :
                try :
                    int(z)
                except ValueError :
                    y[y.index(z)] = str(ord(z))
        y = ''.join(y)
        y = y.replace("-", ".")
        y = y.split(".")
        versions[versions.index(x)] = y

    if len(versions[0]) == len(versions[1]) :
        counter = 0
        while counter < len(versions[0]) :
            if int(versions[1][counter]) > int(versions[0][counter]) : return 1
            elif int(versions[1][counter]) < int(versions[0][counter]) : return -1
            counter += 1
    else :
        if aurVer > localVer : return 1
        elif aurVer < localVer : return -1

aurPkgs = Popen(["pacman", "-Qm"], stdout = PIPE).communicate()
aurPkgs = (str(aurPkgs).replace("\\n", " ").replace("b\'", "").replace("\', None", "").strip("()").rstrip(" ")).split(" ")

counter = 0
while counter < len(aurPkgs) - 1 :
    aurPkgs[counter] = (aurPkgs[counter], aurPkgs[counter + 1])
    del aurPkgs[counter + 1]
    counter += 1

updates = []
splitPkgs = []
mismatches = []
failures = []

for x in aurPkgs:
    try :
        response = requests.get("https://aur.archlinux.org/packages/" + x[0])
    except requests.ConnectionError :
        print("Error. Connection to network failed.")
        os._exit(0)
    page = str(BeautifulSoup(response.content, "html.parser"))
    start = page.find("
Package Details: ")
    if start == -1 : failures.append(x[0])
    else :
        end = page.find("
", start)
        version = page[start + 21:end].split(" ")[1]
        comparison = versionCheck(x[1], version)
        if comparison == 1 :
            updates.append(str(x[0] + " " +x[1] + " --> " + version))
            pkgBaseStart = page.find('''View PKGBUILD /''')
            pkgBase = page[pkgBaseStart + 64:pkgBaseEnd]
            if x[0] != pkgBase : splitPkgs.append(str(x[0] + " " +x[1] + " --> " + version))
        elif comparison == -1 : mismatches.append(str(x[0] + " - (local) " +x[1] + " (AUR) " + version))

if updates == mismatches == failures == [] : print("Everything is up to date.")
else :
    if failures != [] :
        print("The following packages were not found in the AUR:\n-----")
        for x in failures : print(x)
        if (mismatches != []) or (updates != []) : print()
    if mismatches != [] :
        print("The following local packages are more recent than their AUR versions:\n-----")
        for x in mismatches : print(x)
        if updates != [] : print()
    if updates != [] :
        print("The following packages have updates available:\n-----")
        for x in updates : print(x)
        fetch = input("\nFetch updated tarballs? [y/n] ")
        if fetch == "y" :
            homeDir = os.path.expanduser('~')
            if os.path.exists(homeDir + "/Downloads") : downloadsDir = homeDir + "/Downloads"
            else : downloadsDir = homeDir
            for x in updates :
                if x in splitPkgs : continue
                newPkg = x.split(' ')[0]
                pkgUrl = "https://aur.archlinux.org/cgit/aur.git/snapshot/" + newPkg + ".tar.gz"
                Popen(["wget", "-q", pkgUrl, "-P", downloadsDir]).wait()
                if os.path.exists(downloadsDir + "/" + newPkg + ".tar.gz") : completion = "SUCCESS"
                else : completion = "FAILURE"
                print("Fetch: " + newPkg + ".tar.gz - " + completion)
            print("\nDownloads completed. Check: " + downloadsDir)
<|endoftext|>


<commit_before>#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""Apache Beam SDK for Python setup file."""

from __future__ import absolute_import
from __future__ import print_function

import os
import platform
import sys
import warnings
from distutils import log
from distutils.errors import DistutilsError
from distutils.version import StrictVersion

# Pylint and isort disagree here.
# pylint: disable=ungrouped-imports
import setuptools
from pkg_resources import DistributionNotFound
from pkg_resources import get_distribution
from pkg_resources import normalize_path
from pkg_resources import to_filename
from setuptools import Command
from setuptools.command.build_py import build_py
from setuptools.command.develop import develop
from setuptools.command.egg_info import egg_info
from setuptools.command.test import test

class mypy(Command):
  user_options = []

  def initialize_options(self):
    """Abstract method that is required to be overwritten"""

  def finalize_options(self):
    """Abstract method that is required to be overwritten"""

  def get_project_path(self):
    self.run_command('egg_info')

    # Build extensions in-place
    self.reinitialize_command('build_ext', inplace=1)
    self.run_command('build_ext')

    ei_cmd = self.get_finalized_command("egg_info")

    project_path = normalize_path(ei_cmd.egg_base)
    return os.path.join(project_path, to_filename(ei_cmd.egg_name))

  def run(self):
    import subprocess
    args = ['mypy', self.get_project_path()]
    result = subprocess.call(args)
    if result != 0:
      raise DistutilsError("mypy exited with status %d" % result)

def get_version():
  global_names = {}
  exec(  # pylint: disable=exec-used
      open(os.path.join(
          os.path.dirname(os.path.abspath(__file__)),
          'apache_beam/version.py')
          ).read(),
      global_names
  )
  return global_names['__version__']

PACKAGE_NAME = 'apache-beam'
PACKAGE_VERSION = get_version()
PACKAGE_DESCRIPTION = 'Apache Beam SDK for Python'
PACKAGE_URL = 'https://beam.apache.org'
PACKAGE_DOWNLOAD_URL = 'https://pypi.python.org/pypi/apache-beam'
PACKAGE_AUTHOR = 'Apache Software Foundation'
PACKAGE_EMAIL = 'dev@beam.apache.org'
PACKAGE_KEYWORDS = 'apache beam'
PACKAGE_LONG_DESCRIPTION = '''
Apache Beam is a unified programming model for both batch and streaming
data processing, enabling efficient execution across diverse distributed
execution engines and providing extensibility points for connecting to
different technologies and user communities.
'''

REQUIRED_PIP_VERSION = '7.0.0'
_PIP_VERSION = get_distribution('pip').version
if StrictVersion(_PIP_VERSION) < StrictVersion(REQUIRED_PIP_VERSION):
  warnings.warn(
      "You are using version {0} of pip. " \
      "However, version {1} is recommended.".format(
          _PIP_VERSION, REQUIRED_PIP_VERSION
      )
  )

REQUIRED_CYTHON_VERSION = '0.28.1'
try:
  _CYTHON_VERSION = get_distribution('cython').version
  if StrictVersion(_CYTHON_VERSION) < StrictVersion(REQUIRED_CYTHON_VERSION):
    warnings.warn(
        "You are using version {0} of cython. " \
        "However, version {1} is recommended.".format(
            _CYTHON_VERSION, REQUIRED_CYTHON_VERSION
        )
    )
except DistributionNotFound:
  # do nothing if Cython is not installed
  pass

# Currently all compiled modules are optional  (for performance only).
if platform.system() == 'Windows':
  # Windows doesn't always provide int64_t.
  cythonize = lambda *args, **kwargs: []
else:
  try:
    # pylint: disable=wrong-import-position
    from Cython.Build import cythonize
  except ImportError:
    cythonize = lambda *args, **kwargs: []

REQUIRED_PACKAGES = [
    'avro>=1.8.1,<2.0.0; python_version < "3.0"',
    'avro-python3>=1.8.1,!=1.9.2,<2.0.0; python_version >= "3.0"',
    'crcmod>=1.7,<2.0',
    # Dill doesn't have forwards-compatibility guarantees within minor version.
    # Pickles created with a new version of dill may not unpickle using older
    # version of dill. It is best to use the same version of dill on client and
    # server, therefore list of allowed versions is very narrow.
    # See: https://github.com/uqfoundation/dill/issues/341.
    'dill>=0.3.1.1,<0.3.2',
    'fastavro>=0.21.4,<0.22',
    'funcsigs>=1.0.2,<2; python_version < "3.0"',
    'future>=0.16.0,<1.0.0',
    'futures>=3.2.0,<4.0.0; python_version < "3.0"',
    'grpcio>=1.12.1,<2',
    'hdfs>=2.1.0,<3.0.0',
    'httplib2>=0.8,<=0.12.0',
    'mock>=1.0.1,<3.0.0',
    'numpy>=1.14.3,<2',
    'pymongo>=3.8.0,<4.0.0',
    'oauth2client>=2.0.1,<4',
    'protobuf>=3.5.0.post1,<4',
    # [BEAM-6287] pyarrow is not supported on Windows for Python 2
    ('pyarrow>=0.15.1,<0.16.0; python_version >= "3.0" or '
     'platform_system != "Windows"'),
    'pydot>=1.2.0,<2',
    'python-dateutil>=2.8.0,<3',
    'pytz>=2018.3',
    # [BEAM-5628] Beam VCF IO is not supported in Python 3.
    'pyvcf>=0.6.8,<0.7.0; python_version < "3.0"',
    # fixes and additions have been made since typing 3.5
    'typing>=3.7.0,<3.8.0; python_version < "3.8.0"',
    'typing-extensions>=3.7.0,<3.8.0; python_version < "3.8.0"',
    ]

# [BEAM-8181] pyarrow cannot be installed on 32-bit Windows platforms.
if sys.platform == 'win32' and sys.maxsize <= 2**32:
  REQUIRED_PACKAGES = [
      p for p in REQUIRED_PACKAGES if not p.startswith('pyarrow')
  ]

REQUIRED_TEST_PACKAGES = [
    'freezegun>=0.3.12',
    'nose>=1.3.7',
    'nose_xunitmp>=0.4.1',
    'pandas>=0.23.4,<0.25',
    'parameterized>=0.6.0,<0.8.0',
    # pyhamcrest==1.10.0 doesn't work on Py2. Beam still supports Py2.
    # See: https://github.com/hamcrest/PyHamcrest/issues/131.
    'pyhamcrest>=1.9,!=1.10.0,<2.0.0',
    'pyyaml>=3.12,<6.0.0',
    'requests_mock>=1.7,<2.0',
    'tenacity>=5.0.2,<6.0',
    'pytest>=4.4.0,<5.0',
    'pytest-xdist>=1.29.0,<2',
    'pytest-timeout>=1.3.3,<2',
    ]

GCP_REQUIREMENTS = [
    'cachetools>=3.1.0,<4',
    'google-apitools>=0.5.28,<0.5.29',
    # [BEAM-4543] googledatastore is not supported in Python 3.
    'googledatastore>=7.0.1,<7.1; python_version < "3.0"',
    'google-cloud-datastore>=1.7.1,<1.8.0',
    'google-cloud-pubsub>=0.39.0,<1.1.0',
    # GCP packages required by tests
    'google-cloud-bigquery>=1.6.0,<1.18.0',
    'google-cloud-core>=0.28.1,<2',
    'google-cloud-bigtable>=0.31.1,<1.1.0',
    # [BEAM-4543] googledatastore is not supported in Python 3.
    'proto-google-cloud-datastore-v1>=0.90.0,<=0.90.4; python_version < "3.0"',
    'google-cloud-spanner>=1.13.0,<1.14.0',
    'grpcio-gcp>=0.2.2,<1',
]

INTERACTIVE_BEAM = [
    'facets-overview>=1.0.0,<2',
    'ipython>=5.8.0,<6',
    # jsons is supported by Python 3.5.3+.
    'jsons>=1.0.0,<2; python_version >= "3.5.3"',
    'timeloop>=1.0.2,<2',
]
AWS_REQUIREMENTS = [
    'boto3 >=1.9'
]

# We must generate protos after setup_requires are installed.
def generate_protos_first(original_cmd):
  try:
    # See https://issues.apache.org/jira/browse/BEAM-2366
    # pylint: disable=wrong-import-position
    import gen_protos

    class cmd(original_cmd, object):
      def run(self):
        gen_protos.generate_proto_files(log=log)
        super(cmd, self).run()
    return cmd
  except ImportError:
    warnings.warn("Could not import gen_protos, skipping proto generation.")
    return original_cmd

python_requires = '>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*'

if sys.version_info[0] == 2:
  warnings.warn(
      'You are using Apache Beam with Python 2. '
      'New releases of Apache Beam will soon support Python 3 only.')

setuptools.setup(
    name=PACKAGE_NAME,
    version=PACKAGE_VERSION,
    description=PACKAGE_DESCRIPTION,
    long_description=PACKAGE_LONG_DESCRIPTION,
    url=PACKAGE_URL,
    download_url=PACKAGE_DOWNLOAD_URL,
    author=PACKAGE_AUTHOR,
    author_email=PACKAGE_EMAIL,
    packages=setuptools.find_packages(),
    package_data={'apache_beam': [
        '*/*.pyx', '*/*/*.pyx', '*/*.pxd', '*/*/*.pxd', 'testing/data/*.yaml',
        'portability/api/*.yaml']},
    ext_modules=cythonize([
        'apache_beam/**/*.pyx',
        'apache_beam/coders/coder_impl.py',
        'apache_beam/metrics/cells.py',
        'apache_beam/metrics/execution.py',
        'apache_beam/runners/common.py',
        'apache_beam/runners/worker/logger.py',
        'apache_beam/runners/worker/opcounters.py',
        'apache_beam/runners/worker/operations.py',
        'apache_beam/transforms/cy_combiners.py',
        'apache_beam/utils/counters.py',
        'apache_beam/utils/windowed_value.py',
    ]),
    install_requires=REQUIRED_PACKAGES,
    python_requires=python_requires,
    test_suite='nose.collector',
    # BEAM-8840: Do NOT use tests_require or setup_requires.
    extras_require={
        'docs': ['Sphinx>=1.5.2,<2.0'],
        'test': REQUIRED_TEST_PACKAGES,
        'gcp': GCP_REQUIREMENTS,
        'interactive': INTERACTIVE_BEAM,
        'aws': AWS_REQUIREMENTS
    },
    zip_safe=False,
    # PyPI package information.
    classifiers=[
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Topic :: Software Development :: Libraries',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    license='Apache License, Version 2.0',
    keywords=PACKAGE_KEYWORDS,
    entry_points={
        'nose.plugins.0.10': [
            'beam_test_plugin = test_config:BeamTestPlugin',
        ]},
    cmdclass={
        'build_py': generate_protos_first(build_py),
        'develop': generate_protos_first(develop),
        'egg_info': generate_protos_first(egg_info),
        'test': generate_protos_first(test),
        'mypy': generate_protos_first(mypy),
    },
)
<commit_msg>Pin Avro dependency in Python SDK to be consistent with Avro versioning<commit_after>#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""Apache Beam SDK for Python setup file."""

from __future__ import absolute_import
from __future__ import print_function

import os
import platform
import sys
import warnings
from distutils import log
from distutils.errors import DistutilsError
from distutils.version import StrictVersion

# Pylint and isort disagree here.
# pylint: disable=ungrouped-imports
import setuptools
from pkg_resources import DistributionNotFound
from pkg_resources import get_distribution
from pkg_resources import normalize_path
from pkg_resources import to_filename
from setuptools import Command
from setuptools.command.build_py import build_py
from setuptools.command.develop import develop
from setuptools.command.egg_info import egg_info
from setuptools.command.test import test

class mypy(Command):
  user_options = []

  def initialize_options(self):
    """Abstract method that is required to be overwritten"""

  def finalize_options(self):
    """Abstract method that is required to be overwritten"""

  def get_project_path(self):
    self.run_command('egg_info')

    # Build extensions in-place
    self.reinitialize_command('build_ext', inplace=1)
    self.run_command('build_ext')

    ei_cmd = self.get_finalized_command("egg_info")

    project_path = normalize_path(ei_cmd.egg_base)
    return os.path.join(project_path, to_filename(ei_cmd.egg_name))

  def run(self):
    import subprocess
    args = ['mypy', self.get_project_path()]
    result = subprocess.call(args)
    if result != 0:
      raise DistutilsError("mypy exited with status %d" % result)

def get_version():
  global_names = {}
  exec(  # pylint: disable=exec-used
      open(os.path.join(
          os.path.dirname(os.path.abspath(__file__)),
          'apache_beam/version.py')
          ).read(),
      global_names
  )
  return global_names['__version__']

PACKAGE_NAME = 'apache-beam'
PACKAGE_VERSION = get_version()
PACKAGE_DESCRIPTION = 'Apache Beam SDK for Python'
PACKAGE_URL = 'https://beam.apache.org'
PACKAGE_DOWNLOAD_URL = 'https://pypi.python.org/pypi/apache-beam'
PACKAGE_AUTHOR = 'Apache Software Foundation'
PACKAGE_EMAIL = 'dev@beam.apache.org'
PACKAGE_KEYWORDS = 'apache beam'
PACKAGE_LONG_DESCRIPTION = '''
Apache Beam is a unified programming model for both batch and streaming
data processing, enabling efficient execution across diverse distributed
execution engines and providing extensibility points for connecting to
different technologies and user communities.
'''

REQUIRED_PIP_VERSION = '7.0.0'
_PIP_VERSION = get_distribution('pip').version
if StrictVersion(_PIP_VERSION) < StrictVersion(REQUIRED_PIP_VERSION):
  warnings.warn(
      "You are using version {0} of pip. " \
      "However, version {1} is recommended.".format(
          _PIP_VERSION, REQUIRED_PIP_VERSION
      )
  )

REQUIRED_CYTHON_VERSION = '0.28.1'
try:
  _CYTHON_VERSION = get_distribution('cython').version
  if StrictVersion(_CYTHON_VERSION) < StrictVersion(REQUIRED_CYTHON_VERSION):
    warnings.warn(
        "You are using version {0} of cython. " \
        "However, version {1} is recommended.".format(
            _CYTHON_VERSION, REQUIRED_CYTHON_VERSION
        )
    )
except DistributionNotFound:
  # do nothing if Cython is not installed
  pass

# Currently all compiled modules are optional  (for performance only).
if platform.system() == 'Windows':
  # Windows doesn't always provide int64_t.
  cythonize = lambda *args, **kwargs: []
else:
  try:
    # pylint: disable=wrong-import-position
    from Cython.Build import cythonize
  except ImportError:
    cythonize = lambda *args, **kwargs: []

REQUIRED_PACKAGES = [
    # Apache Avro does not follow semantic versioning, so we should not auto
    # upgrade on minor versions. However, due to an issue on Dataflow we need
    # to still include the previous version (1.8.x).
    'avro>=1.8.1,<1.10.0; python_version < "3.0"',
    # Avro 1.9.2 for python3 was broken. The issue was fixed in version 1.9.2.1
    'avro-python3>=1.8.1,!=1.9.2,<1.10.0; python_version >= "3.0"',
    'crcmod>=1.7,<2.0',
    # Dill doesn't have forwards-compatibility guarantees within minor version.
    # Pickles created with a new version of dill may not unpickle using older
    # version of dill. It is best to use the same version of dill on client and
    # server, therefore list of allowed versions is very narrow.
    # See: https://github.com/uqfoundation/dill/issues/341.
    'dill>=0.3.1.1,<0.3.2',
    'fastavro>=0.21.4,<0.22',
    'funcsigs>=1.0.2,<2; python_version < "3.0"',
    'future>=0.16.0,<1.0.0',
    'futures>=3.2.0,<4.0.0; python_version < "3.0"',
    'grpcio>=1.12.1,<2',
    'hdfs>=2.1.0,<3.0.0',
    'httplib2>=0.8,<=0.12.0',
    'mock>=1.0.1,<3.0.0',
    'numpy>=1.14.3,<2',
    'pymongo>=3.8.0,<4.0.0',
    'oauth2client>=2.0.1,<4',
    'protobuf>=3.5.0.post1,<4',
    # [BEAM-6287] pyarrow is not supported on Windows for Python 2
    ('pyarrow>=0.15.1,<0.16.0; python_version >= "3.0" or '
     'platform_system != "Windows"'),
    'pydot>=1.2.0,<2',
    'python-dateutil>=2.8.0,<3',
    'pytz>=2018.3',
    # [BEAM-5628] Beam VCF IO is not supported in Python 3.
    'pyvcf>=0.6.8,<0.7.0; python_version < "3.0"',
    # fixes and additions have been made since typing 3.5
    'typing>=3.7.0,<3.8.0; python_version < "3.8.0"',
    'typing-extensions>=3.7.0,<3.8.0; python_version < "3.8.0"',
    ]

# [BEAM-8181] pyarrow cannot be installed on 32-bit Windows platforms.
if sys.platform == 'win32' and sys.maxsize <= 2**32:
  REQUIRED_PACKAGES = [
      p for p in REQUIRED_PACKAGES if not p.startswith('pyarrow')
  ]

REQUIRED_TEST_PACKAGES = [
    'freezegun>=0.3.12',
    'nose>=1.3.7',
    'nose_xunitmp>=0.4.1',
    'pandas>=0.23.4,<0.25',
    'parameterized>=0.6.0,<0.8.0',
    # pyhamcrest==1.10.0 doesn't work on Py2. Beam still supports Py2.
    # See: https://github.com/hamcrest/PyHamcrest/issues/131.
    'pyhamcrest>=1.9,!=1.10.0,<2.0.0',
    'pyyaml>=3.12,<6.0.0',
    'requests_mock>=1.7,<2.0',
    'tenacity>=5.0.2,<6.0',
    'pytest>=4.4.0,<5.0',
    'pytest-xdist>=1.29.0,<2',
    'pytest-timeout>=1.3.3,<2',
    ]

GCP_REQUIREMENTS = [
    'cachetools>=3.1.0,<4',
    'google-apitools>=0.5.28,<0.5.29',
    # [BEAM-4543] googledatastore is not supported in Python 3.
    'googledatastore>=7.0.1,<7.1; python_version < "3.0"',
    'google-cloud-datastore>=1.7.1,<1.8.0',
    'google-cloud-pubsub>=0.39.0,<1.1.0',
    # GCP packages required by tests
    'google-cloud-bigquery>=1.6.0,<1.18.0',
    'google-cloud-core>=0.28.1,<2',
    'google-cloud-bigtable>=0.31.1,<1.1.0',
    # [BEAM-4543] googledatastore is not supported in Python 3.
    'proto-google-cloud-datastore-v1>=0.90.0,<=0.90.4; python_version < "3.0"',
    'google-cloud-spanner>=1.13.0,<1.14.0',
    'grpcio-gcp>=0.2.2,<1',
]

INTERACTIVE_BEAM = [
    'facets-overview>=1.0.0,<2',
    'ipython>=5.8.0,<6',
    # jsons is supported by Python 3.5.3+.
    'jsons>=1.0.0,<2; python_version >= "3.5.3"',
    'timeloop>=1.0.2,<2',
]
AWS_REQUIREMENTS = [
    'boto3 >=1.9'
]

# We must generate protos after setup_requires are installed.
def generate_protos_first(original_cmd):
  try:
    # See https://issues.apache.org/jira/browse/BEAM-2366
    # pylint: disable=wrong-import-position
    import gen_protos

    class cmd(original_cmd, object):
      def run(self):
        gen_protos.generate_proto_files(log=log)
        super(cmd, self).run()
    return cmd
  except ImportError:
    warnings.warn("Could not import gen_protos, skipping proto generation.")
    return original_cmd

python_requires = '>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*'

if sys.version_info[0] == 2:
  warnings.warn(
      'You are using Apache Beam with Python 2. '
      'New releases of Apache Beam will soon support Python 3 only.')

setuptools.setup(
    name=PACKAGE_NAME,
    version=PACKAGE_VERSION,
    description=PACKAGE_DESCRIPTION,
    long_description=PACKAGE_LONG_DESCRIPTION,
    url=PACKAGE_URL,
    download_url=PACKAGE_DOWNLOAD_URL,
    author=PACKAGE_AUTHOR,
    author_email=PACKAGE_EMAIL,
    packages=setuptools.find_packages(),
    package_data={'apache_beam': [
        '*/*.pyx', '*/*/*.pyx', '*/*.pxd', '*/*/*.pxd', 'testing/data/*.yaml',
        'portability/api/*.yaml']},
    ext_modules=cythonize([
        'apache_beam/**/*.pyx',
        'apache_beam/coders/coder_impl.py',
        'apache_beam/metrics/cells.py',
        'apache_beam/metrics/execution.py',
        'apache_beam/runners/common.py',
        'apache_beam/runners/worker/logger.py',
        'apache_beam/runners/worker/opcounters.py',
        'apache_beam/runners/worker/operations.py',
        'apache_beam/transforms/cy_combiners.py',
        'apache_beam/utils/counters.py',
        'apache_beam/utils/windowed_value.py',
    ]),
    install_requires=REQUIRED_PACKAGES,
    python_requires=python_requires,
    test_suite='nose.collector',
    # BEAM-8840: Do NOT use tests_require or setup_requires.
    extras_require={
        'docs': ['Sphinx>=1.5.2,<2.0'],
        'test': REQUIRED_TEST_PACKAGES,
        'gcp': GCP_REQUIREMENTS,
        'interactive': INTERACTIVE_BEAM,
        'aws': AWS_REQUIREMENTS
    },
    zip_safe=False,
    # PyPI package information.
    classifiers=[
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Topic :: Software Development :: Libraries',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    license='Apache License, Version 2.0',
    keywords=PACKAGE_KEYWORDS,
    entry_points={
        'nose.plugins.0.10': [
            'beam_test_plugin = test_config:BeamTestPlugin',
        ]},
    cmdclass={
        'build_py': generate_protos_first(build_py),
        'develop': generate_protos_first(develop),
        'egg_info': generate_protos_first(egg_info),
        'test': generate_protos_first(test),
        'mypy': generate_protos_first(mypy),
    },
)
<|endoftext|>


<commit_before>import pyopencl as cl

## Tutorial 1: OpenCL structures
# In this part you can learn, how to build up the basic structures that are needed for parallel programming
# in OpenCL/PyOpenCL. This code only contains the absolute minimum you need for an application. If you are interested in
# the structures in more detail, set breakpoints and inspect the object attributes, visit the documentation of PyOpenCL
# (https://documen.tician.de/pyopencl/) or continue with the next tutorials.

############
# Platform #
############

# Looking for different openCL implementations on your hardware (platforms):
platforms = cl.get_platforms()

##########
# Device #
##########

# Looking for available devices (CPU, GPU, Accelerator) for each platform:
platform_devices = []
for platform in platforms:
    devices = platform.get_devices()
    platform_devices.append(devices)

###########
# Context #
###########

# A context is a structure that manages a set of devices of one specific platform.
# A host application is able to work with contexts of different platforms.
# Devices of contexts from different platforms are not able to share resources.

# There are two ways to create a context:
# 1. for specific devices. In this case, create a context for all devices of the first platform:
contextA = cl.Context(platform_devices[0])
# 2. for all devices for the first platform of a given type:
contextB = cl.Context(dev_type=cl.device_type.GPU, properties=[(cl.context_properties.PLATFORM, platforms[0])])
contextC = cl.Context(dev_type=cl.device_type.CPU, properties=[(cl.context_properties.PLATFORM, platforms[0])])

# OpenCL tracks how often a context structure is accessed. This number is called the reference count.
r_count_A = contextA.get_info(cl.context_info.REFERENCE_COUNT)

###########
# Program #
###########

filename = 'exampleKernelFunction.cl'
file = open(filename, 'r')
filestring = "".join(file.readlines())
program = cl.Program(contextA, filestring).build()

###################
# Kernel Function #
###################

# A kernel function represents a function that should be executed in parallel.
# The kernel function is build by an OpenCL-program, that can contain multiple kernels.

#################
# Command Queue #
#################

####################
# Kernel Execution #
####################
<commit_msg>opencl structures: build kernels (work in progress)<commit_after>import pyopencl as cl
import numpy as np

## Tutorial 1: OpenCL structures
# In this part you can learn, how to build up the basic structures that are needed for parallel programming
# in OpenCL/PyOpenCL. This code only contains the absolute minimum you need for an application. If you are interested in
# the structures in more detail, set breakpoints and inspect the object attributes, visit the documentation of PyOpenCL
# (https://documen.tician.de/pyopencl/) or continue with the next tutorials.

############
# Platform #
############

# Looking for different openCL implementations on your hardware (platforms):
platforms = cl.get_platforms()

##########
# Device #
##########

# Looking for available devices (CPU, GPU, Accelerator) for each platform:
platform_devices = []
for platform in platforms:
    devices = platform.get_devices()
    platform_devices.append(devices)

###########
# Context #
###########

# A context is a structure that manages a set of devices of one specific platform.
# A host application is able to work with contexts of different platforms.
# Devices of contexts from different platforms are not able to share resources.

# There are two ways to create a context:
# 1. for specific devices. In this case, create a context for all devices of the first platform:
contextA = cl.Context(platform_devices[0])
# 2. for all devices for the first platform of a given type:
try:
    contextB = cl.Context(dev_type=cl.device_type.GPU, properties=[(cl.context_properties.PLATFORM, platforms[0])])
except:
    contextC = cl.Context(dev_type=cl.device_type.CPU, properties=[(cl.context_properties.PLATFORM, platforms[0])])

# OpenCL tracks how often a context structure is accessed. This number is called the reference count.
r_count_A = contextA.get_info(cl.context_info.REFERENCE_COUNT)

###################
# Kernel Function #
###################

# A kernel function represents a function that should be executed in parallel.
# For example have a look at this function:

def subtract_offset(vector, offset):
    shape = vector.shape
    if len(shape) == 1:
        result = np.zeros(len(vector))
        for element in range(0, len(vector)):
            result[element] = vector[element] - offset
        return result
    else:
        print("The subtract_offset method works only for one-dimensional arrays.")

kernelstringA = """__kernel void exampleKernelFunction(global int* inputdata, global int* outputdata){

     int loopindex = get_global_id(0);
     int offset = 1;
     outputdata[loopindex] = inputdata[loopindex] - offset;

}"""

filename = 'exampleKernelFunction.cl'
file = open(filename, 'r')
kernelstringB = "".join(file.readlines())

###########
# Program #
###########

# The kernel function is build by an OpenCL-program, that can contain multiple kernels.

programA = cl.Program(contextA, kernelstringA).build()
programB = cl.Program(contextA, kernelstringB).build()

# Every time you use program.kernel_name a new kernel object is produced.

#################
# Command Queue #
#################

#########################
# Kernel Execution Time #
#########################

###############
# Simple Test #
###############

testvector = np.array([1, 2, 3, 4, 5, 6, 7, 8]).astype(np.int32)
offset = 1
cpuresult = subtract_offset(testvector, offset)<|endoftext|>


<commit_before>"""
PyNetgear allows you to interface with your NETGEAR wireless router.
"""
from .pynetgear import Netgear
<commit_msg>Clean up unnecessary files<commit_after><|endoftext|>


<commit_before>

from apgl.util.Util import Util
from exp.sandbox.recommendation.IterativeSoftImpute import IterativeSoftImpute
from exp.sandbox.recommendation.SoftImpute import SoftImpute
import sys
import numpy
import unittest
import logging
import scipy.sparse
import numpy.linalg
import numpy.testing as nptst
import exp.util.SparseUtils as ExpSU

class IterativeSoftImputeTest(unittest.TestCase):
    def setUp(self):
        logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
        numpy.set_printoptions(precision=4, suppress=True, linewidth=200)

        numpy.seterr(all="raise")
        numpy.random.seed(21)

        #Create a sequence of matrices
        n = 20
        m = 10
        r = 8
        U, s, V = ExpSU.SparseUtils.generateLowRank((n, m), r)

        numInds = 200
        inds = numpy.random.randint(0, n*m-1, numInds)
        inds = numpy.unique(inds)
        numpy.random.shuffle(inds)
        numInds = inds.shape[0]

        inds1 = inds[0:numInds/3]
        inds2 = inds[0:2*numInds/3]
        inds3 = inds

        X1 = ExpSU.SparseUtils.reconstructLowRank(U, s, V, inds1)
        X2 = ExpSU.SparseUtils.reconstructLowRank(U, s, V, inds2)
        X3 = ExpSU.SparseUtils.reconstructLowRank(U, s, V, inds3)

        self.matrixList = [X1, X2, X3]
        self.indsList = [inds1, inds2, inds3]

    def testLearnModel(self):
        lmbda = 0.0
        eps = 0.1
        k = 10

        matrixIterator = iter(self.matrixList)
        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=k, eps=eps, svdAlg="propack")
        ZList = iterativeSoftImpute.learnModel(matrixIterator)

        #Check that ZList is the same as XList
        for i, Z in enumerate(ZList):
            U, s, V = Z
            Xhat = (U*s).dot(V.T)

            nptst.assert_array_almost_equal(Xhat, self.matrixList[i].todense())

        #Compare solution with that of SoftImpute class
        lmbdaList = [0.1, 0.2, 0.5, 1.0]

        for lmbda in lmbdaList:
            iterativeSoftImpute = IterativeSoftImpute(lmbda, k=k, eps=eps, svdAlg="propack", updateAlg="zero")

            matrixIterator = iter(self.matrixList)
            ZList = iterativeSoftImpute.learnModel(matrixIterator)

            lmbdas = numpy.array([lmbda])

            softImpute = SoftImpute(lmbdas, k=k, eps=eps)
            Z1 = softImpute.learnModel(self.matrixList[0])
            Z2 = softImpute.learnModel(self.matrixList[1])
            Z3 = softImpute.learnModel(self.matrixList[2])

            ZList2 = [Z1, Z2, Z3]

            for j, Zhat in enumerate(ZList):
                U, s, V = Zhat
                Z = (U*s).dot(V.T)
                nptst.assert_array_almost_equal(Z, ZList2[j].todense())

                #Also test with true solution Z = S_lambda(X + Z^\bot_\omega)
                Zomega = numpy.zeros(self.matrixList[j].shape)

                rowInds, colInds = self.matrixList[j].nonzero()
                for i in range(self.matrixList[j].nonzero()[0].shape[0]):
                    Zomega[rowInds[i], colInds[i]] = Z[rowInds[i], colInds[i]]

                U, s, V = ExpSU.SparseUtils.svdSoft(numpy.array(self.matrixList[j]-Zomega+Z), lmbda)

                tol = 0.1
                self.assertTrue(numpy.linalg.norm(Z -(U*s).dot(V.T))**2 < tol)

    def testLearnModel2(self):
        #Test the SVD updating solution in the case where we get an exact solution
        lmbda = 0.0
        eps = 0.1
        k = 20

        matrixIterator = iter(self.matrixList)
        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=k, eps=eps, svdAlg="RSVD")
        ZList = iterativeSoftImpute.learnModel(matrixIterator)

        #Check that ZList is the same as XList
        for i, Z in enumerate(ZList):
            U, s, V = Z
            Xhat = (U*s).dot(V.T)

            nptst.assert_array_almost_equal(Xhat, self.matrixList[i].todense())

        #Compare solution with that of SoftImpute class
        lmbdaList = [0.1, 0.2, 0.5, 1.0]

        for lmbda in lmbdaList:
            iterativeSoftImpute = IterativeSoftImpute(lmbda, k=k, eps=eps, svdAlg="RSVD", updateAlg="zero")

            matrixIterator = iter(self.matrixList)
            ZList = iterativeSoftImpute.learnModel(matrixIterator)

            lmbdas = numpy.array([lmbda])

            softImpute = SoftImpute(lmbdas, k=k, eps=eps)
            Z1 = softImpute.learnModel(self.matrixList[0])
            Z2 = softImpute.learnModel(self.matrixList[1])
            Z3 = softImpute.learnModel(self.matrixList[2])

            ZList2 = [Z1, Z2, Z3]

            for j, Zhat in enumerate(ZList):
                U, s, V = Zhat
                Z = (U*s).dot(V.T)
                nptst.assert_array_almost_equal(Z, ZList2[j].todense())

                #Also test with true solution Z = S_lambda(X + Z^\bot_\omega)
                Zomega = numpy.zeros(self.matrixList[j].shape)

                rowInds, colInds = self.matrixList[j].nonzero()
                for i in range(self.matrixList[j].nonzero()[0].shape[0]):
                    Zomega[rowInds[i], colInds[i]] = Z[rowInds[i], colInds[i]]

                U, s, V = ExpSU.SparseUtils.svdSoft(numpy.array(self.matrixList[j]-Zomega+Z), lmbda)

                tol = 0.1
                self.assertTrue(numpy.linalg.norm(Z -(U*s).dot(V.T))**2 < tol)

    def testLearnModel3(self):
        #Test using Randomised SVD

        #Test on an increasing then decreasing set of solutions
        pass

    #@unittest.skip("")
    def testPredict(self):
        #Create a set of indices
        lmbda = 0.0

        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=10)
        matrixIterator = iter(self.matrixList)
        ZList = iterativeSoftImpute.learnModel(matrixIterator)

        XhatList = iterativeSoftImpute.predict(ZList, self.indsList)

        #Check we get the exact matrices returned
        for i, Xhat in enumerate(XhatList):
            nptst.assert_array_almost_equal(numpy.array(Xhat.todense()), self.matrixList[i].todense())

            self.assertEquals(Xhat.nnz, self.indsList[i].shape[0])

        #Try moderate lambda
        lmbda = 0.1
        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=10)
        matrixIterator = iter(self.matrixList)
        ZList = list(iterativeSoftImpute.learnModel(matrixIterator))

        XhatList = iterativeSoftImpute.predict(iter(ZList), self.indsList)

        for i, Xhat in enumerate(XhatList):
            for ind in self.indsList[i]:
                U, s, V = ZList[i]
                Z = (U*s).dot(V.T)
                self.assertEquals(Xhat[numpy.unravel_index(ind, Xhat.shape)], Z[numpy.unravel_index(ind, Xhat.shape)])

            self.assertEquals(Xhat.nnz, self.indsList[i].shape[0])

    #@unittest.skip("")
    def testModelSelect(self):
        lmbda = 0.1
        shape = (100, 100)
        r = 20
        k = 100
        noise = 0.2
        X = ExpSU.SparseUtils.generateSparseLowRank(shape, r, k, noise)

        print("--------------------")
        print(X.nnz)
        U, s, V = numpy.linalg.svd(X.todense())
        print(s)

        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=10, svdAlg="propack", updateAlg="zero")
        lmbdas = numpy.linspace(numpy.max(s), 0.01, 10)
        folds = 5
        iterativeSoftImpute.modelSelect(X, lmbdas, folds)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()
    <commit_msg>Better tests for modelSelect <commit_after>

from apgl.util.Util import Util
from apgl.util.Sampling import Sampling
from apgl.util.MCEvaluator import MCEvaluator
from exp.sandbox.recommendation.IterativeSoftImpute import IterativeSoftImpute
from exp.sandbox.recommendation.SoftImpute import SoftImpute
import sys
import numpy
import unittest
import logging
import scipy.sparse
import numpy.linalg
import numpy.testing as nptst
import exp.util.SparseUtils as ExpSU

class IterativeSoftImputeTest(unittest.TestCase):
    def setUp(self):
        #logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
        numpy.set_printoptions(precision=4, suppress=True, linewidth=200)

        numpy.seterr(all="raise")
        numpy.random.seed(21)

        #Create a sequence of matrices
        n = 20
        m = 10
        r = 8
        U, s, V = ExpSU.SparseUtils.generateLowRank((n, m), r)

        numInds = 200
        inds = numpy.random.randint(0, n*m-1, numInds)
        inds = numpy.unique(inds)
        numpy.random.shuffle(inds)
        numInds = inds.shape[0]

        inds1 = inds[0:numInds/3]
        inds2 = inds[0:2*numInds/3]
        inds3 = inds

        X1 = ExpSU.SparseUtils.reconstructLowRank(U, s, V, inds1)
        X2 = ExpSU.SparseUtils.reconstructLowRank(U, s, V, inds2)
        X3 = ExpSU.SparseUtils.reconstructLowRank(U, s, V, inds3)

        self.matrixList = [X1, X2, X3]
        self.indsList = [inds1, inds2, inds3]

    def testLearnModel(self):
        lmbda = 0.0
        eps = 0.1
        k = 10

        matrixIterator = iter(self.matrixList)
        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=k, eps=eps, svdAlg="propack")
        ZList = iterativeSoftImpute.learnModel(matrixIterator)

        #Check that ZList is the same as XList
        for i, Z in enumerate(ZList):
            U, s, V = Z
            Xhat = (U*s).dot(V.T)

            nptst.assert_array_almost_equal(Xhat, self.matrixList[i].todense())

        #Compare solution with that of SoftImpute class
        lmbdaList = [0.1, 0.2, 0.5, 1.0]

        for lmbda in lmbdaList:
            iterativeSoftImpute = IterativeSoftImpute(lmbda, k=k, eps=eps, svdAlg="propack", updateAlg="zero")

            matrixIterator = iter(self.matrixList)
            ZList = iterativeSoftImpute.learnModel(matrixIterator)

            lmbdas = numpy.array([lmbda])

            softImpute = SoftImpute(lmbdas, k=k, eps=eps)
            Z1 = softImpute.learnModel(self.matrixList[0])
            Z2 = softImpute.learnModel(self.matrixList[1])
            Z3 = softImpute.learnModel(self.matrixList[2])

            ZList2 = [Z1, Z2, Z3]

            for j, Zhat in enumerate(ZList):
                U, s, V = Zhat
                Z = (U*s).dot(V.T)
                nptst.assert_array_almost_equal(Z, ZList2[j].todense())

                #Also test with true solution Z = S_lambda(X + Z^\bot_\omega)
                Zomega = numpy.zeros(self.matrixList[j].shape)

                rowInds, colInds = self.matrixList[j].nonzero()
                for i in range(self.matrixList[j].nonzero()[0].shape[0]):
                    Zomega[rowInds[i], colInds[i]] = Z[rowInds[i], colInds[i]]

                U, s, V = ExpSU.SparseUtils.svdSoft(numpy.array(self.matrixList[j]-Zomega+Z), lmbda)

                tol = 0.1
                self.assertTrue(numpy.linalg.norm(Z -(U*s).dot(V.T))**2 < tol)

    def testLearnModel2(self):
        #Test the SVD updating solution in the case where we get an exact solution
        lmbda = 0.0
        eps = 0.1
        k = 20

        matrixIterator = iter(self.matrixList)
        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=k, eps=eps, svdAlg="RSVD")
        ZList = iterativeSoftImpute.learnModel(matrixIterator)

        #Check that ZList is the same as XList
        for i, Z in enumerate(ZList):
            U, s, V = Z
            Xhat = (U*s).dot(V.T)

            nptst.assert_array_almost_equal(Xhat, self.matrixList[i].todense())

        #Compare solution with that of SoftImpute class
        lmbdaList = [0.1, 0.2, 0.5, 1.0]

        for lmbda in lmbdaList:
            iterativeSoftImpute = IterativeSoftImpute(lmbda, k=k, eps=eps, svdAlg="RSVD", updateAlg="zero")

            matrixIterator = iter(self.matrixList)
            ZList = iterativeSoftImpute.learnModel(matrixIterator)

            lmbdas = numpy.array([lmbda])

            softImpute = SoftImpute(lmbdas, k=k, eps=eps)
            Z1 = softImpute.learnModel(self.matrixList[0])
            Z2 = softImpute.learnModel(self.matrixList[1])
            Z3 = softImpute.learnModel(self.matrixList[2])

            ZList2 = [Z1, Z2, Z3]

            for j, Zhat in enumerate(ZList):
                U, s, V = Zhat
                Z = (U*s).dot(V.T)
                nptst.assert_array_almost_equal(Z, ZList2[j].todense())

                #Also test with true solution Z = S_lambda(X + Z^\bot_\omega)
                Zomega = numpy.zeros(self.matrixList[j].shape)

                rowInds, colInds = self.matrixList[j].nonzero()
                for i in range(self.matrixList[j].nonzero()[0].shape[0]):
                    Zomega[rowInds[i], colInds[i]] = Z[rowInds[i], colInds[i]]

                U, s, V = ExpSU.SparseUtils.svdSoft(numpy.array(self.matrixList[j]-Zomega+Z), lmbda)

                tol = 0.1
                self.assertTrue(numpy.linalg.norm(Z -(U*s).dot(V.T))**2 < tol)

    def testLearnModel3(self):
        #Test using Randomised SVD

        #Test on an increasing then decreasing set of solutions
        pass

    #@unittest.skip("")
    def testPredict(self):
        #Create a set of indices
        lmbda = 0.0

        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=10)
        matrixIterator = iter(self.matrixList)
        ZList = iterativeSoftImpute.learnModel(matrixIterator)

        XhatList = iterativeSoftImpute.predict(ZList, self.indsList)

        #Check we get the exact matrices returned
        for i, Xhat in enumerate(XhatList):
            nptst.assert_array_almost_equal(numpy.array(Xhat.todense()), self.matrixList[i].todense())

            self.assertEquals(Xhat.nnz, self.indsList[i].shape[0])

        #Try moderate lambda
        lmbda = 0.1
        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=10)
        matrixIterator = iter(self.matrixList)
        ZList = list(iterativeSoftImpute.learnModel(matrixIterator))

        XhatList = iterativeSoftImpute.predict(iter(ZList), self.indsList)

        for i, Xhat in enumerate(XhatList):
            for ind in self.indsList[i]:
                U, s, V = ZList[i]
                Z = (U*s).dot(V.T)
                self.assertEquals(Xhat[numpy.unravel_index(ind, Xhat.shape)], Z[numpy.unravel_index(ind, Xhat.shape)])

            self.assertEquals(Xhat.nnz, self.indsList[i].shape[0])

    #@unittest.skip("")
    def testModelSelect(self):
        lmbda = 0.1
        shape = (20, 20)
        r = 20
        k = 50
        noise = 0.2
        X = ExpSU.SparseUtils.generateSparseLowRank(shape, r, k, noise)

        U, s, V = numpy.linalg.svd(X.todense())

        iterativeSoftImpute = IterativeSoftImpute(lmbda, k=10, svdAlg="propack", updateAlg="zero")
        lmbdas = numpy.linspace(numpy.max(s)+0.1, 0.001, 20)
        folds = 5
        cvInds = Sampling.randCrossValidation(folds, X.nnz)
        meanTestErrors = iterativeSoftImpute.modelSelect(X, lmbdas, cvInds)

        #Now do model selection manually
        (rowInds, colInds) = X.nonzero()
        trainErrors = numpy.zeros((lmbdas.shape[0], len(cvInds)))
        testErrors = numpy.zeros((lmbdas.shape[0], len(cvInds)))

        for i, lmbda in enumerate(lmbdas):
            for j, (trainInds, testInds) in enumerate(cvInds):
                trainX = scipy.sparse.csc_matrix(X.shape)
                testX = scipy.sparse.csc_matrix(X.shape)

                for p in trainInds:
                    trainX[rowInds[p], colInds[p]] = X[rowInds[p], colInds[p]]

                for p in testInds:
                    testX[rowInds[p], colInds[p]] = X[rowInds[p], colInds[p]]

                softImpute = SoftImpute(numpy.array([lmbda]))
                ZList = [softImpute.learnModel(trainX, fullMatrices=False)]

                predTrainX = softImpute.predict(ZList, trainX.nonzero())[0]
                predX = softImpute.predict(ZList, testX.nonzero())[0]

                testErrors[i, j] = MCEvaluator.meanSqError(testX, predX)
                trainErrors[i, j] = MCEvaluator.meanSqError(trainX, predTrainX)

        meanTestErrors2 = testErrors.mean(1)
        meanTrainErrors2 = trainErrors.mean(1)
        nptst.assert_array_almost_equal(meanTestErrors, meanTestErrors2, 3)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()
    <|endoftext|>


<commit_before>from nose.tools import eq_, ok_

from django.core.urlresolvers import reverse

from crashstats.crashstats.tests.test_views import BaseTestViews

class TestViews(BaseTestViews):

    def test_supersearch_home(self):
        url = reverse('documentation:supersearch_home')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        ok_('What is Super Search?' in response.content)

    def test_supersearch_examples(self):
        url = reverse('documentation:supersearch_examples')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        ok_('Examples' in response.content)

    def test_supersearch_api(self):
        url = reverse('documentation:supersearch_api')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        ok_('_results_number' in response.content)
        ok_('_aggs.*' in response.content)
        ok_('signature' in response.content)
<commit_msg>bug 1405675 - update crashstats/documentation/tests/* to pytest<commit_after>from django.core.urlresolvers import reverse

from crashstats.crashstats.tests.test_views import BaseTestViews

class TestViews(BaseTestViews):

    def test_supersearch_home(self):
        url = reverse('documentation:supersearch_home')
        response = self.client.get(url)
        assert response.status_code == 200
        assert 'What is Super Search?' in response.content

    def test_supersearch_examples(self):
        url = reverse('documentation:supersearch_examples')
        response = self.client.get(url)
        assert response.status_code == 200
        assert 'Examples' in response.content

    def test_supersearch_api(self):
        url = reverse('documentation:supersearch_api')
        response = self.client.get(url)
        assert response.status_code == 200
        assert '_results_number' in response.content
        assert '_aggs.*' in response.content
        assert 'signature' in response.content
<|endoftext|>


<commit_before>import sys
import dis
import struct
import array
import types
import functools

if sys.version_info >= (3, 6):
    _STRUCT_ARG = struct.Struct('B')

    def _has_arg(opcode):
        return True
else:
    _STRUCT_ARG = struct.Struct('<H')

    def _has_arg(opcode):
        return opcode >= dis.HAVE_ARGUMENT

def _make_code(code, codestring):
    args = [
        code.co_argcount,  code.co_nlocals,     code.co_stacksize,
        code.co_flags,     codestring,          code.co_consts,
        code.co_names,     code.co_varnames,    code.co_filename,
        code.co_name,      code.co_firstlineno, code.co_lnotab,
        code.co_freevars,  code.co_cellvars
    ]

    try:
        args.insert(1, code.co_kwonlyargcount)  # PY3
    except AttributeError:
        pass

    return types.CodeType(*args)

def _parse_instructions(code):
    extended_arg = 0
    extended_arg_offset = None
    pos = 0

    while pos < len(code):
        offset = pos
        if extended_arg_offset is not None:
            offset = extended_arg_offset

        opcode = struct.unpack_from('B', code, pos)[0]
        pos += 1

        oparg = None
        if _has_arg(opcode):
            oparg = _STRUCT_ARG.unpack_from(code, pos)[0] | extended_arg
            pos += _STRUCT_ARG.size

            if opcode == dis.EXTENDED_ARG:
                extended_arg = oparg << _STRUCT_ARG.size * 8
                extended_arg_offset = offset
                continue

        extended_arg = 0
        extended_arg_offset = None
        yield (dis.opname[opcode], oparg, offset)

def _write_instruction(buf, pos, opcode, oparg=0):
    arg_bits = _STRUCT_ARG.size * 8
    extended_arg = oparg >> arg_bits
    if extended_arg != 0:
        pos = _write_instruction(buf, pos, dis.EXTENDED_ARG, extended_arg)
        oparg &= (1 << arg_bits) - 1

    buf[pos] = opcode
    pos += 1
    if _has_arg(opcode):
        _STRUCT_ARG.pack_into(buf, pos, oparg)
        pos += _STRUCT_ARG.size

    return pos

def _find_labels_and_gotos(code):
    labels = {}
    gotos = []

    block_stack = []
    block_counter = 0

    opname1 = oparg1 = offset1 = None
    opname2 = oparg2 = offset2 = None
    opname3 = oparg3 = offset3 = None

    for opname4, oparg4, offset4 in _parse_instructions(code.co_code):
        if opname1 in ('LOAD_GLOBAL', 'LOAD_NAME'):
            if opname2 == 'LOAD_ATTR' and opname3 == 'POP_TOP':
                name = code.co_names[oparg1]
                if name == 'label':
                    labels[oparg2] = (offset1,
                                      offset4,
                                      tuple(block_stack))
                elif name == 'goto':
                    gotos.append((offset1,
                                  offset4,
                                  oparg2,
                                  tuple(block_stack)))
        elif opname1 in ('SETUP_LOOP',
                         'SETUP_EXCEPT', 'SETUP_FINALLY',
                         'SETUP_WITH', 'SETUP_ASYNC_WITH'):
            block_counter += 1
            block_stack.append(block_counter)
        elif opname1 == 'POP_BLOCK' and block_stack:
            block_stack.pop()

        opname1, oparg1, offset1 = opname2, oparg2, offset2
        opname2, oparg2, offset2 = opname3, oparg3, offset3
        opname3, oparg3, offset3 = opname4, oparg4, offset4

    return labels, gotos

def _inject_nop_sled(buf, pos, end):
    while pos < end:
        pos = _write_instruction(buf, pos, dis.opmap['NOP'])

def _patch_code(code):
    labels, gotos = _find_labels_and_gotos(code)
    buf = array.array('B', code.co_code)

    for pos, end, _ in labels.values():
        _inject_nop_sled(buf, pos, end)

    for pos, end, label, origin_stack in gotos:
        try:
            _, target, target_stack = labels[label]
        except KeyError:
            raise SyntaxError('Unknown label {0!r}'.format(code.co_names[label]))

        target_depth = len(target_stack)
        if origin_stack[:target_depth] != target_stack:
            raise SyntaxError('Jump into different block')

        failed = False
        try:
            for i in range(len(origin_stack) - target_depth):
                pos = _write_instruction(buf, pos, dis.opmap['POP_BLOCK'])
            pos = _write_instruction(buf, pos, dis.opmap['JUMP_ABSOLUTE'], target)
        except (IndexError, struct.error):
            failed = True

        if failed or pos > end:
            raise SyntaxError('Jump out of too many nested blocks')

        _inject_nop_sled(buf, pos, end)

    return _make_code(code, buf.tostring())

def with_goto(func_or_code):
    if isinstance(func_or_code, types.CodeType):
        return _patch_code(func_or_code)

    return functools.update_wrapper(
        types.FunctionType(
            _patch_code(func_or_code.__code__),
            func_or_code.__globals__,
            func_or_code.__name__,
            func_or_code.__defaults__,
            func_or_code.__closure__,
        ),
        func_or_code
    )
<commit_msg>Streamlined some function calls by changing _write_instruction() to expect the opname<commit_after>import sys
import dis
import struct
import array
import types
import functools

if sys.version_info >= (3, 6):
    _STRUCT_ARG = struct.Struct('B')

    def _has_arg(opcode):
        return True
else:
    _STRUCT_ARG = struct.Struct('<H')

    def _has_arg(opcode):
        return opcode >= dis.HAVE_ARGUMENT

def _make_code(code, codestring):
    args = [
        code.co_argcount,  code.co_nlocals,     code.co_stacksize,
        code.co_flags,     codestring,          code.co_consts,
        code.co_names,     code.co_varnames,    code.co_filename,
        code.co_name,      code.co_firstlineno, code.co_lnotab,
        code.co_freevars,  code.co_cellvars
    ]

    try:
        args.insert(1, code.co_kwonlyargcount)  # PY3
    except AttributeError:
        pass

    return types.CodeType(*args)

def _parse_instructions(code):
    extended_arg = 0
    extended_arg_offset = None
    pos = 0

    while pos < len(code):
        offset = pos
        if extended_arg_offset is not None:
            offset = extended_arg_offset

        opcode = struct.unpack_from('B', code, pos)[0]
        pos += 1

        oparg = None
        if _has_arg(opcode):
            oparg = _STRUCT_ARG.unpack_from(code, pos)[0] | extended_arg
            pos += _STRUCT_ARG.size

            if opcode == dis.EXTENDED_ARG:
                extended_arg = oparg << _STRUCT_ARG.size * 8
                extended_arg_offset = offset
                continue

        extended_arg = 0
        extended_arg_offset = None
        yield (dis.opname[opcode], oparg, offset)

def _write_instruction(buf, pos, opname, oparg=0):
    arg_bits = _STRUCT_ARG.size * 8
    extended_arg = oparg >> arg_bits
    if extended_arg != 0:
        pos = _write_instruction(buf, pos, 'EXTENDED_ARG', extended_arg)
        oparg &= (1 << arg_bits) - 1

    opcode = dis.opmap[opname]
    buf[pos] = opcode
    pos += 1

    if _has_arg(opcode):
        _STRUCT_ARG.pack_into(buf, pos, oparg)
        pos += _STRUCT_ARG.size

    return pos

def _find_labels_and_gotos(code):
    labels = {}
    gotos = []

    block_stack = []
    block_counter = 0

    opname1 = oparg1 = offset1 = None
    opname2 = oparg2 = offset2 = None
    opname3 = oparg3 = offset3 = None

    for opname4, oparg4, offset4 in _parse_instructions(code.co_code):
        if opname1 in ('LOAD_GLOBAL', 'LOAD_NAME'):
            if opname2 == 'LOAD_ATTR' and opname3 == 'POP_TOP':
                name = code.co_names[oparg1]
                if name == 'label':
                    labels[oparg2] = (offset1,
                                      offset4,
                                      tuple(block_stack))
                elif name == 'goto':
                    gotos.append((offset1,
                                  offset4,
                                  oparg2,
                                  tuple(block_stack)))
        elif opname1 in ('SETUP_LOOP',
                         'SETUP_EXCEPT', 'SETUP_FINALLY',
                         'SETUP_WITH', 'SETUP_ASYNC_WITH'):
            block_counter += 1
            block_stack.append(block_counter)
        elif opname1 == 'POP_BLOCK' and block_stack:
            block_stack.pop()

        opname1, oparg1, offset1 = opname2, oparg2, offset2
        opname2, oparg2, offset2 = opname3, oparg3, offset3
        opname3, oparg3, offset3 = opname4, oparg4, offset4

    return labels, gotos

def _inject_nop_sled(buf, pos, end):
    while pos < end:
        pos = _write_instruction(buf, pos, 'NOP')

def _patch_code(code):
    labels, gotos = _find_labels_and_gotos(code)
    buf = array.array('B', code.co_code)

    for pos, end, _ in labels.values():
        _inject_nop_sled(buf, pos, end)

    for pos, end, label, origin_stack in gotos:
        try:
            _, target, target_stack = labels[label]
        except KeyError:
            raise SyntaxError('Unknown label {0!r}'.format(code.co_names[label]))

        target_depth = len(target_stack)
        if origin_stack[:target_depth] != target_stack:
            raise SyntaxError('Jump into different block')

        failed = False
        try:
            for i in range(len(origin_stack) - target_depth):
                pos = _write_instruction(buf, pos, 'POP_BLOCK')
            pos = _write_instruction(buf, pos, 'JUMP_ABSOLUTE', target)
        except (IndexError, struct.error):
            failed = True

        if failed or pos > end:
            raise SyntaxError('Jump out of too many nested blocks')

        _inject_nop_sled(buf, pos, end)

    return _make_code(code, buf.tostring())

def with_goto(func_or_code):
    if isinstance(func_or_code, types.CodeType):
        return _patch_code(func_or_code)

    return functools.update_wrapper(
        types.FunctionType(
            _patch_code(func_or_code.__code__),
            func_or_code.__globals__,
            func_or_code.__name__,
            func_or_code.__defaults__,
            func_or_code.__closure__,
        ),
        func_or_code
    )
<|endoftext|>


<commit_before>
from ..run import get_parser

def test_get_parser():
    try:
        get_parser().parse_args(['-h'])
    except SystemExit:
        print('success')
<commit_msg>add functional test to test_run.py<commit_after>from subprocess import call
import os
from ..run import get_parser

def test_get_parser():
    try:
        get_parser().parse_args(['-h'])
    except SystemExit:
        print('success')

def test_nibs(bids_dir, atlas_file, atlas_lut, fmriprep_dir):
    bids_dir = str(bids_dir)
    out_dir = os.path.join(bids_dir, 'derivatives')
    assert call(["nibs",
                 "-a " + str(atlas_file),
                 "-l " + str(atlas_lut),
                 "-c WhiteMatter CSF",
                 "-lp 0.01",
                 bids_dir,
                 "fmriprep",
                 out_dir,
                 "participant"])
<|endoftext|>


<commit_before># -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa.  If not, see <http://www.gnu.org/licenses/>.

import hashlib
from mock import patch
from pybossa.cache import get_key_to_hash, get_hash_key, cache, memoize
from pybossa.sentinel import Sentinel
from settings_test import REDIS_SENTINEL, REDIS_KEYPREFIX

class FakeApp(object):
    def __init__(self):
        self.config = { 'REDIS_SENTINEL': REDIS_SENTINEL }

test_sentinel = Sentinel(app=FakeApp())

class TestCache(object):

    def setUp(self):
        test_sentinel.master.flushall()

    def test_00_get_key_to_hash_with_args(self):
        """Test CACHE get_key_to_hash with args works."""
        expected = ':1:a'
        key_to_hash = get_key_to_hash(1, 'a')
        err_msg = "Different key_to_hash %s != %s" % (key_to_hash, expected)
        assert key_to_hash == expected, err_msg

    def test_01_get_key_to_hash_with_kwargs(self):
        """Test CACHE get_key_to_hash with kwargs works."""
        expected = ':1:a'
        key_to_hash = get_key_to_hash(page=1, vowel='a')
        err_msg = "Different key_to_hash %s != %s" % (key_to_hash, expected)
        assert key_to_hash == expected, err_msg

    def test_02_get_key_to_hash_with_args_and_kwargs(self):
        """Test CACHE get_key_to_hash with args and kwargs works."""
        expected = ':1:a'
        key_to_hash = get_key_to_hash(1, vowel='a')
        err_msg = "Different key_to_hash %s != %s" % (key_to_hash, expected)
        assert key_to_hash == expected, err_msg

    def test_03_get_hash_key(self):
        """Test CACHE get_hash_key works."""
        prefix = 'prefix'
        key_to_hash = get_key_to_hash(1, vowel=u'ñ')
        tmp = key_to_hash.encode('utf-8')
        expected = prefix + ":" + hashlib.md5(tmp).hexdigest()
        key = get_hash_key(prefix, key_to_hash)
        err_msg = "The expected key is different %s != %s" % (expected, key)
        assert expected == key, err_msg

    @patch('pybossa.cache.sentinel', new=test_sentinel)
    def test_cache_stores_function_call_first_time_called(self):
        """Test CACHE cache decorator stores the result of calling a function
        in the cache the first time it's called"""

        @cache(key_prefix='my_cached_func')
        def my_func():
            return 'my_func was called'
        my_func()
        key = "%s::%s" % (REDIS_KEYPREFIX, 'my_cached_func')
        assert test_sentinel.master.keys() == [key], test_sentinel.master.keys()

    @patch('pybossa.cache.sentinel', new=test_sentinel)
    def test_cache_returns_expected_value(self):
        """Test CACHE cache decorator returns the expected function return value"""

        @cache(key_prefix='my_cached_func')
        def my_func():
            return 'my_func was called'
        first_call = my_func()
        second_call = my_func()

        assert first_call == 'my_func was called', first_call
        assert second_call == 'my_func was called', second_call

    @patch('pybossa.cache.sentinel', new=test_sentinel)
    def test_cache_gets_function_from_cache_second_after_first_call(self):
        """Test CACHE cache retrieves the function value from cache after it has
        been called the first time, and does not call the function but once"""

        @cache(key_prefix='my_cached_func')
        def my_func(call_count = 0):
            call_count = call_count + 1
            return call_count
        first_call = my_func()
        second_call = my_func()

        assert second_call == 1, second_call
        assert second_call is first_call, second_call
<commit_msg>Refactor: extracted test class with patch decorator<commit_after># -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa.  If not, see <http://www.gnu.org/licenses/>.

import hashlib
from mock import patch
from pybossa.cache import get_key_to_hash, get_hash_key, cache, memoize
from pybossa.sentinel import Sentinel
from settings_test import REDIS_SENTINEL, REDIS_KEYPREFIX

class TestCacheHashFunctions(object):

    def test_00_get_key_to_hash_with_args(self):
        """Test CACHE get_key_to_hash with args works."""
        expected = ':1:a'
        key_to_hash = get_key_to_hash(1, 'a')
        err_msg = "Different key_to_hash %s != %s" % (key_to_hash, expected)
        assert key_to_hash == expected, err_msg

    def test_01_get_key_to_hash_with_kwargs(self):
        """Test CACHE get_key_to_hash with kwargs works."""
        expected = ':1:a'
        key_to_hash = get_key_to_hash(page=1, vowel='a')
        err_msg = "Different key_to_hash %s != %s" % (key_to_hash, expected)
        assert key_to_hash == expected, err_msg

    def test_02_get_key_to_hash_with_args_and_kwargs(self):
        """Test CACHE get_key_to_hash with args and kwargs works."""
        expected = ':1:a'
        key_to_hash = get_key_to_hash(1, vowel='a')
        err_msg = "Different key_to_hash %s != %s" % (key_to_hash, expected)
        assert key_to_hash == expected, err_msg

    def test_03_get_hash_key(self):
        """Test CACHE get_hash_key works."""
        prefix = 'prefix'
        key_to_hash = get_key_to_hash(1, vowel=u'ñ')
        tmp = key_to_hash.encode('utf-8')
        expected = prefix + ":" + hashlib.md5(tmp).hexdigest()
        key = get_hash_key(prefix, key_to_hash)
        err_msg = "The expected key is different %s != %s" % (expected, key)
        assert expected == key, err_msg

class FakeApp(object):
    def __init__(self):
        self.config = { 'REDIS_SENTINEL': REDIS_SENTINEL }

test_sentinel = Sentinel(app=FakeApp())

@patch('pybossa.cache.sentinel', new=test_sentinel)
class TestCacheMemoizeFunctions(object):

    def setUp(self):
        test_sentinel.master.flushall()

    def test_cache_stores_function_call_first_time_called(self):
        """Test CACHE cache decorator stores the result of calling a function
        in the cache the first time it's called"""

        @cache(key_prefix='my_cached_func')
        def my_func():
            return 'my_func was called'
        my_func()
        key = "%s::%s" % (REDIS_KEYPREFIX, 'my_cached_func')

        assert test_sentinel.master.keys() == [key], test_sentinel.master.keys()

    def test_cache_gets_function_from_cache_second_after_first_call(self):
        """Test CACHE cache retrieves the function value from cache after it has
        been called the first time, and does not call the function but once"""

        @cache(key_prefix='my_cached_func')
        def my_func(call_count = 0):
            call_count = call_count + 1
            return call_count
        first_call = my_func()
        second_call = my_func()

        assert second_call == 1, second_call
        assert second_call is first_call, second_call

    def test_cache_returns_expected_value(self):
        """Test CACHE cache decorator returns the expected function return value"""

        @cache(key_prefix='my_cached_func')
        def my_func():
            return 'my_func was called'
        first_call = my_func()
        second_call = my_func()

        assert first_call == 'my_func was called', first_call
        assert second_call == 'my_func was called', second_call

    def test_memoize_stores_function_call_first_time_called(self):
        """Test CACHE memoize decorator stores the result of calling a function
        in the cache the first time it's called"""

        @memoize()
        def my_func(*args, **kwargs):
            return {'args': args, 'kwargs': kwargs}
        my_func()
        key_pattern = "%s:%s_args:*" % (REDIS_KEYPREFIX, my_func.__name__)

        assert len(test_sentinel.master.keys(key_pattern)) == 1

<|endoftext|>


<commit_before>import pyodbc
import pandas

__all__ = ['read_manages3', 'read_manages4']

def read_manages3(mdb_path):
    """
	Function to read a MANAGES 3.x database and return
	the data in a pandas DataFrame for analysis.

	Parameters
	----------
	mdb_path : str
	    The path to the MANAGES 3.x Site.mdb file.

    Returns
    -------
    DataFrame :  pandas DataFrame
        returns a pandas DataFrame.

	Examples
	--------
	>>> from enviropy.external import read_manages3
	>>> data = read_manages3('H:\INTERNAL\MANAGES_DATA\Cardinal\Cardinal\Site.mdb')

	"""

    driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
    database = mdb_path

    conxn = pyodbc.connect('DRIVER={0};DBQ={1}'.format(driver, database))

    query = """

    SELECT sample_results.lab_id, sample_results.location_id,
	sample_results.sample_date, site_parameters.param_name,
	sample_results.lt_measure, sample_results.analysis_result,
	site_parameters.default_unit
	FROM sample_results LEFT JOIN site_parameters
	ON sample_results.storet_code = site_parameters.storet_code

    """

    data = pandas.read_sql(query, conxn)

    conxn.close()

    return data

def read_manages4(server, database):
    """
	Function to read a MANAGES 4.x database and return
	the data in a pandas DataFrame for analysis.

	Parameters
	----------
	server : str
	    The name of the server.

	database : str
	    The name of the database

    Returns
    -------
    DataFrame :  pandas DataFrame
        returns a pandas DataFrame.

	Examples
	--------
	>>> from enviropy.external import read_manages4
	>>> data = read_manages4(server=server_name, database=database_name)

	"""

    driver = '{SQL Server Native Client 11.0}'

    conxn = pyodbc.connect('DRIVER={0};SERVER={1};DBQ={2};TRUSTED_CONNECTION=Yes'.format(driver, server, database))

    query = """

    SELECT site.site_id, site.name,
	sample_results.lab_id, sample_results.location_id,
	sample_results.sample_date, site_parameters.param_name,
	sample_results.lt_measure, sample_results.analysis_result,
	sample_results.detection_limit, sample_results.RL,
	sample_results.flags, site_parameters.default_unit

	FROM sample_results
	    LEFT JOIN site_parameters
	        ON sample_results.storet_code = site_parameters.storet_code AND sample_results.site_id = site_parameters.site_id
        LEFT JOIN locations
		    ON locations.site_id = sample_results.site_id AND locations.location_id = sample_results.location_id
		LEFT JOIN site
            ON site.site_id = locations.site_id
    """

    data = pandas.read_sql(query, conxn)

    conxn.close()

    return data<commit_msg>fixed bugin read_manages4 function<commit_after>import pyodbc
import pandas

__all__ = ['read_manages3', 'read_manages4']

def read_manages3(mdb_path):
    """
	Function to read a MANAGES 3.x database and return
	the data in a pandas DataFrame for analysis.

	Parameters
	----------
	mdb_path : str
	    The path to the MANAGES 3.x Site.mdb file.

    Returns
    -------
    DataFrame :  pandas DataFrame
        returns a pandas DataFrame.

	Examples
	--------
	>>> from enviropy.external import read_manages3
	>>> data = read_manages3('H:\INTERNAL\MANAGES_DATA\Cardinal\Cardinal\Site.mdb')

	"""

    driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
    database = mdb_path

    conxn = pyodbc.connect('DRIVER={0};DBQ={1}'.format(driver, database))

    query = """

    SELECT sample_results.lab_id, sample_results.location_id,
	sample_results.sample_date, site_parameters.param_name,
	sample_results.lt_measure, sample_results.analysis_result,
	site_parameters.default_unit
	FROM sample_results LEFT JOIN site_parameters
	ON sample_results.storet_code = site_parameters.storet_code

    """

    data = pandas.read_sql(query, conxn)

    conxn.close()

    return data

def read_manages4(server, database):
    """
	Function to read a MANAGES 4.x database and return
	the data in a pandas DataFrame for analysis.

	Parameters
	----------
	server : str
	    The name of the server.

	database : str
	    The name of the database

    Returns
    -------
    DataFrame :  pandas DataFrame
        returns a pandas DataFrame.

	Examples
	--------
	>>> from enviropy.external import read_manages4
	>>> data = read_manages4(server=server_name, database=database_name)

	"""

    driver = '{SQL Server Native Client 11.0}'

    conxn = pyodbc.connect('DRIVER={0};SERVER={1};DATABASE={2};TRUSTED_CONNECTION=Yes'.format(driver, server, database))

    query = """

    SELECT site.site_id, site.name,
	sample_results.lab_id, sample_results.location_id,
	sample_results.sample_date, site_parameters.param_name,
	sample_results.lt_measure, sample_results.analysis_result,
	sample_results.detection_limit, sample_results.RL,
	sample_results.flags, site_parameters.default_unit

	FROM sample_results
	    LEFT JOIN site_parameters
	        ON sample_results.storet_code = site_parameters.storet_code AND sample_results.site_id = site_parameters.site_id
            LEFT JOIN locations
		ON locations.site_id = sample_results.site_id AND locations.location_id = sample_results.location_id
	    LEFT JOIN site
                ON site.site_id = locations.site_id
    """

    data = pandas.read_sql(query, conxn)

    conxn.close()

    return data<|endoftext|>


<commit_before>"""fips verb to build the oryol samples webpage"""

import os
import yaml
import shutil
import subprocess
import glob
from string import Template

from mod import log, util, project, config
from tools import texexport

GitHubSamplesURL = 'https://github.com/floooh/oryol/tree/master/code/Samples/'

#-------------------------------------------------------------------------------
def deploy_webpage(fips_dir, proj_dir, webpage_dir) :
    """builds the final webpage under under fips-deploy/oryol-webpage"""
    ws_dir = util.get_workspace_dir(fips_dir)

    # load the websamples.yml file, should have been created during the last build
    with open(webpage_dir + '/websamples.yml', 'r') as f :
        samples = yaml.load(f.read())

    # build the thumbnail gallery
    content = ''
    for sample in samples :
        if sample['name'] != '__end__' :
            name    = sample['name']
            imgPath = sample['image']
            types   = sample['type']
            desc    = sample['desc']
            head, tail = os.path.split(imgPath)
            if tail == 'none' :
                imgFileName = 'dummy.jpg'
            else :
                imgFileName = tail
            content += '
\n'
            content += '
{}
\n'.format(name)
            content += '

\n'.format(name,imgFileName,desc)
            content += '
\n'
            content += '
\n'
            if 'emscripten' in types :
                content += '
emsc
\n'.format(name)
            if 'pnacl' in types :
                content += '
pnacl
\n'.format(name)
            if 'android' in types :
                content += '
apk
\n'.format(name)
            content += '
\n'
            content += '
\n'
            content += '
\n'

    # populate the html template, and write to the build directory
    with open(proj_dir + '/web/index.html', 'r') as f :
        templ = Template(f.read())
    html = templ.safe_substitute(samples=content)
    with open(webpage_dir + '/index.html', 'w') as f :
        f.write(html)

    # copy other required files
    for name in ['style.css', 'dummy.jpg', 'emsc.js', 'pnacl.js', 'about.html', 'favicon.png'] :
        log.info('> copy file: {}'.format(name))
        shutil.copy(proj_dir + '/web/' + name, webpage_dir + '/' + name)

    # generate emscripten HTML pages
    emsc_deploy_dir = '{}/fips-deploy/oryol/emsc-make-release'.format(ws_dir)
    for sample in samples :
        name = sample['name']
        if name != '__end__' and 'emscripten' in sample['type'] :
            log.info('> generate emscripten HTML page: {}'.format(name))
            for ext in ['js', 'html.mem'] :
                shutil.copy('{}/{}.{}'.format(emsc_deploy_dir, name, ext), webpage_dir)
            with open(proj_dir + '/web/emsc.html', 'r') as f :
                templ = Template(f.read())
            src_url = GitHubSamplesURL + sample['src'];
            html = templ.safe_substitute(name=name, source=src_url)
            with open('{}/{}.html'.format(webpage_dir, name), 'w') as f :
                f.write(html)

    # copy PNaCl HTML pages
    pnacl_deploy_dir = '{}/fips-deploy/oryol/pnacl-make-release'.format(ws_dir)
    for sample in samples :
        name = sample['name']
        if name != '__end__' and 'pnacl' in sample['type'] :
            log.info('> generate PNaCl HTML page: {}'.format(name))
            for ext in ['nmf', 'pexe'] :
                shutil.copy('{}/{}.{}'.format(pnacl_deploy_dir, name, ext), webpage_dir)
            with open(proj_dir + '/web/pnacl.html', 'r') as f :
                templ = Template(f.read())
            src_url = GitHubSamplesURL + sample['src'];
            html = templ.safe_substitute(name=name, source=src_url)
            with open('{}/{}_pnacl.html'.format(webpage_dir, name), 'w') as f :
                f.write(html)

    # copy the screenshots
    for sample in samples :
        if sample['name'] != '__end__' :
            img_path = sample['image']
            head, tail = os.path.split(img_path)
            if tail != 'none' :
                log.info('> copy screenshot: {}'.format(tail))
                shutil.copy(img_path, webpage_dir + '/' + tail)

    # copy the Android sample files over
    android_deploy_dir = '{}/fips-deploy/oryol/android-make-release'.format(ws_dir)
    for sample in samples :
        if sample['name'] != '__end__' and 'android' in sample['type'] :
            log.info('> copy android sample files: {}'.format(sample['name']))
            shutil.copy('{}/{}-debug.apk'.format(android_deploy_dir, sample['name']), webpage_dir)

#-------------------------------------------------------------------------------
def export_assets(fips_dir, proj_dir, webpage_dir) :

    tex_srcdir = proj_dir + '/data'
    tex_dstdir = webpage_dir
    texexport.configure(proj_dir, tex_srcdir, tex_dstdir)
    texexport.exportSampleTextures()
    for dataFile in glob.glob(proj_dir + '/data/nanovg/*') :
        shutil.copy(dataFile, webpage_dir)
    for dataFile in glob.glob(proj_dir + '/data/*.txt') :
        shutil.copy(dataFile, webpage_dir)

#-------------------------------------------------------------------------------
def build_deploy_webpage(fips_dir, proj_dir) :
    # if webpage dir exists, clear it first
    ws_dir = util.get_workspace_dir(fips_dir)
    webpage_dir = '{}/fips-deploy/oryol-webpage'.format(ws_dir)
    if os.path.isdir(webpage_dir) :
        shutil.rmtree(webpage_dir)
    os.makedirs(webpage_dir)

    # compile emscripten, pnacl and android samples
    project.build(fips_dir, proj_dir, 'emsc-make-release')
    project.build(fips_dir, proj_dir, 'pnacl-make-release')
    project.build(fips_dir, proj_dir, 'android-make-release')

    # export sample assets
    export_assets(fips_dir, proj_dir, webpage_dir)

    # deploy the webpage
    deploy_webpage(fips_dir, proj_dir, webpage_dir)

    log.colored(log.GREEN, 'Generated Samples web page under {}.'.format(webpage_dir))

#-------------------------------------------------------------------------------
def serve_webpage(fips_dir, proj_dir) :
    ws_dir = util.get_workspace_dir(fips_dir)
    webpage_dir = '{}/fips-deploy/oryol-webpage'.format(ws_dir)
    p = config.get_host_platform()
    if p == 'osx' :
        try :
            subprocess.call(
                    ['open http://localhost:8000 ; python {}/mod/httpserver.py'.format(fips_dir)],
                    cwd = webpage_dir, shell=True)
        except KeyboardInterrupt :
            pass
    elif p == 'win':
        log.error("FIXME: Windows not supported yet")
    elif p == 'linux':
        log.error("FIXME: Linux not supported yet")

#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
    if len(args) > 0 :
        if args[0] == 'build' :
            build_deploy_webpage(fips_dir, proj_dir)
        elif args[0] == 'serve' :
            serve_webpage(fips_dir, proj_dir)
        else :
            log.error("Invalid param '{}', expected 'build' or 'serve'".format(args[0]))
    else :
        log.error("Param 'build' or 'serve' expected")

#-------------------------------------------------------------------------------
def help() :
    log.info(log.YELLOW +
             'fips webpage build\n' +
             'fips webpage serve\n' +
             log.DEF +
             '    build oryol samples webpage')

<commit_msg>fixes for changed fips module apis<commit_after>"""fips verb to build the oryol samples webpage"""

import os
import yaml
import shutil
import subprocess
import glob
from string import Template

from mod import log, util, project
from tools import texexport

GitHubSamplesURL = 'https://github.com/floooh/oryol/tree/master/code/Samples/'

#-------------------------------------------------------------------------------
def deploy_webpage(fips_dir, proj_dir, webpage_dir) :
    """builds the final webpage under under fips-deploy/oryol-webpage"""
    ws_dir = util.get_workspace_dir(fips_dir)

    # load the websamples.yml file, should have been created during the last build
    with open(webpage_dir + '/websamples.yml', 'r') as f :
        samples = yaml.load(f.read())

    # build the thumbnail gallery
    content = ''
    for sample in samples :
        if sample['name'] != '__end__' :
            name    = sample['name']
            imgPath = sample['image']
            types   = sample['type']
            desc    = sample['desc']
            head, tail = os.path.split(imgPath)
            if tail == 'none' :
                imgFileName = 'dummy.jpg'
            else :
                imgFileName = tail
            content += '
\n'
            content += '
{}
\n'.format(name)
            content += '

\n'.format(name,imgFileName,desc)
            content += '
\n'
            content += '
\n'
            if 'emscripten' in types :
                content += '
emsc
\n'.format(name)
            if 'pnacl' in types :
                content += '
pnacl
\n'.format(name)
            if 'android' in types :
                content += '
apk
\n'.format(name)
            content += '
\n'
            content += '
\n'
            content += '
\n'

    # populate the html template, and write to the build directory
    with open(proj_dir + '/web/index.html', 'r') as f :
        templ = Template(f.read())
    html = templ.safe_substitute(samples=content)
    with open(webpage_dir + '/index.html', 'w') as f :
        f.write(html)

    # copy other required files
    for name in ['style.css', 'dummy.jpg', 'emsc.js', 'pnacl.js', 'about.html', 'favicon.png'] :
        log.info('> copy file: {}'.format(name))
        shutil.copy(proj_dir + '/web/' + name, webpage_dir + '/' + name)

    # generate emscripten HTML pages
    emsc_deploy_dir = '{}/fips-deploy/oryol/emsc-make-release'.format(ws_dir)
    for sample in samples :
        name = sample['name']
        if name != '__end__' and 'emscripten' in sample['type'] :
            log.info('> generate emscripten HTML page: {}'.format(name))
            for ext in ['js', 'html.mem'] :
                shutil.copy('{}/{}.{}'.format(emsc_deploy_dir, name, ext), webpage_dir)
            with open(proj_dir + '/web/emsc.html', 'r') as f :
                templ = Template(f.read())
            src_url = GitHubSamplesURL + sample['src'];
            html = templ.safe_substitute(name=name, source=src_url)
            with open('{}/{}.html'.format(webpage_dir, name), 'w') as f :
                f.write(html)

    # copy PNaCl HTML pages
    pnacl_deploy_dir = '{}/fips-deploy/oryol/pnacl-make-release'.format(ws_dir)
    for sample in samples :
        name = sample['name']
        if name != '__end__' and 'pnacl' in sample['type'] :
            log.info('> generate PNaCl HTML page: {}'.format(name))
            for ext in ['nmf', 'pexe'] :
                shutil.copy('{}/{}.{}'.format(pnacl_deploy_dir, name, ext), webpage_dir)
            with open(proj_dir + '/web/pnacl.html', 'r') as f :
                templ = Template(f.read())
            src_url = GitHubSamplesURL + sample['src'];
            html = templ.safe_substitute(name=name, source=src_url)
            with open('{}/{}_pnacl.html'.format(webpage_dir, name), 'w') as f :
                f.write(html)

    # copy the screenshots
    for sample in samples :
        if sample['name'] != '__end__' :
            img_path = sample['image']
            head, tail = os.path.split(img_path)
            if tail != 'none' :
                log.info('> copy screenshot: {}'.format(tail))
                shutil.copy(img_path, webpage_dir + '/' + tail)

    # copy the Android sample files over
    android_deploy_dir = '{}/fips-deploy/oryol/android-make-release'.format(ws_dir)
    for sample in samples :
        if sample['name'] != '__end__' and 'android' in sample['type'] :
            log.info('> copy android sample files: {}'.format(sample['name']))
            shutil.copy('{}/{}-debug.apk'.format(android_deploy_dir, sample['name']), webpage_dir)

#-------------------------------------------------------------------------------
def export_assets(fips_dir, proj_dir, webpage_dir) :

    tex_srcdir = proj_dir + '/data'
    tex_dstdir = webpage_dir
    texexport.configure(proj_dir, tex_srcdir, tex_dstdir)
    texexport.exportSampleTextures()
    for dataFile in glob.glob(proj_dir + '/data/nanovg/*') :
        shutil.copy(dataFile, webpage_dir)
    for dataFile in glob.glob(proj_dir + '/data/*.txt') :
        shutil.copy(dataFile, webpage_dir)

#-------------------------------------------------------------------------------
def build_deploy_webpage(fips_dir, proj_dir) :
    # if webpage dir exists, clear it first
    ws_dir = util.get_workspace_dir(fips_dir)
    webpage_dir = '{}/fips-deploy/oryol-webpage'.format(ws_dir)
    if os.path.isdir(webpage_dir) :
        shutil.rmtree(webpage_dir)
    os.makedirs(webpage_dir)

    # compile emscripten, pnacl and android samples
    project.build(fips_dir, proj_dir, 'emsc-make-release')
    project.build(fips_dir, proj_dir, 'pnacl-make-release')
    project.build(fips_dir, proj_dir, 'android-make-release')

    # export sample assets
    export_assets(fips_dir, proj_dir, webpage_dir)

    # deploy the webpage
    deploy_webpage(fips_dir, proj_dir, webpage_dir)

    log.colored(log.GREEN, 'Generated Samples web page under {}.'.format(webpage_dir))

#-------------------------------------------------------------------------------
def serve_webpage(fips_dir, proj_dir) :
    ws_dir = util.get_workspace_dir(fips_dir)
    webpage_dir = '{}/fips-deploy/oryol-webpage'.format(ws_dir)
    p = util.get_host_platform()
    if p == 'osx' :
        try :
            subprocess.call(
                    ['open http://localhost:8000 ; python {}/mod/httpserver.py'.format(fips_dir)],
                    cwd = webpage_dir, shell=True)
        except KeyboardInterrupt :
            pass
    elif p == 'win':
        log.error("FIXME: Windows not supported yet")
    elif p == 'linux':
        log.error("FIXME: Linux not supported yet")

#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
    if len(args) > 0 :
        if args[0] == 'build' :
            build_deploy_webpage(fips_dir, proj_dir)
        elif args[0] == 'serve' :
            serve_webpage(fips_dir, proj_dir)
        else :
            log.error("Invalid param '{}', expected 'build' or 'serve'".format(args[0]))
    else :
        log.error("Param 'build' or 'serve' expected")

#-------------------------------------------------------------------------------
def help() :
    log.info(log.YELLOW +
             'fips webpage build\n' +
             'fips webpage serve\n' +
             log.DEF +
             '    build oryol samples webpage')

<|endoftext|>


<commit_before>import glob
import os
import logging

from lettuce import *
from splinter import Browser
from django.core.management import call_command

from django.template.defaultfilters import slugify

@before.each_scenario
def flush_database(step):
    call_command('flush', interactive=False)

@before.all
def clear_screen_shots():
    screen_shots = glob.glob('./screenshots/*.png')
    for screen_shot in screen_shots:
        os.remove(screen_shot)
    open_browser()

def open_browser():
    logging.warning("about to open browser")
    world.browser = Browser("phantomjs")
    world.browser.driver.set_window_size(1024, 720)

@after.each_scenario
def take_screen_shot(scenario):
    if scenario.failed:
        world.browser.driver.save_screenshot('screenshots/%s.png' % slugify(scenario.name))

@before.outline
def cleanup(args, *kwargs):
    call_command('flush', interactive=False)

@after.outline
def take_screen_shot(args, *kwargs):
    key = kwargs[1].keys()[0]
    if kwargs[-1] != []:
        world.browser.driver.save_screenshot('screenshots/%s.png' % slugify(kwargs[1][key]))

@after.each_scenario
def clear_cookies(scenario):
    world.browser.driver.delete_all_cookies()

@after.all
def close_browser(total):
    world.browser.quit()

@after.all
def tear_down(step):
    os.system('rm *.pdf')
    os.system("rm -rf media/user_uploads/*")
<commit_msg>added some logging before clearing screenshots<commit_after>import glob
import os
import logging

from lettuce import *
from splinter import Browser
from django.core.management import call_command

from django.template.defaultfilters import slugify

@before.each_scenario
def flush_database(step):
    call_command('flush', interactive=False)

@before.all
def clear_screen_shots():
    logging.warning("about to clear screenshots")
    screen_shots = glob.glob('./screenshots/*.png')
    for screen_shot in screen_shots:
        os.remove(screen_shot)
    open_browser()

def open_browser():
    logging.warning("about to open browser")
    world.browser = Browser("phantomjs")
    world.browser.driver.set_window_size(1024, 720)

@after.each_scenario
def take_screen_shot(scenario):
    if scenario.failed:
        world.browser.driver.save_screenshot('screenshots/%s.png' % slugify(scenario.name))

@before.outline
def cleanup(args, *kwargs):
    call_command('flush', interactive=False)

@after.outline
def take_screen_shot(args, *kwargs):
    key = kwargs[1].keys()[0]
    if kwargs[-1] != []:
        world.browser.driver.save_screenshot('screenshots/%s.png' % slugify(kwargs[1][key]))

@after.each_scenario
def clear_cookies(scenario):
    world.browser.driver.delete_all_cookies()

@after.all
def close_browser(total):
    world.browser.quit()

@after.all
def tear_down(step):
    os.system('rm *.pdf')
    os.system("rm -rf media/user_uploads/*")
<|endoftext|>