repo_name stringlengths 5 100 | path stringlengths 4 375 | copies stringclasses 991 values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15 values |
|---|---|---|---|---|---|
miipl-naveen/optibizz | addons/l10n_be_intrastat/__openerp__.py | 257 | 1631 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (C) 2014-2015 Odoo S.A. <http://www.odoo.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Belgian Intrastat Declaration',
'version': '1.0',
'category': 'Reporting',
'description': """
Generates Intrastat XML report for declaration
Based on invoices.
""",
'author': 'Odoo SA',
'depends': ['report_intrastat', 'sale_stock', 'account_accountant', 'l10n_be'],
'data': [
'data/regions.xml',
'data/report.intrastat.code.csv',
'data/transaction.codes.xml',
'data/transport.modes.xml',
'security/groups.xml',
'security/ir.model.access.csv',
'l10n_be_intrastat.xml',
'wizard/l10n_be_intrastat_xml_view.xml',
],
'installable': True,
}
| agpl-3.0 |
tectronics/smap-data | python/smap/formatters.py | 6 | 4969 | """
Copyright (c) 2011, 2012, Regents of the University of California
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
"""
"""
@author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
"""
import re
import zlib
from zope.interface import implements
from twisted.internet.task import cooperate
from twisted.web import iweb
from smap import schema
from smap.sjson import AsyncJSON, dumps
from smap.util import push_metadata, join_path, split_path
from smap.contrib import dtutil
# from smap.core import SmapException
class AsyncFormatter(object):
"""Boilerplate for an async producer"""
implements(iweb.IBodyProducer)
content_encoding = None
def __init__(self, value):
self._value = value
self.length = iweb.UNKNOWN_LENGTH
def startProducing(self, consumer):
self._consumer = consumer
self._task = cooperate(self._produce())
d = self._task.whenDone()
d.addBoth(self._unregister)
return d
def pauseProducing(self):
self._task.pause()
def resumeProducing(self):
self._task.resume()
def stopProducing(self):
self._task.stop()
def _unregister(self, passthrough):
return passthrough
class StaticProducer(AsyncFormatter):
BLKSZ = 1024
def _produce(self):
for i in xrange(0, len(self._value), self.BLKSZ):
self._consumer.write(self._value[i:i+self.BLKSZ])
yield None
class GzipJson(StaticProducer):
content_type = 'application/json'
content_encoding = 'gzip'
def __init__(self, value):
value = dumps(value)
self._value = zlib.compress(value)
print "%i -> %i" % (len(value), len(self._value))
self.length = len(self._value)
class GzipAvro(StaticProducer):
content_type = 'avro/binary'
content_encoding = 'gzip'
def __init__(self, value):
json = dumps(value)
avro = schema.dump_report(value)
self._value = zlib.compress(avro)
print "json: %i gzip-json: %i avro: %i gzip-avro: %i" % (
len(json), len(zlib.compress(json)), len(avro), len(self._value))
self.length = len(self._value)
class AsyncSmapToCsv(AsyncFormatter):
"""Convert a sMAP report to a simplified CSV format for dumb clients"""
content_type = 'text/csv'
@staticmethod
def _format_point(path, uid, val):
return ','.join([uid, path, str(int(val[0] / 1000)), str(val[1])])
def _produce(self):
for path, val in self._value.iteritems():
if not 'uuid' in val: continue
self._consumer.write('\n'.join((AsyncSmapToCsv._format_point(path,
str(val['uuid']),
p)
for p in val['Readings'])))
yield None
__FORMATTERS__ = {
'json': AsyncJSON,
'gzip-json': GzipJson,
'gzip-avro': GzipAvro,
'csv': AsyncSmapToCsv,
}
def get_formatter(format):
return __FORMATTERS__[format]
def load_csv(data):
"""Load csv data from a string into an approximate sMAP object"""
obj = {}
for line in re.split("(\r?\n)|$", data):
parts = line.split(',')
if len(parts) != 4:
raise Exception("Invalid CSV line: " + line)
uid, path, ts, val = parts
if not path in obj:
obj[path] = {'uuid': uid}
if obj[path]['uuid'] != uid:
raise Exception("Multiple uuids with the same path: " + path)
if not 'Readings' in obj[path]:
obj[path]['Readings'] = []
obj[path]['Readings'].append([int(ts) * 1000, float(val)])
return obj
| bsd-2-clause |
mpoquet/execo | src/execo_g5k/planning.py | 1 | 49114 | # Copyright 2009-2016 INRIA Rhone-Alpes, Service Experimentation et
# Developpement
#
# This file is part of Execo.
#
# Execo is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Execo is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Execo. If not, see <http://www.gnu.org/licenses/>
"""Module provides functions to help you to plan your experiment on Grid'5000.
"""
from .charter import g5k_charter_time, get_next_charter_period
from copy import deepcopy
from datetime import timedelta
from execo import logger, Host
from execo.log import style
from execo.time_utils import timedelta_to_seconds, get_seconds, \
unixts_to_datetime, get_unixts, format_date
from execo_g5k import OarSubmission, get_current_oar_jobs, get_oar_job_info, \
get_current_oargrid_jobs, get_oargrid_job_oar_jobs
from execo_g5k.api_utils import get_g5k_sites, get_g5k_clusters, \
get_cluster_site, get_site_clusters, get_resource_attributes, get_host_cluster, \
get_host_site, get_host_attributes, get_g5k_hosts, get_host_shortname, \
get_host_longname
from execo_g5k.config import g5k_configuration
from execo_g5k.utils import G5kAutoPortForwarder
from itertools import cycle
from math import ceil, floor
from operator import itemgetter
from pprint import pformat
from threading import Thread, currentThread
from time import time
from traceback import format_exc
try:
import matplotlib.pyplot as PLT
import matplotlib.dates as MD
except ImportError:
pass
try:
import psycopg2
_retrieve_method = 'PostgreSQL'
except:
_retrieve_method = 'API'
def get_job_by_name(job_name, sites=None):
""" """
logger.detail('Looking for a job named %s', style.emph(job_name))
if not sites:
sites = get_g5k_sites()
oargrid_jobs = get_current_oargrid_jobs()
if len(oargrid_jobs) > 0:
for g_job in oargrid_jobs:
for job in get_oargrid_job_oar_jobs(g_job):
info = get_oar_job_info(job[0], job[1])
if info['name'] == job_name:
logger.info('Oargridjob %s found !', style.emph(g_job))
return g_job, None
running_jobs = get_current_oar_jobs(sites)
for job in running_jobs:
info = get_oar_job_info(job[0], job[1])
if info['name'] == job_name:
logger.info('Job %s found on site %s !', style.emph(job[0]),
style.host(job[1]))
return job
return None, None
def get_planning(elements=['grid5000'], vlan=False, subnet=False, storage=False,
out_of_chart=False, starttime=None, endtime=None,
ignore_besteffort=True, queues='default'):
"""Retrieve the planning of the elements (site, cluster) and others resources.
Element planning structure is ``{'busy': [(123456,123457), ... ], 'free': [(123457,123460), ... ]}.``
:param elements: a list of Grid'5000 elements ('grid5000', <site>, <cluster>)
:param vlan: a boolean to ask for KaVLAN computation
:param subnet: a boolean to ask for subnets computation
:param storage: a boolean to ask for sorage computation
:param out_of_chart: if True, consider that days outside weekends are busy
:param starttime: start of time period for which to compute the planning, defaults to now + 1 minute
:param endtime: end of time period for which to compute the planning, defaults to 4 weeks from now
:param ignore_besteffort: True by default, to consider the resources with besteffort jobs as available
:param queues: list of oar queues for which to get the planning
Return a dict whose keys are sites, whose values are dict whose keys
are cluster, subnets, kavlan or storage,
whose values are planning dicts, whose keys are hosts, subnet address range,
vlan number or chunk id planning respectively.
"""
if not starttime: starttime = int(time() + timedelta_to_seconds(timedelta(minutes = 1)))
starttime = int(get_unixts(starttime))
if not endtime: endtime = int(starttime + timedelta_to_seconds(timedelta(weeks = 4, minutes = 1)))
endtime = int(get_unixts(endtime))
if 'grid5000' in elements:
sites = elements = get_g5k_sites()
else:
sites = list(set([site for site in elements
if site in get_g5k_sites()] +
[get_cluster_site(cluster) for cluster in elements
if cluster in get_g5k_clusters(queues=queues)] +
[get_host_site(host) for host in elements
if host in get_g5k_hosts()
or get_host_shortname(host) in get_g5k_hosts()]))
if len(sites) == 0:
logger.error('Wrong elements given: %s' % (elements,))
return None
planning = {}
for site in sites:
planning[site] = {}
for cluster in get_site_clusters(site, queues=queues):
planning[site][cluster] = {}
for site in sites:
if vlan:
planning[site].update({'vlans': {}})
if subnet:
planning[site].update({'subnets': {}})
if storage:
planning[site].update({'storage': {}})
if _retrieve_method == 'API':
_get_planning_API(planning, ignore_besteffort)
elif _retrieve_method == 'PostgreSQL':
_get_planning_PGSQL(planning, ignore_besteffort)
if out_of_chart:
_add_charter_to_planning(planning, starttime, endtime)
for site_pl in planning.values():
for res_pl in site_pl.values():
for el_planning in res_pl.values():
el_planning['busy'].sort()
_merge_el_planning(el_planning['busy'])
_trunc_el_planning(el_planning['busy'], starttime, endtime)
_fill_el_planning_free(el_planning, starttime, endtime)
# cleaning
real_planning = deepcopy(planning)
for site, site_pl in planning.items():
for cl, cl_pl in site_pl.items():
if cl in ['vlans']:
continue
keep_cluster = False
for h in cl_pl:
if not (get_host_site(h) in elements or
get_host_cluster(h) in elements or
get_host_shortname(h) in elements or
h in elements):
del real_planning[site][cl][h]
else:
keep_cluster = True
if not keep_cluster:
del real_planning[site][cl]
return real_planning
def compute_slots(planning, walltime, excluded_elements=None):
"""Compute the slots limits and find the number of available nodes for
each elements and for the given walltime.
Return the list of slots where a slot is ``[ start, stop, freehosts ]`` and
freehosts is a dict of Grid'5000 element with number of nodes available
``{'grid5000': 40, 'lyon': 20, 'reims': 10, 'stremi': 10 }``.
WARNING: slots does not includes subnets
:param planning: a dict of the resources planning, returned by ``get_planning``
:param walltime: a duration in a format supported by get_seconds where the resources
are available
:param excluded_elements: list of elements that will not be included in the slots
computation
"""
slots = []
walltime = get_seconds(walltime)
if excluded_elements is not None:
_remove_excluded(planning, excluded_elements)
limits = _slots_limits(planning)
# Checking if we need to compile vlans planning
kavlan = False
kavlan_global = False
if len(planning) > 0:
if 'vlans' in next(iter(planning.values())):
if len(planning) > 1:
kavlan_global = True
else:
kavlan = True
for limit in limits:
log = ''
free_elements = {'grid5000': 0}
if kavlan_global:
free_vlans_global = []
for site, site_planning in planning.items():
free_elements[site] = 0
for cluster, cluster_planning in site_planning.items():
if cluster in get_g5k_clusters(queues=None):
free_elements[cluster] = 0
for host, host_planning in cluster_planning.items():
host_free = False
for free_slot in host_planning['free']:
if free_slot[0] <= limit and free_slot[1] >= limit + walltime:
host_free = True
if host_free:
free_elements['grid5000'] += 1
free_elements[site] += 1
free_elements[cluster] += 1
log += ', ' + host
if kavlan:
free_vlans = 0
for vlan, vlan_planning in site_planning['vlans'].items():
if int(vlan.split('-')[1]) < 10:
kavlan_free = False
for free_slot in vlan_planning['free']:
if free_slot[0] <= limit and free_slot[1] >= limit + walltime:
kavlan_free = True
if kavlan_free:
free_vlans += 1
free_elements['kavlan'] = free_vlans
elif kavlan_global:
for vlan, vlan_planning in site_planning['vlans'].items():
if int(vlan.split('-')[1]) > 10:
kavlan_global_free = False
for free_slot in vlan_planning['free']:
if free_slot[0] <= limit and free_slot[1] >= limit + walltime:
kavlan_global_free = True
if kavlan_global_free:
free_vlans_global.append(site)
free_elements['kavlan'] = free_vlans_global
## MISSING OTHER RESOURCES COMPUTATION
logger.debug(log)
slots.append([limit, limit + walltime, free_elements])
slots.sort(key=itemgetter(0))
return slots
def max_resources(planning):
""" """
resources = {"grid5000": 0}
for site, site_pl in planning.items():
resources[site] = 0
for cl, cl_pl in site_pl.items():
if cl in ['vlans']:
continue
resources[cl] = 0
keep_cluster = False
for h in cl_pl:
resources["grid5000"] += 1
resources[cl] += 1
resources[site] +=1
return resources
def compute_coorm_slots(planning, excluded_elements=None):
""" """
slots = []
limits = _slots_limits(planning)
for start in limits:
stop = 10 ** 25
free_cores = {'grid5000': 0}
for site, site_planning in planning.items():
free_cores[site] = 0
for cluster, cluster_planning in site_planning.items():
free_cores[cluster] = 0
if cluster in get_g5k_clusters(queues=None):
for host, host_planning in cluster_planning.items():
for free_slot in host_planning['free']:
if free_slot[0] <= start and free_slot[0] < stop:
free_cores[cluster] += get_host_attributes(host)['architecture']['nb_cores']
free_cores[site] += get_host_attributes(host)['architecture']['nb_cores']
free_cores['grid5000'] += get_host_attributes(host)['architecture']['nb_cores']
if free_slot[1] < stop:
stop = free_slot[1]
slots.append((start, stop, free_cores))
return slots
def find_first_slot(slots, resources_wanted):
""" Return the first slot (a tuple start date, end date, resources) where some resources are available
:param slots: list of slots returned by ``compute_slots``
:param resources_wanted: a dict of elements that must have some free hosts
"""
for slot in slots:
vlan_free = True
if 'kavlan' in resources_wanted:
if isinstance(slot[2]['kavlan'], int):
if slot[2]['kavlan'] == 0:
vlan_free = False
elif isinstance(slot[2]['kavlan'], list):
if len(slot[2]['kavlan']) == 0:
vlan_free = False
res_nodes = sum([nodes for element, nodes in slot[2].items()
if element in resources_wanted and element != 'kavlan'])
if res_nodes > 0 and vlan_free:
return slot
return None, None, None
def find_max_slot(slots, resources_wanted):
"""Return the slot (a tuple start date, end date, resources) with the maximum nodes available for the given elements
:param slots: list of slots returned by ``compute_slots``
:param resources_wanted: a dict of elements that must be maximized"""
max_nodes = 0
max_slot = None, None, None
for slot in slots:
vlan_free = True
if 'kavlan' in resources_wanted:
if isinstance(slot[2]['kavlan'], int):
if slot[2]['kavlan'] == 0:
vlan_free = False
elif isinstance(slot[2]['kavlan'], list):
if len(slot[2]['kavlan']) == 0:
vlan_free = False
res_nodes = sum([nodes for element, nodes in slot[2].items()
if element in resources_wanted and element != 'kavlan'])
if res_nodes > max_nodes and vlan_free:
max_nodes = res_nodes
max_slot = slot
return max_slot
def find_free_slot(slots, resources_wanted):
"""Return the first slot (a tuple start date, end date, resources) with enough resources
:param slots: list of slots returned by ``compute_slots``
:param resources_wanted: a dict describing the wanted ressources
``{'grid5000': 50, 'lyon': 20, 'stremi': 10 }``"""
# We need to add the clusters nodes to the total nodes of a site
real_wanted = resources_wanted.copy()
for cluster, n_nodes in resources_wanted.items():
if cluster in get_g5k_clusters(queues=None):
site = get_cluster_site(cluster)
if site in resources_wanted:
real_wanted[site] += n_nodes
for slot in slots:
vlan_free = True
if 'kavlan' in resources_wanted:
if isinstance(slot[2]['kavlan'], int):
if slot[2]['kavlan'] == 0:
vlan_free = False
elif isinstance(slot[2]['kavlan'], list):
if len(slot[2]['kavlan']) == 0:
vlan_free = False
slot_ok = True
for element, n_nodes in slot[2].items():
if element in real_wanted and real_wanted[element] > n_nodes \
and real_wanted != 'kavlan':
slot_ok = False
if slot_ok and vlan_free:
if 'kavlan' in resources_wanted:
resources_wanted['kavlan'] = slot[2]['kavlan']
return slot
return None, None, None
def find_coorm_slot(slots, resources_wanted):
""" """
for start, stop, res in slots:
logger.debug("%s %s %s" % (format_date(start), format_date(stop), res))
slot_ok = True
for element, cpu in resources_wanted.items():
logger.debug("%s %s" % (element, cpu))
if res[element] < cpu * (stop - start) / 3600:
slot_ok = False
if slot_ok:
return start, stop, res
def get_hosts_jobs(hosts, walltime, out_of_chart=False):
"""Find the first slot when the hosts are available and return a
list of jobs_specs
:param hosts: list of hosts
:param walltime: duration of reservation
"""
hosts = [x.address if isinstance(x, Host) else x for x in hosts]
planning = get_planning(elements=hosts, out_of_chart=out_of_chart)
limits = _slots_limits(planning)
walltime = get_seconds(walltime)
for limit in limits:
all_host_free = True
for site_planning in planning.values():
for cluster, cluster_planning in site_planning.items():
if cluster in get_g5k_clusters(queues=None):
for host_planning in cluster_planning.values():
host_free = False
for free_slot in host_planning['free']:
if free_slot[0] <= limit and free_slot[1] >= limit + walltime:
host_free = True
if not host_free:
all_host_free = False
if all_host_free:
startdate = limit
break
jobs_specs = []
for site in planning:
site_hosts = [ get_host_longname(h) for h in hosts if get_host_site(h) == site ]
sub_res = "{host in ('" + "','".join(site_hosts) + "')}/nodes=" + str(len(site_hosts))
jobs_specs.append((OarSubmission(resources=sub_res,
reservation_date=startdate), site))
return jobs_specs
def show_resources(resources, msg='Resources', max_resources=None, queues='default'):
"""Print the resources in a fancy way"""
if not max_resources:
max_resources = {}
total_hosts = 0
log = style.log_header(msg) + '\n'
for site in get_g5k_sites():
site_added = False
if site in resources:
log += style.log_header(site).ljust(20) + ' ' + str(resources[site])
if site in max_resources:
log += '/' + str(max_resources[site])
log += ' '
site_added = True
for cluster in get_site_clusters(site, queues=queues):
if len(list(set(get_site_clusters(site)) & set(resources.keys()))) > 0 \
and not site_added:
log += style.log_header(site).ljust(20)
if site in max_resources:
log += '/' + str(max_resources[site])
log += ' '
site_added = True
if cluster in resources:
log += style.emph(cluster) + ': ' + str(resources[cluster])
if cluster in max_resources:
log += '/' + str(max_resources[cluster])
log += ' '
total_hosts += resources[cluster]
if site_added:
log += '\n'
if 'grid5000' in resources:
log += style.log_header('Grid5000').ljust(20) + str(resources['grid5000'])
if "grid5000" in max_resources:
log += '/' + str(max_resources["grid5000"])
elif total_hosts > 0:
log += style.log_header('Total ').ljust(20) + str(total_hosts)
logger.info(log)
def get_jobs_specs(resources, excluded_elements=None, name=None):
""" Generate the several job specifications from the dict of resources and
the blacklisted elements
:param resources: a dict, whose keys are Grid'5000 element and values the
corresponding number of n_nodes
:param excluded_elements: a list of elements that won't be used
:param name: the name of the jobs that will be given
"""
jobs_specs = []
if excluded_elements == None:
excluded_elements = []
# Creating the list of sites used
sites = []
real_resources = resources.copy()
for resource in resources:
if resource in get_g5k_sites() and resource not in sites:
sites.append(resource)
if resource in get_g5k_clusters(queues=None):
if resource not in excluded_elements:
site = get_cluster_site(resource)
if site not in sites:
sites.append(site)
if site not in real_resources:
real_resources[site] = 0
# Checking if we need a Kavlan, a KaVLAN global or none
get_kavlan = 'kavlan' in resources
if get_kavlan:
kavlan = 'kavlan'
n_sites = 0
for resource in real_resources:
if resource in sites:
n_sites += 1
if n_sites > 1:
kavlan += '-global'
break
blacklisted_hosts = {}
for element in excluded_elements:
if element not in get_g5k_clusters(queues=None) + get_g5k_sites():
site = get_host_site(element)
if not 'site' in blacklisted_hosts:
blacklisted_hosts[site] = [element]
else:
blacklisted_hosts[site].append(element)
for site in sites:
sub_resources = ''
# Adding a KaVLAN if needed
if get_kavlan:
if not 'global' in kavlan:
sub_resources = "{type='" + kavlan + "'}/vlan=1+"
get_kavlan = False
elif site in resources['kavlan']:
sub_resources = "{type='" + kavlan + "'}/vlan=1+"
get_kavlan = False
base_sql = '{'
end_sql = '}/'
# Creating blacklist SQL string for hosts
host_blacklist = False
str_hosts = ''
if site in blacklisted_hosts and len(blacklisted_hosts[site]) > 0:
str_hosts = ''.join(["host not in ('" + get_host_longname(host) + "') and "
for host in blacklisted_hosts[site]])
host_blacklist = True
#Adding the clusters blacklist
str_clusters = str_hosts if host_blacklist else ''
cl_blacklist = False
clusters_nodes = 0
for cluster in get_site_clusters(site, queues=None):
if cluster in resources and resources[cluster] > 0:
if str_hosts == '':
sub_resources += "{cluster='" + cluster + "'}"
else:
sub_resources += base_sql + str_hosts + "cluster='" + \
cluster + "'" + end_sql
sub_resources += "/nodes=" + str(resources[cluster]) + '+'
clusters_nodes += resources[cluster]
if cluster in excluded_elements:
str_clusters += "cluster not in ('" + cluster + "') and "
cl_blacklist = True
# Generating the site blacklist string from host and cluster blacklist
str_site = ''
if host_blacklist or cl_blacklist:
str_site += base_sql
if not cl_blacklist:
str_site += str_hosts[:-4]
else:
str_site += str_clusters[:-4]
str_site = str_site + end_sql
if real_resources[site] > 0:
sub_resources += str_site + "nodes=" + str(real_resources[site]) +\
'+'
if sub_resources != '':
jobs_specs.append((OarSubmission(resources=sub_resources[:-1],
name=name), site))
return jobs_specs
def distribute_hosts(resources_available, resources_wanted,
excluded_elements=None, ratio=None):
""" Distribute the resources on the different sites and cluster
:param resources_available: a dict defining the resources available
:param resources_wanted: a dict defining the resources available you really want
:param excluded_elements: a list of elements that won't be used
:param ratio: if not None (the default), a float between 0 and 1,
to actually only use a fraction of the resources."""
if excluded_elements == None: excluded_elements = []
resources = {}
#Defining the cluster you want
clusters_wanted = {}
for element, n_nodes in resources_wanted.items():
if element in get_g5k_clusters(queues=None):
clusters_wanted[element] = n_nodes
for cluster, n_nodes in clusters_wanted.items():
nodes = n_nodes if n_nodes > 0 else resources_available[cluster]
resources_available[get_cluster_site(cluster)] -= nodes
resources[cluster] = nodes
# Blacklisting clusters
for element in excluded_elements:
if element in get_g5k_clusters(queues=None) and element in resources_available:
resources_available['grid5000'] -= resources_available[element]
resources_available[get_cluster_site(element)] -= resources_available[element]
resources_available[element] = 0
#Defining the sites you want
sites_wanted = {}
for element, n_nodes in resources_wanted.items():
if element in get_g5k_sites() and element not in excluded_elements:
sites_wanted[element] = n_nodes
for site, n_nodes in sites_wanted.items():
resources[site] = n_nodes if n_nodes > 0 else resources_available[site]
# Blacklisting sites
for element in excluded_elements:
if element in get_g5k_sites() and element in resources_available:
resources_available['grid5000'] -= resources_available[element]
resources_available[element] = 0
#Distributing hosts on grid5000 elements
logger.debug(pformat(resources_wanted))
if 'grid5000' in resources_wanted:
g5k_nodes = resources_wanted['grid5000'] if resources_wanted['grid5000'] > 0 else resources_available['grid5000']
total_nodes = 0
sites = [element for element in resources_available if element in get_g5k_sites() ]
iter_sites = cycle(sites)
while total_nodes < g5k_nodes:
site = next(iter_sites)
if resources_available[site] == 0:
sites.remove(site)
iter_sites = cycle(sites)
else:
resources_available[site] -= 1
if site in resources:
resources[site] += 1
else:
resources[site] = 1
total_nodes += 1
logger.debug(pformat(resources))
if 'kavlan' in resources_wanted:
resources['kavlan'] = resources_available['kavlan']
# apply optional ratio
if ratio != None:
resources.update((x, int(floor(y * ratio))) for x, y in resources.items())
return resources
def _fix_job(start_time, end_time):
return int(start_time), int(end_time) + 120
def _get_vlans_API(site):
"""Retrieve the list of VLAN of a site from the 3.0 Grid'5000 API"""
equips = get_resource_attributes('/sites/'+site+'/network_equipments/')
vlans = []
for equip in equips['items']:
if 'vlans' in equip and len(equip['vlans']) >2:
for params in equip['vlans'].values():
if type( params ) == type({}) and 'name' in params \
and int(params['name'].split('-')[1])>3:
# > 3 because vlans 1, 2, 3 are not routed
vlans.append(params['name'])
return vlans
def _get_job_link_attr_API(p):
try:
currentThread().attr = get_resource_attributes(p)
except Exception as e:
currentThread().broken = True
currentThread().ex = e
def _get_site_planning_API(site, site_planning, ignore_besteffort):
try:
alive_nodes = set([str(node['network_address'])
for node in get_resource_attributes('/sites/'+site+'/internal/oarapi/resources/details.json?limit=2^30')['items']
if node['type'] == 'default' and node['state'] != 'Dead' and node['maintenance'] != 'YES'])
for host in alive_nodes:
host_cluster = get_host_cluster(str(host))
if host_cluster in site_planning:
site_planning[host_cluster].update({host: {'busy': [], 'free': []}})
if 'vlans' in site_planning:
site_planning['vlans'] = {}
for vlan in _get_vlans_API(site):
site_planning['vlans'][vlan] = {'busy': [], 'free': []}
# STORAGE AND SUBNETS MISSING
# Retrieving jobs
site_jobs = get_resource_attributes('/sites/'+site+'/jobs?limit=1073741824&state=waiting,launching,running')['items']
jobs_links = [ link['href'] for job in site_jobs for link in job['links'] \
if link['rel'] == 'self' and (ignore_besteffort == False or job['queue'] != 'besteffort') ]
threads = []
for link in jobs_links:
t = Thread(target = _get_job_link_attr_API, args = ('/'+str(link).split('/', 2)[2], ))
t.broken = False
t.attr = None
t.ex = None
threads.append(t)
t.start()
for t in threads:
t.join()
if t.broken:
raise t.ex
attr = t.attr
try:
start_time = attr['started_at'] if attr['started_at'] != 0 else attr['scheduled_at']
end_time = start_time + attr['walltime']
except:
continue
start_time, end_time = _fix_job(start_time, end_time)
nodes = attr['assigned_nodes']
for node in nodes:
cluster = node.split('.',1)[0].split('-')[0]
if cluster in site_planning and node in site_planning[cluster]:
site_planning[cluster][node]['busy'].append( (start_time, end_time))
if 'vlans' in site_planning and 'vlans' in attr['resources_by_type'] \
and int(attr['resources_by_type']['vlans'][0]) > 3:
kavname ='kavlan-'+str(attr['resources_by_type']['vlans'][0])
site_planning['vlans'][kavname]['busy'].append( (start_time, end_time))
if 'subnets' in site_planning and 'subnets' in attr['resources_by_type']:
for subnet in attr['resources_by_type']['subnets']:
if subnet not in site_planning['subnets']:
site_planning['subnets'][subnet] = {'busy': [], 'free': []}
site_planning['subnets'][subnet]['busy'].append( (start_time, end_time))
# STORAGE IS MISSING
except Exception as e:
logger.warn('error connecting to oar database / getting planning from ' + site)
logger.detail("exception:\n" + format_exc())
currentThread().broken = True
def _get_planning_API(planning, ignore_besteffort):
"""Retrieve the planning using the 3.0 Grid'5000 API """
broken_sites = []
threads = {}
for site in planning:
t = Thread(target = _get_site_planning_API, args = (site, planning[site], ignore_besteffort))
threads[site] = t
t.broken = False
t.start()
for site, t in threads.items():
t.join()
if t.broken:
broken_sites.append(site)
# Removing sites not reachable
for site in broken_sites:
del planning[site]
def _get_site_planning_PGSQL(site, site_planning, ignore_besteffort):
try:
with G5kAutoPortForwarder(site,
'oardb.' + site + '.grid5000.fr',
g5k_configuration['oar_pgsql_ro_port']) as (host, port):
conn = psycopg2.connect(host=host, port=port,
user=g5k_configuration['oar_pgsql_ro_user'],
password=g5k_configuration['oar_pgsql_ro_password'],
database=g5k_configuration['oar_pgsql_ro_db']
)
try:
cur = conn.cursor()
# Retrieving alive resources
sql = """SELECT DISTINCT R.type, R.network_address, R.vlan, R.subnet_address
FROM resources R
WHERE state <> 'Dead' AND R.maintenance <> 'YES';"""
cur.execute(sql)
for data in cur.fetchall():
if data[0] == "default":
cluster = get_host_cluster(data[1])
if cluster in site_planning:
site_planning[cluster][data[1]] = {'busy': [],
'free': []}
if data[0] in ['kavlan', 'kavlan-global'] \
and 'vlans' in site_planning:
site_planning['vlans']['kavlan-' + data[2]] = {'busy': [],
'free': []}
if data[0] == "subnet" and 'subnet' in site_planning:
site_planning['subnets'][data[3]] = {'busy': [],
'free': []}
sql = ("""SELECT J.job_id, J.state, GJP.start_time AS start_time,
GJP.start_time+MJD.moldable_walltime,
array_agg(DISTINCT R.network_address) AS hosts,
array_agg(DISTINCT R.vlan) AS vlan,
array_agg(DISTINCT R.subnet_address) AS subnets
FROM jobs J
LEFT JOIN moldable_job_descriptions MJD
ON MJD.moldable_job_id=J.job_id
LEFT JOIN gantt_jobs_predictions GJP
ON GJP.moldable_job_id=MJD.moldable_id
INNER JOIN gantt_jobs_resources AR
ON AR.moldable_job_id=MJD.moldable_id
LEFT JOIN resources R
ON AR.resource_id=R.resource_id
WHERE ( J.state='Launching' OR J.state='Running' OR J.state='Waiting')
""" +
(""" AND queue_name<>'besteffort'""" if ignore_besteffort else """""") +
"""GROUP BY J.job_id, GJP.start_time, MJD.moldable_walltime
ORDER BY J.start_time""")
# CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(R.network_address,'.',1),'-',-1), SIGNED)"""
cur.execute(sql)
for job in cur.fetchall():
start_time = job[2]
end_time = job[3]
start_time, end_time = _fix_job(start_time, end_time)
if len(job[4]) > 0:
for host in job[4]:
if host != '':
cluster = get_host_cluster(host)
if cluster in site_planning:
if host in site_planning[cluster]:
site_planning[cluster][host]['busy'].append((start_time, end_time))
if job[5][0] and 'vlans' in site_planning:
for vlan in job[5]:
if isinstance(vlan, str) and int(vlan) > 3:
# only routed vlan
site_planning['vlans']['kavlan-' + vlan]['busy'].append((start_time, end_time))
if len(job[6]) > 0 and 'subnet' in site_planning:
for subnet in job[6]:
site_planning['subnets'][subnet]['busy'].append((start_time, end_time))
finally:
conn.close()
except Exception as e:
logger.warn('error connecting to oar database / getting planning from ' + site)
logger.detail("exception:\n" + format_exc())
currentThread().broken = True
def _get_planning_PGSQL(planning, ignore_besteffort):
"""Retrieve the planning using the oar2 database"""
broken_sites = []
threads = {}
for site in planning:
t = Thread(target = _get_site_planning_PGSQL, args = (site, planning[site], ignore_besteffort))
threads[site] = t
t.broken = False
t.start()
for site, t in threads.items():
t.join()
if t.broken:
broken_sites.append(site)
# Removing sites not reachable
for site in broken_sites:
del planning[site]
def _remove_excluded(planning, excluded_resources):
"""This function remove elements from planning"""
# first removing the site
for element in excluded_resources:
if element in get_g5k_sites() and element in planning:
del planning[element]
# then removing specific clusters
for site_pl in planning.values():
for res in list(site_pl):
if res in excluded_resources:
del site_pl[res]
continue
for element in list(site_pl[res]):
if element in excluded_resources:
del site_pl[res][element]
def _merge_el_planning(el_planning):
"""An internal function to merge the busy or free planning of an element"""
if len(el_planning) > 1:
for i in range(len(el_planning)):
j = i+1
if j == len(el_planning)-1:
break
while True:
condition = el_planning[i][1] >= el_planning[j][0]
if condition:
if el_planning[j][1] > el_planning[i][1]:
el_planning[i]=(el_planning[i][0], el_planning[j][1])
el_planning.pop(j)
if j == len(el_planning) - 1:
break
else:
break
if j == len(el_planning) - 1:
break
def _trunc_el_planning(el_planning, starttime, endtime):
"""Modify (start, stop) tuple that are not within the (starttime, endtime) interval """
if len(el_planning) > 0:
el_planning.sort()
# Truncating jobs that end before starttime
i = 0
while True:
if i == len(el_planning):
break
start, stop = el_planning[i]
if stop < starttime or start > endtime:
el_planning.remove( (start, stop ))
else:
if start < starttime:
if stop < endtime:
el_planning.remove( (start, stop ) )
el_planning.append( (starttime, stop) )
else:
el_planning.remove( (start, stop ) )
el_planning.append( (starttime, endtime) )
elif stop > endtime:
el_planning.remove( (start, stop ) )
el_planning.append( (start, endtime) )
else:
i += 1
if i == len(el_planning):
break
el_planning.sort()
def _fill_el_planning_free(el_planning, starttime, endtime):
"""An internal function to compute the planning free of all elements"""
if len(el_planning['busy']) > 0:
if el_planning['busy'][0][0] > starttime:
el_planning['free'].append((starttime, el_planning['busy'][0][0]))
for i in range(0, len(el_planning['busy'])-1):
el_planning['free'].append((el_planning['busy'][i][1], el_planning['busy'][i+1][0]))
if el_planning['busy'][len(el_planning['busy'])-1][1] < endtime:
el_planning['free'].append((el_planning['busy'][len(el_planning['busy'])-1][1], endtime))
else:
el_planning['free'].append((starttime, endtime))
def _slots_limits(planning):
"""Return the limits of slots, defined by a resource state change."""
limits = set()
for site in planning.values():
for res_pl in site.values():
for el_planning in res_pl.values():
for start, stop in el_planning['busy']:
limits.add(start)
limits.add(stop)
for start, stop in el_planning['free']:
limits.add(start)
limits.add(stop)
limits = sorted(limits)
if len(limits) > 0:
limits.pop()
return limits
def _add_charter_to_planning(planning, starttime, endtime):
charter_el_planning = get_charter_el_planning(starttime, endtime)
for site in planning.values():
for res_pl in site.values():
for el_planning in res_pl.values():
el_planning['busy'] += charter_el_planning
el_planning['busy'].sort()
def get_charter_el_planning(start_time, end_time):
"""Returns the list of tuples (start, end) of g5k charter time periods between start_time and end_time.
:param start_time: a date in one of the types supported by
`execo.time_utils.get_unixts`
:param end_time: a date in one of the types supported by
`execo.time_utils.get_unixts`
"""
start_time = unixts_to_datetime(get_unixts(start_time))
end_time = unixts_to_datetime(get_unixts(end_time))
el_planning = []
while True:
charter_start, charter_end = get_next_charter_period(start_time, end_time)
if charter_start == None: break
el_planning.append((int(charter_start), int(charter_end)))
start_time = charter_end
return el_planning
"""Functions to draw the Gantt chart, the slots available, and other plots """
def _set_colors():
colors = {}
colors['busy'] = '#666666'
rgb_colors = [(x[0]/255., x[1]/255., x[2]/255.) for x in \
[(255., 122., 122.), (255., 204., 122.), (255., 255., 122.), (255., 246., 153.), (204., 255., 122.),
(122., 255., 122.), (122., 255., 255.), (122., 204., 255.), (204., 188., 255.), (255., 188., 255.)]]
i_site = 0
for site in sorted(get_g5k_sites()):
colors[site] = rgb_colors[i_site]
i_cluster = 0
for cluster in sorted(get_site_clusters(site, queues=None)):
min_index = colors[site].index(min(colors[site]))
color = [0., 0., 0.]
for i in range(3):
color[i] = min(colors[site][i], 1.)
if i == min_index:
color[i] += i_cluster * 0.12
colors[cluster] = tuple(color)
i_cluster += 1
i_site += 1
return colors
def draw_gantt(planning, colors = None, show = False, save = True, outfile = None):
""" Draw the hosts planning for the elements you ask (requires Matplotlib)
:param planning: the dict of elements planning
:param colors: a dict to define element coloring ``{'element': (255., 122., 122.)}``
:param show: display the Gantt diagram
:param save: save the Gantt diagram to outfile
:param outfile: specify the output file"""
if colors is None:
colors = _set_colors()
n_sites = len(planning)
startstamp = None
endstamp = None
for clusters_hosts in planning.values():
for hosts_kinds in clusters_hosts.values():
for kinds_slots in hosts_kinds.values():
for slots in kinds_slots.values():
for slot in slots:
if startstamp == None or slot[0] < startstamp:
startstamp = slot[0]
if endstamp == None or slot[1] > endstamp:
endstamp = slot[1]
if startstamp and endstamp: break
if startstamp and endstamp: break
for slot in slots:
if slot[0] < startstamp:
startstamp = slot[0]
if slot[1] > endstamp:
endstamp = slot[1]
if outfile is None:
outfile = 'gantt_' + "_".join([site for site in planning]) \
+ '_' + format_date(startstamp)
logger.info('Saving Gantt chart to %s', style.emph(outfile))
n_col = 2 if n_sites > 1 else 1
n_row = int(ceil(float(n_sites) / float(n_col)))
x_major_locator = MD.AutoDateLocator()
xfmt = MD.DateFormatter('%d %b, %H:%M ')
PLT.ioff()
fig = PLT.figure(figsize=(15, 5 * n_row), dpi=80)
i_site = 1
for site, clusters in planning.items():
n_hosts = 0
for hosts in clusters.values():
n_hosts += len(hosts)
if n_hosts == 0: continue
ax = fig.add_subplot(n_row, n_col, i_site, title=site.title())
ax.title.set_fontsize(18)
ax.xaxis_date()
ax.set_xlim(unixts_to_datetime(startstamp), unixts_to_datetime(endstamp))
ax.xaxis.set_major_formatter(xfmt)
ax.xaxis.set_major_locator(x_major_locator)
ax.xaxis.grid(color='black', linestyle='dashed')
PLT.xticks(rotation=15)
ax.set_ylim(0, 1)
ax.get_yaxis().set_ticks([])
ax.yaxis.label.set_fontsize(16)
pos = 0.0
inc = 1.0 / n_hosts
ylabel = ''
for cluster, hosts in clusters.items():
ylabel += cluster + ' '
i_host = 0
for key in sorted(list(hosts), key = lambda name: (name.split('.',1)[0].split('-')[0],
int( name.split('.',1)[0].split('-')[1] ))):
slots = hosts[key]
i_host +=1
cl_colors = {'free': colors[cluster], 'busy': colors['busy']}
for kind in cl_colors:
for freeslot in slots[kind]:
edate, bdate = [MD.date2num(item) for item in
(unixts_to_datetime(freeslot[1]), unixts_to_datetime(freeslot[0]))]
ax.barh(pos, edate - bdate , 1, left = bdate,
color = cl_colors[kind], edgecolor = 'none' )
pos += inc
if i_host == len(hosts):
ax.axhline(y = pos, color = cl_colors['busy'], linestyle ='-', linewidth = 1)
ax.set_ylabel(ylabel)
i_site += 1
fig.tight_layout()
if show:
PLT.show()
if save:
logger.debug('Saving file %s ...', outfile)
PLT.savefig (outfile, dpi=300)
def draw_slots(slots, colors=None, show=False, save=True, outfile=None):
"""Draw the number of nodes available for the clusters (requires Matplotlib >= 1.2.0)
:param slots: a list of slot, as returned by ``compute_slots``
:param colors: a dict to define element coloring ``{'element': (255., 122., 122.)}``
:param show: display the slots versus time
:param save: save the plot to outfile
:param outfile: specify the output file"""
startstamp = slots[0][0]
endstamp = slots[-1][1]
if outfile is None:
outfile = 'slots_' + format_date(startstamp)
logger.info('Saving slots diagram to %s', style.emph(outfile))
if colors is None:
colors = _set_colors()
xfmt = MD.DateFormatter('%d %b, %H:%M ')
if endstamp - startstamp <= timedelta_to_seconds(timedelta(days=7)):
x_major_locator = MD.HourLocator(byhour=[9, 19])
elif endstamp - startstamp <= timedelta_to_seconds(timedelta(days=17)):
x_major_locator = MD.HourLocator(byhour=[9])
else:
x_major_locator = MD.AutoDateLocator()
max_nodes = {}
total_nodes = 0
slot_limits = []
total_list = []
i_slot = 0
for slot in slots:
slot_limits.append(slot[0])
if i_slot + 1 < len(slots):
slot_limits.append(slots[i_slot + 1][0])
i_slot += 1
for element, n_nodes in slot[2].items():
if element in get_g5k_clusters(queues=None):
if not element in max_nodes:
max_nodes[element] = []
max_nodes[element].append(n_nodes)
max_nodes[element].append(n_nodes)
if element == 'grid5000':
total_list.append(n_nodes)
total_list.append(n_nodes)
if n_nodes > total_nodes:
total_nodes = n_nodes
slot_limits.append(endstamp)
slot_limits.sort()
dates = [unixts_to_datetime(ts) for ts in slot_limits]
datenums = MD.date2num(dates)
fig = PLT.figure(figsize=(15,10), dpi=80)
ax = PLT.subplot(111)
ax.xaxis_date()
box = ax.get_position()
ax.set_position([box.x0-0.07, box.y0, box.width, box.height])
ax.set_xlim(unixts_to_datetime(startstamp), unixts_to_datetime(endstamp))
ax.set_xlabel('Time')
ax.set_ylabel('Nodes available')
ax.set_ylim(0, total_nodes*1.1)
ax.axhline(y = total_nodes, color = '#000000', linestyle ='-', linewidth = 2, label = 'ABSOLUTE MAXIMUM')
ax.yaxis.grid(color='gray', linestyle='dashed')
ax.xaxis.set_major_formatter(xfmt)
ax.xaxis.set_major_locator(x_major_locator )
PLT.xticks(rotation = 15)
max_nodes_list = []
p_legend = []
p_rects = []
p_colors = []
for key, value in sorted(max_nodes.items()):
if key != 'grid5000':
max_nodes_list.append(value)
p_legend.append(key)
p_rects.append(PLT.Rectangle((0, 0), 1, 1, fc = colors[key]))
p_colors.append(colors[key])
plots = PLT.stackplot(datenums, max_nodes_list, colors = p_colors)
PLT.legend(p_rects, p_legend, loc='center right', ncol = 1, shadow = True, bbox_to_anchor=(1.2, 0.5))
if show:
PLT.show()
if save:
logger.debug('Saving file %s ...', outfile)
PLT.savefig (outfile, dpi=300)
| gpl-3.0 |
jeanlinux/calibre | src/calibre/ebooks/conversion/plugins/pdf_input.py | 21 | 2745 | # -*- coding: utf-8 -*-
__license__ = 'GPL 3'
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import os
from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
class PDFInput(InputFormatPlugin):
name = 'PDF Input'
author = 'Kovid Goyal and John Schember'
description = 'Convert PDF files to HTML'
file_types = set(['pdf'])
options = set([
OptionRecommendation(name='no_images', recommended_value=False,
help=_('Do not extract images from the document')),
OptionRecommendation(name='unwrap_factor', recommended_value=0.45,
help=_('Scale used to determine the length at which a line should '
'be unwrapped. Valid values are a decimal between 0 and 1. The '
'default is 0.45, just below the median line length.')),
OptionRecommendation(name='new_pdf_engine', recommended_value=False,
help=_('Use the new PDF conversion engine.'))
])
def convert_new(self, stream, accelerators):
from calibre.ebooks.pdf.pdftohtml import pdftohtml
from calibre.utils.cleantext import clean_ascii_chars
from calibre.ebooks.pdf.reflow import PDFDocument
pdftohtml(os.getcwdu(), stream.name, self.opts.no_images, as_xml=True)
with open(u'index.xml', 'rb') as f:
xml = clean_ascii_chars(f.read())
PDFDocument(xml, self.opts, self.log)
return os.path.join(os.getcwdu(), u'metadata.opf')
def convert(self, stream, options, file_ext, log,
accelerators):
from calibre.ebooks.metadata.opf2 import OPFCreator
from calibre.ebooks.pdf.pdftohtml import pdftohtml
log.debug('Converting file to html...')
# The main html file will be named index.html
self.opts, self.log = options, log
if options.new_pdf_engine:
return self.convert_new(stream, accelerators)
pdftohtml(os.getcwdu(), stream.name, options.no_images)
from calibre.ebooks.metadata.meta import get_metadata
log.debug('Retrieving document metadata...')
mi = get_metadata(stream, 'pdf')
opf = OPFCreator(os.getcwdu(), mi)
manifest = [(u'index.html', None)]
images = os.listdir(os.getcwdu())
images.remove('index.html')
for i in images:
manifest.append((i, None))
log.debug('Generating manifest...')
opf.create_manifest(manifest)
opf.create_spine([u'index.html'])
log.debug('Rendering manifest...')
with open(u'metadata.opf', 'wb') as opffile:
opf.render(opffile)
return os.path.join(os.getcwdu(), u'metadata.opf')
| gpl-3.0 |
ivannaranjo/google-api-dotnet-client | ClientGenerator/src/googleapis/codegen/filesys/files_test.py | 11 | 1188 | #!/usr/bin/python2.7
import os
import shutil
import tempfile
from google.apputils import basetest
from googleapis.codegen.filesys import files
class FilesTest(basetest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp()
for name in 'abc':
open(os.path.join(self.tempdir, name), 'w').write(name)
def tearDown(self):
shutil.rmtree(self.tempdir)
def testGetFileContentsLocal(self):
filename = os.path.join(self.tempdir, 'a')
contents = files.GetFileContents(filename)
self.assertEquals('a', contents)
def testIterFilesLocal(self):
listing = sorted(files.IterFiles(self.tempdir))
expected = [os.path.join(self.tempdir, x) for x in 'abc']
self.assertEquals(expected, listing)
def testIsFileLocal(self):
self.assertTrue(files.IsFile(os.path.join(self.tempdir, 'a')))
self.assertFalse(files.IsFile(self.tempdir))
def testParseGsPath(self):
path = '/gs/moo-goo-gai-pan/bismarck/marx/leopold.zip'
spec = files.ParseGsPath(path)
self.assertIsNotNone(spec)
expected = ('moo-goo-gai-pan', 'bismarck/marx/leopold.zip')
self.assertEquals(expected, spec)
if __name__ == '__main__':
basetest.main()
| apache-2.0 |
sarvex/tensorflow | tensorflow/lite/experimental/mlir/testing/op_tests/rfft2d.py | 6 | 2235 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Test configs for rfft2d."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from tensorflow.lite.testing.zip_test_utils import create_tensor_data
from tensorflow.lite.testing.zip_test_utils import ExtraTocoOptions
from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests
from tensorflow.lite.testing.zip_test_utils import register_make_test_function
@register_make_test_function()
def make_rfft2d_tests(options):
"""Make a set of tests to do rfft2d."""
test_parameters = [{
"input_dtype": [tf.float32],
"input_shape": [[8, 8], [3, 8, 8], [3, 1, 16]],
"fft_length": [
None, [4, 4], [4, 8], [8, 4], [8, 8], [8, 16], [16, 8], [16, 16],
[1, 8], [1, 16]
]
}]
def build_graph(parameters):
input_value = tf.compat.v1.placeholder(
dtype=parameters["input_dtype"],
name="input",
shape=parameters["input_shape"])
outs = tf.signal.rfft2d(input_value, fft_length=parameters["fft_length"])
return [input_value], [outs]
def build_inputs(parameters, sess, inputs, outputs):
input_value = create_tensor_data(parameters["input_dtype"],
parameters["input_shape"])
return [input_value], sess.run(
outputs, feed_dict=dict(zip(inputs, [input_value])))
extra_toco_options = ExtraTocoOptions()
make_zip_of_tests(options, test_parameters, build_graph, build_inputs,
extra_toco_options)
| apache-2.0 |
shiora/The-Perfect-Pokemon-Team-Balancer | libs/env/Lib/site-packages/pip/_vendor/distlib/locators.py | 166 | 46553 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2013 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import gzip
from io import BytesIO
import json
import logging
import os
import posixpath
import re
try:
import threading
except ImportError:
import dummy_threading as threading
import zlib
from . import DistlibException
from .compat import (urljoin, urlparse, urlunparse, url2pathname, pathname2url,
queue, quote, unescape, string_types, build_opener,
HTTPRedirectHandler as BaseRedirectHandler,
Request, HTTPError, URLError)
from .database import Distribution, DistributionPath, make_dist
from .metadata import Metadata
from .util import (cached_property, parse_credentials, ensure_slash,
split_filename, get_project_data, parse_requirement,
parse_name_and_version, ServerProxy)
from .version import get_scheme, UnsupportedVersionError
from .wheel import Wheel, is_compatible
logger = logging.getLogger(__name__)
HASHER_HASH = re.compile('^(\w+)=([a-f0-9]+)')
CHARSET = re.compile(r';\s*charset\s*=\s*(.*)\s*$', re.I)
HTML_CONTENT_TYPE = re.compile('text/html|application/x(ht)?ml')
DEFAULT_INDEX = 'http://python.org/pypi'
def get_all_distribution_names(url=None):
"""
Return all distribution names known by an index.
:param url: The URL of the index.
:return: A list of all known distribution names.
"""
if url is None:
url = DEFAULT_INDEX
client = ServerProxy(url, timeout=3.0)
return client.list_packages()
class RedirectHandler(BaseRedirectHandler):
"""
A class to work around a bug in some Python 3.2.x releases.
"""
# There's a bug in the base version for some 3.2.x
# (e.g. 3.2.2 on Ubuntu Oneiric). If a Location header
# returns e.g. /abc, it bails because it says the scheme ''
# is bogus, when actually it should use the request's
# URL for the scheme. See Python issue #13696.
def http_error_302(self, req, fp, code, msg, headers):
# Some servers (incorrectly) return multiple Location headers
# (so probably same goes for URI). Use first header.
newurl = None
for key in ('location', 'uri'):
if key in headers:
newurl = headers[key]
break
if newurl is None:
return
urlparts = urlparse(newurl)
if urlparts.scheme == '':
newurl = urljoin(req.get_full_url(), newurl)
if hasattr(headers, 'replace_header'):
headers.replace_header(key, newurl)
else:
headers[key] = newurl
return BaseRedirectHandler.http_error_302(self, req, fp, code, msg,
headers)
http_error_301 = http_error_303 = http_error_307 = http_error_302
class Locator(object):
"""
A base class for locators - things that locate distributions.
"""
source_extensions = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz')
binary_extensions = ('.egg', '.exe', '.whl')
excluded_extensions = ('.pdf',)
# A list of tags indicating which wheels you want to match. The default
# value of None matches against the tags compatible with the running
# Python. If you want to match other values, set wheel_tags on a locator
# instance to a list of tuples (pyver, abi, arch) which you want to match.
wheel_tags = None
downloadable_extensions = source_extensions + ('.whl',)
def __init__(self, scheme='default'):
"""
Initialise an instance.
:param scheme: Because locators look for most recent versions, they
need to know the version scheme to use. This specifies
the current PEP-recommended scheme - use ``'legacy'``
if you need to support existing distributions on PyPI.
"""
self._cache = {}
self.scheme = scheme
# Because of bugs in some of the handlers on some of the platforms,
# we use our own opener rather than just using urlopen.
self.opener = build_opener(RedirectHandler())
# If get_project() is called from locate(), the matcher instance
# is set from the requirement passed to locate(). See issue #18 for
# why this can be useful to know.
self.matcher = None
def clear_cache(self):
self._cache.clear()
def _get_scheme(self):
return self._scheme
def _set_scheme(self, value):
self._scheme = value
scheme = property(_get_scheme, _set_scheme)
def _get_project(self, name):
"""
For a given project, get a dictionary mapping available versions to Distribution
instances.
This should be implemented in subclasses.
If called from a locate() request, self.matcher will be set to a
matcher for the requirement to satisfy, otherwise it will be None.
"""
raise NotImplementedError('Please implement in the subclass')
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
raise NotImplementedError('Please implement in the subclass')
def get_project(self, name):
"""
For a given project, get a dictionary mapping available versions to Distribution
instances.
This calls _get_project to do all the work, and just implements a caching layer on top.
"""
if self._cache is None:
result = self._get_project(name)
elif name in self._cache:
result = self._cache[name]
else:
result = self._get_project(name)
self._cache[name] = result
return result
def score_url(self, url):
"""
Give an url a score which can be used to choose preferred URLs
for a given project release.
"""
t = urlparse(url)
return (t.scheme != 'https', 'pypi.python.org' in t.netloc,
posixpath.basename(t.path))
def prefer_url(self, url1, url2):
"""
Choose one of two URLs where both are candidates for distribution
archives for the same version of a distribution (for example,
.tar.gz vs. zip).
The current implement favours http:// URLs over https://, archives
from PyPI over those from other locations and then the archive name.
"""
result = url2
if url1:
s1 = self.score_url(url1)
s2 = self.score_url(url2)
if s1 > s2:
result = url1
if result != url2:
logger.debug('Not replacing %r with %r', url1, url2)
else:
logger.debug('Replacing %r with %r', url1, url2)
return result
def split_filename(self, filename, project_name):
"""
Attempt to split a filename in project name, version and Python version.
"""
return split_filename(filename, project_name)
def convert_url_to_download_info(self, url, project_name):
"""
See if a URL is a candidate for a download URL for a project (the URL
has typically been scraped from an HTML page).
If it is, a dictionary is returned with keys "name", "version",
"filename" and "url"; otherwise, None is returned.
"""
def same_project(name1, name2):
name1, name2 = name1.lower(), name2.lower()
if name1 == name2:
result = True
else:
# distribute replaces '-' by '_' in project names, so it
# can tell where the version starts in a filename.
result = name1.replace('_', '-') == name2.replace('_', '-')
return result
result = None
scheme, netloc, path, params, query, frag = urlparse(url)
if frag.lower().startswith('egg='):
logger.debug('%s: version hint in fragment: %r',
project_name, frag)
m = HASHER_HASH.match(frag)
if m:
algo, digest = m.groups()
else:
algo, digest = None, None
origpath = path
if path and path[-1] == '/':
path = path[:-1]
if path.endswith('.whl'):
try:
wheel = Wheel(path)
if is_compatible(wheel, self.wheel_tags):
if project_name is None:
include = True
else:
include = same_project(wheel.name, project_name)
if include:
result = {
'name': wheel.name,
'version': wheel.version,
'filename': wheel.filename,
'url': urlunparse((scheme, netloc, origpath,
params, query, '')),
'python-version': ', '.join(
['.'.join(list(v[2:])) for v in wheel.pyver]),
}
except Exception as e:
logger.warning('invalid path for wheel: %s', path)
elif path.endswith(self.downloadable_extensions):
path = filename = posixpath.basename(path)
for ext in self.downloadable_extensions:
if path.endswith(ext):
path = path[:-len(ext)]
t = self.split_filename(path, project_name)
if not t:
logger.debug('No match for project/version: %s', path)
else:
name, version, pyver = t
if not project_name or same_project(project_name, name):
result = {
'name': name,
'version': version,
'filename': filename,
'url': urlunparse((scheme, netloc, origpath,
params, query, '')),
#'packagetype': 'sdist',
}
if pyver:
result['python-version'] = pyver
break
if result and algo:
result['%s_digest' % algo] = digest
return result
def _get_digest(self, info):
"""
Get a digest from a dictionary by looking at keys of the form
'algo_digest'.
Returns a 2-tuple (algo, digest) if found, else None. Currently
looks only for SHA256, then MD5.
"""
result = None
for algo in ('sha256', 'md5'):
key = '%s_digest' % algo
if key in info:
result = (algo, info[key])
break
return result
def _update_version_data(self, result, info):
"""
Update a result dictionary (the final result from _get_project) with a dictionary for a
specific version, whih typically holds information gleaned from a filename or URL for an
archive for the distribution.
"""
name = info.pop('name')
version = info.pop('version')
if version in result:
dist = result[version]
md = dist.metadata
else:
dist = make_dist(name, version, scheme=self.scheme)
md = dist.metadata
dist.digest = self._get_digest(info)
if md.source_url != info['url']:
md.source_url = self.prefer_url(md.source_url, info['url'])
dist.locator = self
result[version] = dist
def locate(self, requirement, prereleases=False):
"""
Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``True``, allow pre-release versions
to be located. Otherwise, pre-release versions
are not returned.
:return: A :class:`Distribution` instance, or ``None`` if no such
distribution could be located.
"""
result = None
r = parse_requirement(requirement)
if r is None:
raise DistlibException('Not a valid requirement: %r' % requirement)
scheme = get_scheme(self.scheme)
self.matcher = matcher = scheme.matcher(r.requirement)
logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__)
versions = self.get_project(r.name)
if versions:
# sometimes, versions are invalid
slist = []
vcls = matcher.version_class
for k in versions:
try:
if not matcher.match(k):
logger.debug('%s did not match %r', matcher, k)
else:
if prereleases or not vcls(k).is_prerelease:
slist.append(k)
else:
logger.debug('skipping pre-release '
'version %s of %s', k, matcher.name)
except Exception:
logger.warning('error matching %s with %r', matcher, k)
pass # slist.append(k)
if len(slist) > 1:
slist = sorted(slist, key=scheme.key)
if slist:
logger.debug('sorted list: %s', slist)
result = versions[slist[-1]]
if result and r.extras:
result.extras = r.extras
self.matcher = None
return result
class PyPIRPCLocator(Locator):
"""
This locator uses XML-RPC to locate distributions. It therefore
cannot be used with simple mirrors (that only mirror file content).
"""
def __init__(self, url, **kwargs):
"""
Initialise an instance.
:param url: The URL to use for XML-RPC.
:param kwargs: Passed to the superclass constructor.
"""
super(PyPIRPCLocator, self).__init__(**kwargs)
self.base_url = url
self.client = ServerProxy(url, timeout=3.0)
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
return set(self.client.list_packages())
def _get_project(self, name):
result = {}
versions = self.client.package_releases(name, True)
for v in versions:
urls = self.client.release_urls(name, v)
data = self.client.release_data(name, v)
metadata = Metadata(scheme=self.scheme)
metadata.name = data['name']
metadata.version = data['version']
metadata.license = data.get('license')
metadata.keywords = data.get('keywords', [])
metadata.summary = data.get('summary')
dist = Distribution(metadata)
if urls:
info = urls[0]
metadata.source_url = info['url']
dist.digest = self._get_digest(info)
dist.locator = self
result[v] = dist
return result
class PyPIJSONLocator(Locator):
"""
This locator uses PyPI's JSON interface. It's very limited in functionality
nad probably not worth using.
"""
def __init__(self, url, **kwargs):
super(PyPIJSONLocator, self).__init__(**kwargs)
self.base_url = ensure_slash(url)
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
raise NotImplementedError('Not available from this locator')
def _get_project(self, name):
result = {}
url = urljoin(self.base_url, '%s/json' % quote(name))
try:
resp = self.opener.open(url)
data = resp.read().decode() # for now
d = json.loads(data)
md = Metadata(scheme=self.scheme)
data = d['info']
md.name = data['name']
md.version = data['version']
md.license = data.get('license')
md.keywords = data.get('keywords', [])
md.summary = data.get('summary')
dist = Distribution(md)
urls = d['urls']
if urls:
info = urls[0]
md.source_url = info['url']
dist.digest = self._get_digest(info)
dist.locator = self
result[md.version] = dist
except Exception as e:
logger.exception('JSON fetch failed: %s', e)
return result
class Page(object):
"""
This class represents a scraped HTML page.
"""
# The following slightly hairy-looking regex just looks for the contents of
# an anchor link, which has an attribute "href" either immediately preceded
# or immediately followed by a "rel" attribute. The attribute values can be
# declared with double quotes, single quotes or no quotes - which leads to
# the length of the expression.
_href = re.compile("""
(rel\s*=\s*(?:"(?P<rel1>[^"]*)"|'(?P<rel2>[^']*)'|(?P<rel3>[^>\s\n]*))\s+)?
href\s*=\s*(?:"(?P<url1>[^"]*)"|'(?P<url2>[^']*)'|(?P<url3>[^>\s\n]*))
(\s+rel\s*=\s*(?:"(?P<rel4>[^"]*)"|'(?P<rel5>[^']*)'|(?P<rel6>[^>\s\n]*)))?
""", re.I | re.S | re.X)
_base = re.compile(r"""<base\s+href\s*=\s*['"]?([^'">]+)""", re.I | re.S)
def __init__(self, data, url):
"""
Initialise an instance with the Unicode page contents and the URL they
came from.
"""
self.data = data
self.base_url = self.url = url
m = self._base.search(self.data)
if m:
self.base_url = m.group(1)
_clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I)
@cached_property
def links(self):
"""
Return the URLs of all the links on a page together with information
about their "rel" attribute, for determining which ones to treat as
downloads and which ones to queue for further scraping.
"""
def clean(url):
"Tidy up an URL."
scheme, netloc, path, params, query, frag = urlparse(url)
return urlunparse((scheme, netloc, quote(path),
params, query, frag))
result = set()
for match in self._href.finditer(self.data):
d = match.groupdict('')
rel = (d['rel1'] or d['rel2'] or d['rel3'] or
d['rel4'] or d['rel5'] or d['rel6'])
url = d['url1'] or d['url2'] or d['url3']
url = urljoin(self.base_url, url)
url = unescape(url)
url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url)
result.add((url, rel))
# We sort the result, hoping to bring the most recent versions
# to the front
result = sorted(result, key=lambda t: t[0], reverse=True)
return result
class SimpleScrapingLocator(Locator):
"""
A locator which scrapes HTML pages to locate downloads for a distribution.
This runs multiple threads to do the I/O; performance is at least as good
as pip's PackageFinder, which works in an analogous fashion.
"""
# These are used to deal with various Content-Encoding schemes.
decoders = {
'deflate': zlib.decompress,
'gzip': lambda b: gzip.GzipFile(fileobj=BytesIO(d)).read(),
'none': lambda b: b,
}
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
"""
Initialise an instance.
:param url: The root URL to use for scraping.
:param timeout: The timeout, in seconds, to be applied to requests.
This defaults to ``None`` (no timeout specified).
:param num_workers: The number of worker threads you want to do I/O,
This defaults to 10.
:param kwargs: Passed to the superclass.
"""
super(SimpleScrapingLocator, self).__init__(**kwargs)
self.base_url = ensure_slash(url)
self.timeout = timeout
self._page_cache = {}
self._seen = set()
self._to_fetch = queue.Queue()
self._bad_hosts = set()
self.skip_externals = False
self.num_workers = num_workers
self._lock = threading.RLock()
def _prepare_threads(self):
"""
Threads are created only when get_project is called, and terminate
before it returns. They are there primarily to parallelise I/O (i.e.
fetching web pages).
"""
self._threads = []
for i in range(self.num_workers):
t = threading.Thread(target=self._fetch)
t.setDaemon(True)
t.start()
self._threads.append(t)
def _wait_threads(self):
"""
Tell all the threads to terminate (by sending a sentinel value) and
wait for them to do so.
"""
# Note that you need two loops, since you can't say which
# thread will get each sentinel
for t in self._threads:
self._to_fetch.put(None) # sentinel
for t in self._threads:
t.join()
self._threads = []
def _get_project(self, name):
self.result = result = {}
self.project_name = name
url = urljoin(self.base_url, '%s/' % quote(name))
self._seen.clear()
self._page_cache.clear()
self._prepare_threads()
try:
logger.debug('Queueing %s', url)
self._to_fetch.put(url)
self._to_fetch.join()
finally:
self._wait_threads()
del self.result
return result
platform_dependent = re.compile(r'\b(linux-(i\d86|x86_64|arm\w+)|'
r'win(32|-amd64)|macosx-?\d+)\b', re.I)
def _is_platform_dependent(self, url):
"""
Does an URL refer to a platform-specific download?
"""
return self.platform_dependent.search(url)
def _process_download(self, url):
"""
See if an URL is a suitable download for a project.
If it is, register information in the result dictionary (for
_get_project) about the specific version it's for.
Note that the return value isn't actually used other than as a boolean
value.
"""
if self._is_platform_dependent(url):
info = None
else:
info = self.convert_url_to_download_info(url, self.project_name)
logger.debug('process_download: %s -> %s', url, info)
if info:
with self._lock: # needed because self.result is shared
self._update_version_data(self.result, info)
return info
def _should_queue(self, link, referrer, rel):
"""
Determine whether a link URL from a referring page and with a
particular "rel" attribute should be queued for scraping.
"""
scheme, netloc, path, _, _, _ = urlparse(link)
if path.endswith(self.source_extensions + self.binary_extensions +
self.excluded_extensions):
result = False
elif self.skip_externals and not link.startswith(self.base_url):
result = False
elif not referrer.startswith(self.base_url):
result = False
elif rel not in ('homepage', 'download'):
result = False
elif scheme not in ('http', 'https', 'ftp'):
result = False
elif self._is_platform_dependent(link):
result = False
else:
host = netloc.split(':', 1)[0]
if host.lower() == 'localhost':
result = False
else:
result = True
logger.debug('should_queue: %s (%s) from %s -> %s', link, rel,
referrer, result)
return result
def _fetch(self):
"""
Get a URL to fetch from the work queue, get the HTML page, examine its
links for download candidates and candidates for further scraping.
This is a handy method to run in a thread.
"""
while True:
url = self._to_fetch.get()
try:
if url:
page = self.get_page(url)
if page is None: # e.g. after an error
continue
for link, rel in page.links:
if link not in self._seen:
self._seen.add(link)
if (not self._process_download(link) and
self._should_queue(link, url, rel)):
logger.debug('Queueing %s from %s', link, url)
self._to_fetch.put(link)
finally:
# always do this, to avoid hangs :-)
self._to_fetch.task_done()
if not url:
#logger.debug('Sentinel seen, quitting.')
break
def get_page(self, url):
"""
Get the HTML for an URL, possibly from an in-memory cache.
XXX TODO Note: this cache is never actually cleared. It's assumed that
the data won't get stale over the lifetime of a locator instance (not
necessarily true for the default_locator).
"""
# http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api
scheme, netloc, path, _, _, _ = urlparse(url)
if scheme == 'file' and os.path.isdir(url2pathname(path)):
url = urljoin(ensure_slash(url), 'index.html')
if url in self._page_cache:
result = self._page_cache[url]
logger.debug('Returning %s from cache: %s', url, result)
else:
host = netloc.split(':', 1)[0]
result = None
if host in self._bad_hosts:
logger.debug('Skipping %s due to bad host %s', url, host)
else:
req = Request(url, headers={'Accept-encoding': 'identity'})
try:
logger.debug('Fetching %s', url)
resp = self.opener.open(req, timeout=self.timeout)
logger.debug('Fetched %s', url)
headers = resp.info()
content_type = headers.get('Content-Type', '')
if HTML_CONTENT_TYPE.match(content_type):
final_url = resp.geturl()
data = resp.read()
encoding = headers.get('Content-Encoding')
if encoding:
decoder = self.decoders[encoding] # fail if not found
data = decoder(data)
encoding = 'utf-8'
m = CHARSET.search(content_type)
if m:
encoding = m.group(1)
try:
data = data.decode(encoding)
except UnicodeError:
data = data.decode('latin-1') # fallback
result = Page(data, final_url)
self._page_cache[final_url] = result
except HTTPError as e:
if e.code != 404:
logger.exception('Fetch failed: %s: %s', url, e)
except URLError as e:
logger.exception('Fetch failed: %s: %s', url, e)
with self._lock:
self._bad_hosts.add(host)
except Exception as e:
logger.exception('Fetch failed: %s: %s', url, e)
finally:
self._page_cache[url] = result # even if None (failure)
return result
_distname_re = re.compile('<a href=[^>]*>([^<]+)<')
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
page = self.get_page(self.base_url)
if not page:
raise DistlibException('Unable to get %s' % self.base_url)
for match in self._distname_re.finditer(page.data):
result.add(match.group(1))
return result
class DirectoryLocator(Locator):
"""
This class locates distributions in a directory tree.
"""
def __init__(self, path, **kwargs):
"""
Initialise an instance.
:param path: The root of the directory tree to search.
:param kwargs: Passed to the superclass constructor,
except for:
* recursive - if True (the default), subdirectories are
recursed into. If False, only the top-level directory
is searched,
"""
self.recursive = kwargs.pop('recursive', True)
super(DirectoryLocator, self).__init__(**kwargs)
path = os.path.abspath(path)
if not os.path.isdir(path):
raise DistlibException('Not a directory: %r' % path)
self.base_dir = path
def should_include(self, filename, parent):
"""
Should a filename be considered as a candidate for a distribution
archive? As well as the filename, the directory which contains it
is provided, though not used by the current implementation.
"""
return filename.endswith(self.downloadable_extensions)
def _get_project(self, name):
result = {}
for root, dirs, files in os.walk(self.base_dir):
for fn in files:
if self.should_include(fn, root):
fn = os.path.join(root, fn)
url = urlunparse(('file', '',
pathname2url(os.path.abspath(fn)),
'', '', ''))
info = self.convert_url_to_download_info(url, name)
if info:
self._update_version_data(result, info)
if not self.recursive:
break
return result
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
for root, dirs, files in os.walk(self.base_dir):
for fn in files:
if self.should_include(fn, root):
fn = os.path.join(root, fn)
url = urlunparse(('file', '',
pathname2url(os.path.abspath(fn)),
'', '', ''))
info = self.convert_url_to_download_info(url, None)
if info:
result.add(info['name'])
if not self.recursive:
break
return result
class JSONLocator(Locator):
"""
This locator uses special extended metadata (not available on PyPI) and is
the basis of performant dependency resolution in distlib. Other locators
require archive downloads before dependencies can be determined! As you
might imagine, that can be slow.
"""
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
raise NotImplementedError('Not available from this locator')
def _get_project(self, name):
result = {}
data = get_project_data(name)
if data:
for info in data.get('files', []):
if info['ptype'] != 'sdist' or info['pyversion'] != 'source':
continue
# We don't store summary in project metadata as it makes
# the data bigger for no benefit during dependency
# resolution
dist = make_dist(data['name'], info['version'],
summary=data.get('summary',
'Placeholder for summary'),
scheme=self.scheme)
md = dist.metadata
md.source_url = info['url']
# TODO SHA256 digest
if 'digest' in info and info['digest']:
dist.digest = ('md5', info['digest'])
md.dependencies = info.get('requirements', {})
dist.exports = info.get('exports', {})
result[dist.version] = dist
return result
class DistPathLocator(Locator):
"""
This locator finds installed distributions in a path. It can be useful for
adding to an :class:`AggregatingLocator`.
"""
def __init__(self, distpath, **kwargs):
"""
Initialise an instance.
:param distpath: A :class:`DistributionPath` instance to search.
"""
super(DistPathLocator, self).__init__(**kwargs)
assert isinstance(distpath, DistributionPath)
self.distpath = distpath
def _get_project(self, name):
dist = self.distpath.get_distribution(name)
if dist is None:
result = {}
else:
result = { dist.version: dist }
return result
class AggregatingLocator(Locator):
"""
This class allows you to chain and/or merge a list of locators.
"""
def __init__(self, *locators, **kwargs):
"""
Initialise an instance.
:param locators: The list of locators to search.
:param kwargs: Passed to the superclass constructor,
except for:
* merge - if False (the default), the first successful
search from any of the locators is returned. If True,
the results from all locators are merged (this can be
slow).
"""
self.merge = kwargs.pop('merge', False)
self.locators = locators
super(AggregatingLocator, self).__init__(**kwargs)
def clear_cache(self):
super(AggregatingLocator, self).clear_cache()
for locator in self.locators:
locator.clear_cache()
def _set_scheme(self, value):
self._scheme = value
for locator in self.locators:
locator.scheme = value
scheme = property(Locator.scheme.fget, _set_scheme)
def _get_project(self, name):
result = {}
for locator in self.locators:
d = locator.get_project(name)
if d:
if self.merge:
result.update(d)
else:
# See issue #18. If any dists are found and we're looking
# for specific constraints, we only return something if
# a match is found. For example, if a DirectoryLocator
# returns just foo (1.0) while we're looking for
# foo (>= 2.0), we'll pretend there was nothing there so
# that subsequent locators can be queried. Otherwise we
# would just return foo (1.0) which would then lead to a
# failure to find foo (>= 2.0), because other locators
# weren't searched. Note that this only matters when
# merge=False.
if self.matcher is None:
found = True
else:
found = False
for k in d:
if self.matcher.match(k):
found = True
break
if found:
result = d
break
return result
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
for locator in self.locators:
try:
result |= locator.get_distribution_names()
except NotImplementedError:
pass
return result
# We use a legacy scheme simply because most of the dists on PyPI use legacy
# versions which don't conform to PEP 426 / PEP 440.
default_locator = AggregatingLocator(
JSONLocator(),
SimpleScrapingLocator('https://pypi.python.org/simple/',
timeout=3.0),
scheme='legacy')
locate = default_locator.locate
NAME_VERSION_RE = re.compile(r'(?P<name>[\w-]+)\s*'
r'\(\s*(==\s*)?(?P<ver>[^)]+)\)$')
class DependencyFinder(object):
"""
Locate dependencies for distributions.
"""
def __init__(self, locator=None):
"""
Initialise an instance, using the specified locator
to locate distributions.
"""
self.locator = locator or default_locator
self.scheme = get_scheme(self.locator.scheme)
def add_distribution(self, dist):
"""
Add a distribution to the finder. This will update internal information
about who provides what.
:param dist: The distribution to add.
"""
logger.debug('adding distribution %s', dist)
name = dist.key
self.dists_by_name[name] = dist
self.dists[(name, dist.version)] = dist
for p in dist.provides:
name, version = parse_name_and_version(p)
logger.debug('Add to provided: %s, %s, %s', name, version, dist)
self.provided.setdefault(name, set()).add((version, dist))
def remove_distribution(self, dist):
"""
Remove a distribution from the finder. This will update internal
information about who provides what.
:param dist: The distribution to remove.
"""
logger.debug('removing distribution %s', dist)
name = dist.key
del self.dists_by_name[name]
del self.dists[(name, dist.version)]
for p in dist.provides:
name, version = parse_name_and_version(p)
logger.debug('Remove from provided: %s, %s, %s', name, version, dist)
s = self.provided[name]
s.remove((version, dist))
if not s:
del self.provided[name]
def get_matcher(self, reqt):
"""
Get a version matcher for a requirement.
:param reqt: The requirement
:type reqt: str
:return: A version matcher (an instance of
:class:`distlib.version.Matcher`).
"""
try:
matcher = self.scheme.matcher(reqt)
except UnsupportedVersionError:
# XXX compat-mode if cannot read the version
name = reqt.split()[0]
matcher = self.scheme.matcher(name)
return matcher
def find_providers(self, reqt):
"""
Find the distributions which can fulfill a requirement.
:param reqt: The requirement.
:type reqt: str
:return: A set of distribution which can fulfill the requirement.
"""
matcher = self.get_matcher(reqt)
name = matcher.key # case-insensitive
result = set()
provided = self.provided
if name in provided:
for version, provider in provided[name]:
try:
match = matcher.match(version)
except UnsupportedVersionError:
match = False
if match:
result.add(provider)
break
return result
def try_to_replace(self, provider, other, problems):
"""
Attempt to replace one provider with another. This is typically used
when resolving dependencies from multiple sources, e.g. A requires
(B >= 1.0) while C requires (B >= 1.1).
For successful replacement, ``provider`` must meet all the requirements
which ``other`` fulfills.
:param provider: The provider we are trying to replace with.
:param other: The provider we're trying to replace.
:param problems: If False is returned, this will contain what
problems prevented replacement. This is currently
a tuple of the literal string 'cantreplace',
``provider``, ``other`` and the set of requirements
that ``provider`` couldn't fulfill.
:return: True if we can replace ``other`` with ``provider``, else
False.
"""
rlist = self.reqts[other]
unmatched = set()
for s in rlist:
matcher = self.get_matcher(s)
if not matcher.match(provider.version):
unmatched.add(s)
if unmatched:
# can't replace other with provider
problems.add(('cantreplace', provider, other, unmatched))
result = False
else:
# can replace other with provider
self.remove_distribution(other)
del self.reqts[other]
for s in rlist:
self.reqts.setdefault(provider, set()).add(s)
self.add_distribution(provider)
result = True
return result
def find(self, requirement, meta_extras=None, prereleases=False):
"""
Find a distribution and all distributions it depends on.
:param requirement: The requirement specifying the distribution to
find, or a Distribution instance.
:param meta_extras: A list of meta extras such as :test:, :build: and
so on.
:param prereleases: If ``True``, allow pre-release versions to be
returned - otherwise, don't return prereleases
unless they're all that's available.
Return a set of :class:`Distribution` instances and a set of
problems.
The distributions returned should be such that they have the
:attr:`required` attribute set to ``True`` if they were
from the ``requirement`` passed to ``find()``, and they have the
:attr:`build_time_dependency` attribute set to ``True`` unless they
are post-installation dependencies of the ``requirement``.
The problems should be a tuple consisting of the string
``'unsatisfied'`` and the requirement which couldn't be satisfied
by any distribution known to the locator.
"""
self.provided = {}
self.dists = {}
self.dists_by_name = {}
self.reqts = {}
meta_extras = set(meta_extras or [])
if ':*:' in meta_extras:
meta_extras.remove(':*:')
# :meta: and :run: are implicitly included
meta_extras |= set([':test:', ':build:', ':dev:'])
if isinstance(requirement, Distribution):
dist = odist = requirement
logger.debug('passed %s as requirement', odist)
else:
dist = odist = self.locator.locate(requirement,
prereleases=prereleases)
if dist is None:
raise DistlibException('Unable to locate %r' % requirement)
logger.debug('located %s', odist)
dist.requested = True
problems = set()
todo = set([dist])
install_dists = set([odist])
while todo:
dist = todo.pop()
name = dist.key # case-insensitive
if name not in self.dists_by_name:
self.add_distribution(dist)
else:
#import pdb; pdb.set_trace()
other = self.dists_by_name[name]
if other != dist:
self.try_to_replace(dist, other, problems)
ireqts = dist.run_requires | dist.meta_requires
sreqts = dist.build_requires
ereqts = set()
if dist in install_dists:
for key in ('test', 'build', 'dev'):
e = ':%s:' % key
if e in meta_extras:
ereqts |= getattr(dist, '%s_requires' % key)
all_reqts = ireqts | sreqts | ereqts
for r in all_reqts:
providers = self.find_providers(r)
if not providers:
logger.debug('No providers found for %r', r)
provider = self.locator.locate(r, prereleases=prereleases)
# If no provider is found and we didn't consider
# prereleases, consider them now.
if provider is None and not prereleases:
provider = self.locator.locate(r, prereleases=True)
if provider is None:
logger.debug('Cannot satisfy %r', r)
problems.add(('unsatisfied', r))
else:
n, v = provider.key, provider.version
if (n, v) not in self.dists:
todo.add(provider)
providers.add(provider)
if r in ireqts and dist in install_dists:
install_dists.add(provider)
logger.debug('Adding %s to install_dists',
provider.name_and_version)
for p in providers:
name = p.key
if name not in self.dists_by_name:
self.reqts.setdefault(p, set()).add(r)
else:
other = self.dists_by_name[name]
if other != p:
# see if other can be replaced by p
self.try_to_replace(p, other, problems)
dists = set(self.dists.values())
for dist in dists:
dist.build_time_dependency = dist not in install_dists
if dist.build_time_dependency:
logger.debug('%s is a build-time dependency only.',
dist.name_and_version)
logger.debug('find done for %s', odist)
return dists, problems
| gpl-2.0 |
t0mk/ansible | lib/ansible/modules/identity/ipa/ipa_group.py | 20 | 9697 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: ipa_group
author: Thomas Krahn (@Nosmoht)
short_description: Manage FreeIPA group
description:
- Add, modify and delete group within IPA server
options:
cn:
description:
- Canonical name.
- Can not be changed as it is the unique identifier.
required: true
aliases: ['name']
external:
description:
- Allow adding external non-IPA members from trusted domains.
required: false
gidnumber:
description:
- GID (use this option to set it manually).
required: false
group:
description:
- List of group names assigned to this group.
- If an empty list is passed all groups will be removed from this group.
- If option is omitted assigned groups will not be checked or changed.
- Groups that are already assigned but not passed will be removed.
nonposix:
description:
- Create as a non-POSIX group.
required: false
user:
description:
- List of user names assigned to this group.
- If an empty list is passed all users will be removed from this group.
- If option is omitted assigned users will not be checked or changed.
- Users that are already assigned but not passed will be removed.
state:
description:
- State to ensure
required: false
default: "present"
choices: ["present", "absent"]
ipa_port:
description: Port of IPA server
required: false
default: 443
ipa_host:
description: IP or hostname of IPA server
required: false
default: "ipa.example.com"
ipa_user:
description: Administrative account used on IPA server
required: false
default: "admin"
ipa_pass:
description: Password of administrative user
required: true
ipa_prot:
description: Protocol used by IPA server
required: false
default: "https"
choices: ["http", "https"]
validate_certs:
description:
- This only applies if C(ipa_prot) is I(https).
- If set to C(no), the SSL certificates will not be validated.
- This should only set to C(no) used on personally controlled sites using self-signed certificates.
required: false
default: true
version_added: "2.3"
'''
EXAMPLES = '''
# Ensure group is present
- ipa_group:
name: oinstall
gidnumber: 54321
state: present
ipa_host: ipa.example.com
ipa_user: admin
ipa_pass: topsecret
# Ensure that groups sysops and appops are assigned to ops but no other group
- ipa_group:
name: ops
group:
- sysops
- appops
ipa_host: ipa.example.com
ipa_user: admin
ipa_pass: topsecret
# Ensure that users linus and larry are assign to the group, but no other user
- ipa_group:
name: sysops
user:
- linus
- larry
ipa_host: ipa.example.com
ipa_user: admin
ipa_pass: topsecret
# Ensure group is absent
- ipa_group:
name: sysops
state: absent
ipa_host: ipa.example.com
ipa_user: admin
ipa_pass: topsecret
'''
RETURN = '''
group:
description: Group as returned by IPA API
returned: always
type: dict
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.ipa import IPAClient
class GroupIPAClient(IPAClient):
def __init__(self, module, host, port, protocol):
super(GroupIPAClient, self).__init__(module, host, port, protocol)
def group_find(self, name):
return self._post_json(method='group_find', name=None, item={'all': True, 'cn': name})
def group_add(self, name, item):
return self._post_json(method='group_add', name=name, item=item)
def group_mod(self, name, item):
return self._post_json(method='group_mod', name=name, item=item)
def group_del(self, name):
return self._post_json(method='group_del', name=name)
def group_add_member(self, name, item):
return self._post_json(method='group_add_member', name=name, item=item)
def group_add_member_group(self, name, item):
return self.group_add_member(name=name, item={'group': item})
def group_add_member_user(self, name, item):
return self.group_add_member(name=name, item={'user': item})
def group_remove_member(self, name, item):
return self._post_json(method='group_remove_member', name=name, item=item)
def group_remove_member_group(self, name, item):
return self.group_remove_member(name=name, item={'group': item})
def group_remove_member_user(self, name, item):
return self.group_remove_member(name=name, item={'user': item})
def get_group_dict(description=None, external=None, gid=None, nonposix=None):
group = {}
if description is not None:
group['description'] = description
if external is not None:
group['external'] = external
if gid is not None:
group['gidnumber'] = gid
if nonposix is not None:
group['nonposix'] = nonposix
return group
def get_group_diff(client, ipa_group, module_group):
data = []
# With group_add attribute nonposix is passed, whereas with group_mod only posix can be passed.
if 'nonposix' in module_group:
# Only non-posix groups can be changed to posix
if not module_group['nonposix'] and ipa_group.get('nonposix'):
module_group['posix'] = True
del module_group['nonposix']
return client.get_diff(ipa_data=ipa_group, module_data=module_group)
def ensure(module, client):
state = module.params['state']
name = module.params['name']
group = module.params['group']
user = module.params['user']
module_group = get_group_dict(description=module.params['description'], external=module.params['external'],
gid=module.params['gidnumber'], nonposix=module.params['nonposix'])
ipa_group = client.group_find(name=name)
changed = False
if state == 'present':
if not ipa_group:
changed = True
if not module.check_mode:
ipa_group = client.group_add(name, item=module_group)
else:
diff = get_group_diff(client, ipa_group, module_group)
if len(diff) > 0:
changed = True
if not module.check_mode:
data = {}
for key in diff:
data[key] = module_group.get(key)
client.group_mod(name=name, item=data)
if group is not None:
changed = client.modify_if_diff(name, ipa_group.get('member_group', []), group,
client.group_add_member_group,
client.group_remove_member_group) or changed
if user is not None:
changed = client.modify_if_diff(name, ipa_group.get('member_user', []), user,
client.group_add_member_user,
client.group_remove_member_user) or changed
else:
if ipa_group:
changed = True
if not module.check_mode:
client.group_del(name)
return changed, client.group_find(name=name)
def main():
module = AnsibleModule(
argument_spec=dict(
cn=dict(type='str', required=True, aliases=['name']),
description=dict(type='str', required=False),
external=dict(type='bool', required=False),
gidnumber=dict(type='str', required=False, aliases=['gid']),
group=dict(type='list', required=False),
nonposix=dict(type='bool', required=False),
state=dict(type='str', required=False, default='present', choices=['present', 'absent']),
user=dict(type='list', required=False),
ipa_prot=dict(type='str', required=False, default='https', choices=['http', 'https']),
ipa_host=dict(type='str', required=False, default='ipa.example.com'),
ipa_port=dict(type='int', required=False, default=443),
ipa_user=dict(type='str', required=False, default='admin'),
ipa_pass=dict(type='str', required=True, no_log=True),
validate_certs=dict(type='bool', required=False, default=True),
),
supports_check_mode=True,
)
client = GroupIPAClient(module=module,
host=module.params['ipa_host'],
port=module.params['ipa_port'],
protocol=module.params['ipa_prot'])
try:
client.login(username=module.params['ipa_user'],
password=module.params['ipa_pass'])
changed, group = ensure(module, client)
module.exit_json(changed=changed, group=group)
except Exception:
e = get_exception()
module.fail_json(msg=str(e))
if __name__ == '__main__':
main()
| gpl-3.0 |
honnibal/spaCy | spacy/lang/lt/morph_rules.py | 1 | 76393 | # coding: utf8
from __future__ import unicode_literals
from ...symbols import LEMMA, PRON_LEMMA
_coordinating_conjunctions = [
"ar",
"arba",
"bei",
"beigi",
"bet",
"betgi",
"ir",
"kadangi",
"kuo",
"ne",
"o",
"tad",
"tai",
"tačiau",
"tegul",
"tik",
"visgi",
]
_subordinating_conjunctions = [
"jei",
"jeigu",
"jog",
"kad",
"kai",
"kaip",
"kol",
"lyg",
"nebent",
"negu",
"nei",
"nes",
"nors",
"tarsi",
"tuo",
"užuot",
]
MORPH_RULES = {
"Cg": dict(
[(word, {"POS": "CCONJ"}) for word in _coordinating_conjunctions]
+ [(word, {"POS": "SCONJ"}) for word in _subordinating_conjunctions]
),
"Pg--an": {
"keletą": {LEMMA: PRON_LEMMA, "POS": "PRON", "Case": "Acc", "PronType": "Ind"},
"save": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"PronType": "Prs",
"Reflex": "Yes",
},
},
"Pg--dn": {
"sau": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"PronType": "Prs",
"Reflex": "Yes",
}
},
"Pg--gn": {
"keleto": {LEMMA: PRON_LEMMA, "POS": "PRON", "Case": "Gen", "PronType": "Ind"},
"savo": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"PronType": "Prs",
"Reflex": "Yes",
},
"savęs": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"PronType": "Prs",
"Reflex": "Yes",
},
},
"Pg--in": {
"savimi": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"PronType": "Prs",
"Reflex": "Yes",
}
},
"Pg--nn": {
"keletas": {LEMMA: PRON_LEMMA, "POS": "PRON", "Case": "Nom", "PronType": "Ind"}
},
"Pg-dnn": {
"mudu": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Number": "Dual",
"Person": "1",
"PronType": "Prs",
}
},
"Pg-pa-": {
"jus": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Number": "Plur",
"Person": "2",
"PronType": "Prs",
}
},
"Pg-pan": {
"jus": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Number": "Plur",
"Person": "2",
"PronType": "Prs",
},
"mus": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Number": "Plur",
"Person": "1",
"PronType": "Prs",
},
},
"Pg-pdn": {
"jums": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Number": "Plur",
"Person": "2",
"PronType": "Prs",
},
"mums": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Number": "Plur",
"Person": "1",
"PronType": "Prs",
},
},
"Pg-pgn": {
"jūsų": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Number": "Plur",
"Person": "2",
"PronType": "Prs",
},
"mūsų": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Number": "Plur",
"Person": "1",
"PronType": "Prs",
},
},
"Pg-pin": {
"jumis": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Number": "Plur",
"Person": "2",
"PronType": "Prs",
},
"mumis": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Number": "Plur",
"Person": "1",
"PronType": "Prs",
},
},
"Pg-pln": {
"jumyse": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Number": "Plur",
"Person": "2",
"PronType": "Prs",
}
},
"Pg-pnn": {
"jūs": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Number": "Plur",
"Person": "2",
"PronType": "Prs",
},
"mes": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Number": "Plur",
"Person": "1",
"PronType": "Prs",
},
},
"Pg-san": {
"mane": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Number": "Sing",
"Person": "1",
"PronType": "Prs",
},
"tave": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Number": "Sing",
"Person": "2",
"PronType": "Prs",
},
},
"Pg-sd-": {
"tau": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Number": "Sing",
"Person": "2",
"PronType": "Prs",
}
},
"Pg-sdn": {
"man": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Number": "Sing",
"Person": "1",
"PronType": "Prs",
},
"sau": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Number": "Sing",
"PronType": "Prs",
"Reflex": "Yes",
},
"tau": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Number": "Sing",
"Person": "2",
"PronType": "Prs",
},
},
"Pg-sgn": {
"mano": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Number": "Sing",
"Person": "1",
"PronType": "Prs",
},
"manęs": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Number": "Sing",
"Person": "1",
"PronType": "Prs",
},
"tavo": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Number": "Sing",
"Person": "2",
"PronType": "Prs",
},
"tavęs": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Number": "Sing",
"Person": "2",
"PronType": "Prs",
},
},
"Pg-sin": {
"manimi": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Number": "Sing",
"Person": "1",
"PronType": "Prs",
},
"tavim": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Number": "Sing",
"Person": "2",
"PronType": "Prs",
},
"tavimi": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Number": "Sing",
"Person": "2",
"PronType": "Prs",
},
},
"Pg-sln": {
"manyje": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Number": "Sing",
"Person": "1",
"PronType": "Prs",
},
"tavyje": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Number": "Sing",
"Person": "2",
"PronType": "Prs",
},
},
"Pg-snn": {
"aš": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Number": "Sing",
"Person": "1",
"PronType": "Prs",
},
"tu": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Number": "Sing",
"Person": "2",
"PronType": "Prs",
},
},
"Pgf-an": {
"kelias": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Fem",
"PronType": "Ind",
}
},
"Pgf-dn": {
"kelioms": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Fem",
"PronType": "Ind",
}
},
"Pgf-nn": {
"kelios": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"PronType": "Ind",
}
},
"Pgfdn-": {
"abi": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"Number": "Dual",
"PronType": "Ind",
}
},
"Pgfpan": {
"jas": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Fem",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"kelias": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kitas": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kokias": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Int",
},
"kurias": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Int",
},
"savas": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"tas": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
"tokias": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgfpdn": {
"joms": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Fem",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"kitoms": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kurioms": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Int",
},
"tokioms": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgfpgn": {
"jokių": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Neg",
},
"jų": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Fem",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"kelių": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kitų": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kurių": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Int",
},
"pačių": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Emp",
},
"tokių": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
"tų": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgfpin": {
"jomis": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Fem",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"kitokiomis": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kitomis": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kokiomis": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Int",
},
"kuriomis": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Int",
},
"pačiomis": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Emp",
},
"tomis": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgfpln": {
"jose": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Gender": "Fem",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"kitose": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kuriose": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Int",
},
"tokiose": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
"tose": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgfpnn": {
"jos": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"kitokios": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kitos": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Ind",
},
"kokios": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Int",
},
"kurios": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Int",
},
"pačios": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Emp",
},
"tokios": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
"tos": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgfsan": {
"ją": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Fem",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kiekvieną": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Tot",
},
"kitokią": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Ind",
},
"kitą": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Ind",
},
"kokią": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Int",
},
"kurią": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Int",
},
"pačią": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Emp",
},
"tokią": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
"tą": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgfsdn": {
"jai": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Fem",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kiekvienai": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Tot",
},
"kitai": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Ind",
},
"pačiai": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Emp",
},
},
"Pgfsgn": {
"jokios": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Neg",
},
"jos": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Fem",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kiekvienos": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Tot",
},
"kokios": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Int",
},
"kurios": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Int",
},
"pačios": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Emp",
},
"tokios": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
"tos": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgfsin": {
"ja": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Fem",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kiekviena": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Tot",
},
"kita": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Ind",
},
"kuria": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Int",
},
"ta": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
"tokia": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgfsln": {
"joje": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Gender": "Fem",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kiekvienoje": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Tot",
},
"kitoje": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Ind",
},
"kurioje": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Int",
},
"toje": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
"tokioje": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgfsnn": {
"ji": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kiekviena": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Tot",
},
"kita": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Ind",
},
"kokia": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Int",
},
"kuri": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Int",
},
"pati": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Emp",
},
"sava": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Ind",
},
"ta": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
"tokia": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgfsny": {
"jinai": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"toji": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgfsny-": {
"jinai": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Fem",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
}
},
"Pgm-a-": {
"kelis": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"PronType": "Ind",
}
},
"Pgm-an": {
"kelis": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"PronType": "Ind",
}
},
"Pgm-dn": {
"keliems": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Masc",
"PronType": "Ind",
}
},
"Pgm-gn": {
"kelių": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Masc",
"PronType": "Ind",
}
},
"Pgm-nn": {
"keli": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Masc",
"PronType": "Ind",
}
},
"Pgmdan": {
"mudu": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"Number": "Dual",
"Person": "1",
"PronType": "Prs",
}
},
"Pgmdgn": {
"mudviejų": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Masc",
"Number": "Dual",
"Person": "1",
"PronType": "Prs",
}
},
"Pgmdnn": {
"jiedu": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Masc",
"Number": "Dual",
"Person": "3",
"PronType": "Prs",
},
"mudu": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Masc",
"Number": "Dual",
"Person": "1",
"PronType": "Prs",
},
},
"Pgmpan": {
"juos": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"jus": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"Number": "Plur",
"Person": "2",
"PronType": "Prs",
},
"kitus": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Ind",
},
"kokius": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Int",
},
"kuriuos": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Int",
},
"pačius": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Emp",
},
"tokius": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Dem",
},
"tuos": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgmpan-": {
"juos": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
}
},
"Pgmpdn": {
"jiems": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Masc",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"kitiems": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Ind",
},
"kuriems": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Int",
},
"patiems": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Emp",
},
"tiems": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgmpgn": {
"jokių": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Neg",
},
"jų": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Masc",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"kitų": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Ind",
},
"kokių": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Int",
},
"kurių": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Int",
},
"pačių": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Emp",
},
"tokių": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Dem",
},
"tų": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgmpin": {
"jais": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Masc",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"jokiais": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Neg",
},
"kitais": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Ind",
},
"kokiais": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Int",
},
"savais": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Ind",
},
"tais": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Dem",
},
"tokiais": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgmpln": {
"juose": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Gender": "Masc",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"kituose": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Ind",
},
},
"Pgmpnn": {
"jie": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Masc",
"Number": "Plur",
"Person": "3",
"PronType": "Prs",
},
"jūs": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Masc",
"Number": "Plur",
"Person": "2",
"PronType": "Prs",
},
"kiti": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Ind",
},
"kokie": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Int",
},
"kurie": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Int",
},
"patys": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Emp",
},
"tie": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Dem",
},
"tokie": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Plur",
"PronType": "Dem",
},
},
"Pgmsan": {
"jį": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kiekvieną": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Tot",
},
"kitokį": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Ind",
},
"kitą": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Acc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Ind",
},
"kokį": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"kurį": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"tokį": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
"tą": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Acc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgmsdn": {
"jam": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Masc",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kiekvienam": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Tot",
},
"kitam": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Dat",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Ind",
},
"kokiam": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"kuriam": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"pačiam": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Emp",
},
"tam": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Dat",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgmsgn": {
"jo": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"jokio": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Neg",
},
"kiekvieno": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Tot",
},
"kito": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Ind",
},
"kokio": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"kurio": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"paties": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Emp",
},
"savo": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Ind",
},
"to": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
"tokio": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Gen",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgmsin": {
"juo": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Masc",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kitu": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Ins",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Ind",
},
"kokiu": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"kuriuo": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"pačiu": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Emp",
},
"tokiu": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
"tuo": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Ins",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgmsln": {
"jame": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Loc",
"Gender": "Masc",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"kiekvienam": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Tot",
},
"kokiame": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"kuriame": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"tame": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Loc",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgmsnn": {
"jis": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"Person": "3",
"PronType": "Prs",
},
"joks": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Neg",
},
"kiekvienas": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Tot",
},
"kitas": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Ind",
},
"kitoks": {
LEMMA: PRON_LEMMA,
"POS": "PRON",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Ind",
},
"koks": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"kuris": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Int",
},
"pats": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Emp",
},
"tas": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
"toks": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgmsny": {
"patsai": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Emp",
},
"tasai": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
"toksai": {
LEMMA: PRON_LEMMA,
"POS": "DET",
"Case": "Nom",
"Gender": "Masc",
"Number": "Sing",
"PronType": "Dem",
},
},
"Pgn--n": {
"tai": {LEMMA: PRON_LEMMA, "POS": "DET", "Gender": "Neut", "PronType": "Dem"}
},
"Pgnn--n": {
"tai": {LEMMA: PRON_LEMMA, "POS": "DET", "Gender": "Neut", "PronType": "Dem"}
},
"Pgsmdn": {
"tam": {LEMMA: PRON_LEMMA, "POS": "DET", "Case": "Dat", "PronType": "Dem"}
},
"Qg": {"tai": {LEMMA: "tas", "POS": "PART"}},
"Vgap----n--n--": {
"esant": {
LEMMA: "būti",
"POS": "VERB",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Ger",
},
"turint": {
LEMMA: "turėti",
"POS": "VERB",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Ger",
},
},
"Vgh--pm-n--n--": {
"būdami": {
LEMMA: "būti",
"POS": "VERB",
"Gender": "Masc",
"Number": "Plur",
"Polarity": "POS",
"VerbForm": "Conv",
}
},
"Vgh--sm-n--n--": {
"būdamas": {
LEMMA: "būti",
"POS": "VERB",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"VerbForm": "Conv",
}
},
"Vgi-----n--n--": {
"būti": {LEMMA: "būti", "POS": "VERB", "Polarity": "POS", "VerbForm": "Inf"},
"daryti": {
LEMMA: "daryti",
"POS": "VERB",
"Polarity": "POS",
"VerbForm": "Inf",
},
"turėti": {
LEMMA: "turėti",
"POS": "VERB",
"Polarity": "POS",
"VerbForm": "Inf",
},
},
"Vgm-1p--n--ns-": {
"turėtume": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Cnd",
"Number": "Plur",
"Person": "1",
"Polarity": "POS",
"VerbForm": "Fin",
}
},
"Vgm-2p--n--nm-": {
"būkite": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Imp",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"VerbForm": "Fin",
},
"darykit": {
LEMMA: "daryti",
"POS": "VERB",
"Mood": "Imp",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"VerbForm": "Fin",
},
"darykite": {
LEMMA: "daryti",
"POS": "VERB",
"Mood": "Imp",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"VerbForm": "Fin",
},
"turėkite": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Imp",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"VerbForm": "Fin",
},
},
"Vgm-2p--n--ns-": {
"turėtumėte": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Cnd",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"VerbForm": "Fin",
}
},
"Vgm-2s--n--ns-": {
"turėtum": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Cnd",
"Number": "Sing",
"Person": "2",
"Polarity": "POS",
"VerbForm": "Fin",
}
},
"Vgm-3---n--ns-": {
"būtų": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Cnd",
"Person": "3",
"Polarity": "POS",
"VerbForm": "Fin",
},
"turėtų": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Cnd",
"Person": "3",
"Polarity": "POS",
"VerbForm": "Fin",
},
},
"Vgm-3p--n--ns-": {
"būtų": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Cnd",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"VerbForm": "Fin",
},
"turėtų": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Cnd",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"VerbForm": "Fin",
},
},
"Vgm-3s--n--ns-": {
"būtų": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Cnd",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"VerbForm": "Fin",
},
"turėtų": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Cnd",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"VerbForm": "Fin",
},
},
"Vgma1p--n--ni-": {
"turėjom": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "1",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
}
},
"Vgma1s--n--ni-": {
"turėjau": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "1",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
}
},
"Vgma3---n--ni-": {
"buvo": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
},
"turėjo": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
},
},
"Vgma3p--n--ni-": {
"buvo": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
},
"darė": {
LEMMA: "daryti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
},
"turėjo": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
},
},
"Vgma3s--n--ni-": {
"buvo": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
},
"darė": {
LEMMA: "daryti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
},
"turėjo": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
},
},
"Vgmf1s--n--ni-": {
"turėsiu": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "1",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
}
},
"Vgmf2p--n--ni-": {
"būsite": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
},
"darysite": {
LEMMA: "daryti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
},
"turėsite": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
},
},
"Vgmf3---n--ni-": {
"bus": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Person": "3",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
}
},
"Vgmf3p--n--ni-": {
"bus": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
},
"darys": {
LEMMA: "daryti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
},
"turės": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
},
},
"Vgmf3s--n--ni-": {
"bus": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
},
"turės": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Fin",
},
},
"Vgmp1p--n--ni-": {
"darome": {
LEMMA: "daryti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "1",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"esame": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "1",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"turime": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "1",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
},
"Vgmp1s--n--ni-": {
"būnu": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "1",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"esu": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "1",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"turiu": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "1",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
},
"Vgmp2p--n--ni-": {
"esate": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"turite": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "2",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
},
"Vgmp2s--n--ni-": {
"esi": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "2",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"turi": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "2",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
},
"Vgmp3---n--ni-": {
"būna": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"turi": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"yra": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
},
"Vgmp3p--n--ni-": {
"būna": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"daro": {
LEMMA: "daryti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"turi": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"yra": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Plur",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
},
"Vgmp3s--n--ni-": {
"būna": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"daro": {
LEMMA: "daryti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"turi": {
LEMMA: "turėti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
"yra": {
LEMMA: "būti",
"POS": "VERB",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Fin",
},
},
"Vgmq2s--n--ni-": {
"turėdavai": {
LEMMA: "turėti",
"POS": "VERB",
"Aspect": "Hab",
"Mood": "Ind",
"Number": "Sing",
"Person": "2",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
}
},
"Vgmq3---n--ni-": {
"būdavo": {
LEMMA: "būti",
"POS": "VERB",
"Aspect": "Hab",
"Mood": "Ind",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
}
},
"Vgmq3s--n--ni-": {
"turėdavo": {
LEMMA: "turėti",
"POS": "VERB",
"Aspect": "Hab",
"Mood": "Ind",
"Number": "Sing",
"Person": "3",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Fin",
}
},
"Vgp--pfnnnnn-p": {
"darytinos": {
LEMMA: "daryti",
"POS": "VERB",
"Case": "Nom",
"Degree": "POS",
"Gender": "Fem",
"Number": "Plur",
"Polarity": "POS",
"VerbForm": "Part",
}
},
"Vgpa--nann-n-p": {
"buvę": {
LEMMA: "būti",
"POS": "VERB",
"Degree": "POS",
"Gender": "Neut",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpa-pmanngn-p": {
"buvusių": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Gen",
"Degree": "POS",
"Gender": "Masc",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpa-smanngn-p": {
"buvusio": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Gen",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpa-smannnn-p": {
"buvęs": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Nom",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Part",
"Voice": "Act",
},
"turėjęs": {
LEMMA: "turėti",
"POS": "VERB",
"Case": "Nom",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Part",
"Voice": "Act",
},
},
"Vgpa-smanyin-p": {
"buvusiuoju": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Ins",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpf-smpnnan-p": {
"būsimą": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Acc",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Part",
"Voice": "Pass",
}
},
"Vgpf-smpnndn-p": {
"būsimam": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Dat",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Fut",
"VerbForm": "Part",
"Voice": "Pass",
}
},
"Vgpp--npnn-n-p": {
"esama": {
LEMMA: "būti",
"POS": "VERB",
"Degree": "POS",
"Gender": "Neut",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Pass",
}
},
"Vgpp-pfannan-p": {
"esančias": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Acc",
"Degree": "POS",
"Gender": "Fem",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-pfanndn-p": {
"turinčioms": {
LEMMA: "turėti",
"POS": "VERB",
"Case": "Dat",
"Degree": "POS",
"Gender": "Fem",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-pfannin-p": {
"esančiomis": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Ins",
"Degree": "POS",
"Gender": "Fem",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-pfpnnan-p": {
"daromas": {
LEMMA: "daryti",
"POS": "VERB",
"Case": "Acc",
"Degree": "POS",
"Gender": "Fem",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Pass",
},
"turimas": {
LEMMA: "turėti",
"POS": "VERB",
"Case": "Acc",
"Degree": "POS",
"Gender": "Fem",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Pass",
},
},
"Vgpp-pfpnnin-p": {
"turimomis": {
LEMMA: "turėti",
"POS": "VERB",
"Case": "Ins",
"Degree": "POS",
"Gender": "Fem",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Pass",
}
},
"Vgpp-pmannan-p": {
"turinčius": {
LEMMA: "turėti",
"POS": "VERB",
"Case": "Acc",
"Degree": "POS",
"Gender": "Masc",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-pmanngn-p": {
"esančių": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Gen",
"Degree": "POS",
"Gender": "Masc",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-pmannin-p": {
"esančiais": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Ins",
"Degree": "POS",
"Gender": "Masc",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-pmannnn-p": {
"esantys": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Nom",
"Degree": "POS",
"Gender": "Masc",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-pmpnnan-p": {
"turimus": {
LEMMA: "turėti",
"POS": "VERB",
"Case": "Acc",
"Degree": "POS",
"Gender": "Masc",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Pass",
}
},
"Vgpp-pmpnngn-p": {
"esamų": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Gen",
"Degree": "POS",
"Gender": "Masc",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Pass",
}
},
"Vgpp-sfanngn-p": {
"turinčios": {
LEMMA: "turėti",
"POS": "VERB",
"Case": "Gen",
"Degree": "POS",
"Gender": "Fem",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-sfannln-p": {
"esančioje": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Loc",
"Degree": "POS",
"Gender": "Fem",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-sfannnn-p": {
"esanti": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Nom",
"Degree": "POS",
"Gender": "Fem",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-sfpnnnn-p": {
"daroma": {
LEMMA: "daryti",
"POS": "VERB",
"Case": "Nom",
"Degree": "POS",
"Gender": "Fem",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Pass",
}
},
"Vgpp-smanngn-p": {
"esančio": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Gen",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
}
},
"Vgpp-smannnn-p": {
"esantis": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Nom",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
},
"esąs": {
LEMMA: "būti",
"POS": "VERB",
"Case": "Nom",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
},
"turintis": {
LEMMA: "turėti",
"POS": "VERB",
"Case": "Nom",
"Degree": "POS",
"Gender": "Masc",
"Number": "Sing",
"Polarity": "POS",
"Tense": "Pres",
"VerbForm": "Part",
"Voice": "Act",
},
},
"Vgps--npnn-n-p": {
"daryta": {
LEMMA: "daryti",
"POS": "VERB",
"Aspect": "Perf",
"Degree": "POS",
"Gender": "Neut",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Part",
"Voice": "Pass",
}
},
"Vgps-pmpnnnn-p": {
"daryti": {
LEMMA: "daryti",
"POS": "VERB",
"Aspect": "Perf",
"Case": "Nom",
"Degree": "POS",
"Gender": "Masc",
"Number": "Plur",
"Polarity": "POS",
"Tense": "Past",
"VerbForm": "Part",
"Voice": "Pass",
}
},
}
for tag, rules in MORPH_RULES.items():
for key, attrs in dict(rules).items():
rules[key.title()] = attrs
| mit |
toshywoshy/ansible | test/units/plugins/lookup/test_env.py | 54 | 1120 | # -*- coding: utf-8 -*-
# Copyright: (c) 2019, Abhay Kadam <abhaykadam88@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from ansible.plugins.loader import lookup_loader
@pytest.mark.parametrize('env_var,exp_value', [
('foo', 'bar'),
('equation', 'a=b*100')
])
def test_env_var_value(monkeypatch, env_var, exp_value):
monkeypatch.setattr('ansible.utils.py3compat.environ.get', lambda x, y: exp_value)
env_lookup = lookup_loader.get('env')
retval = env_lookup.run([env_var], None)
assert retval == [exp_value]
@pytest.mark.parametrize('env_var,exp_value', [
('simple_var', 'alpha-β-gamma'),
('the_var', 'ãnˈsiβle')
])
def test_utf8_env_var_value(monkeypatch, env_var, exp_value):
monkeypatch.setattr('ansible.utils.py3compat.environ.get', lambda x, y: exp_value)
env_lookup = lookup_loader.get('env')
retval = env_lookup.run([env_var], None)
assert retval == [exp_value]
| gpl-3.0 |
israelbenatar/boto | boto/gs/user.py | 168 | 1947 | # Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class User(object):
def __init__(self, parent=None, id='', name=''):
if parent:
parent.owner = self
self.type = None
self.id = id
self.name = name
def __repr__(self):
return self.id
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Name':
self.name = value
elif name == 'ID':
self.id = value
else:
setattr(self, name, value)
def to_xml(self, element_name='Owner'):
if self.type:
s = '<%s type="%s">' % (element_name, self.type)
else:
s = '<%s>' % element_name
s += '<ID>%s</ID>' % self.id
if self.name:
s += '<Name>%s</Name>' % self.name
s += '</%s>' % element_name
return s
| mit |
shepdelacreme/ansible | lib/ansible/modules/identity/ipa/ipa_vault.py | 74 | 7749 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Juan Manuel Parrilla <jparrill@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ipa_vault
author: Juan Manuel Parrilla (@jparrill)
short_description: Manage FreeIPA vaults
description:
- Add, modify and delete vaults and secret vaults.
- KRA service should be enabled to use this module.
options:
cn:
description:
- Vault name.
- Can not be changed as it is the unique identifier.
required: true
aliases: ["name"]
description:
description:
- Description.
ipavaulttype:
description:
- Vault types are based on security level.
default: "symmetric"
choices: ["standard", "symmetric", "asymmetric"]
required: true
aliases: ["vault_type"]
ipavaultpublickey:
description:
- Public key.
aliases: ["vault_public_key"]
ipavaultsalt:
description:
- Vault Salt.
aliases: ["vault_salt"]
username:
description:
- Any user can own one or more user vaults.
- Mutually exclusive with service.
aliases: ["user"]
service:
description:
- Any service can own one or more service vaults.
- Mutually exclusive with user.
state:
description:
- State to ensure.
default: "present"
choices: ["present", "absent"]
replace:
description:
- Force replace the existant vault on IPA server.
type: bool
default: False
choices: ["True", "False"]
validate_certs:
description:
- Validate IPA server certificates.
type: bool
default: true
extends_documentation_fragment: ipa.documentation
version_added: "2.7"
'''
EXAMPLES = '''
# Ensure vault is present
- ipa_vault:
name: vault01
vault_type: standard
user: user01
ipa_host: ipa.example.com
ipa_user: admin
ipa_pass: topsecret
validate_certs: false
# Ensure vault is present for Admin user
- ipa_vault:
name: vault01
vault_type: standard
ipa_host: ipa.example.com
ipa_user: admin
ipa_pass: topsecret
# Ensure vault is absent
- ipa_vault:
name: vault01
vault_type: standard
user: user01
state: absent
ipa_host: ipa.example.com
ipa_user: admin
ipa_pass: topsecret
# Modify vault if already exists
- ipa_vault:
name: vault01
vault_type: standard
description: "Vault for test"
ipa_host: ipa.example.com
ipa_user: admin
ipa_pass: topsecret
replace: True
# Get vault info if already exists
- ipa_vault:
name: vault01
ipa_host: ipa.example.com
ipa_user: admin
ipa_pass: topsecret
'''
RETURN = '''
vault:
description: Vault as returned by IPA API
returned: always
type: dict
'''
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ipa import IPAClient, ipa_argument_spec
from ansible.module_utils._text import to_native
class VaultIPAClient(IPAClient):
def __init__(self, module, host, port, protocol):
super(VaultIPAClient, self).__init__(module, host, port, protocol)
def vault_find(self, name):
return self._post_json(method='vault_find', name=None, item={'all': True, 'cn': name})
def vault_add_internal(self, name, item):
return self._post_json(method='vault_add_internal', name=name, item=item)
def vault_mod_internal(self, name, item):
return self._post_json(method='vault_mod_internal', name=name, item=item)
def vault_del(self, name):
return self._post_json(method='vault_del', name=name)
def get_vault_dict(description=None, vault_type=None, vault_salt=None, vault_public_key=None, service=None):
vault = {}
if description is not None:
vault['description'] = description
if vault_type is not None:
vault['ipavaulttype'] = vault_type
if vault_salt is not None:
vault['ipavaultsalt'] = vault_salt
if vault_public_key is not None:
vault['ipavaultpublickey'] = vault_public_key
if service is not None:
vault['service'] = service
return vault
def get_vault_diff(client, ipa_vault, module_vault, module):
return client.get_diff(ipa_data=ipa_vault, module_data=module_vault)
def ensure(module, client):
state = module.params['state']
name = module.params['cn']
user = module.params['username']
replace = module.params['replace']
module_vault = get_vault_dict(description=module.params['description'], vault_type=module.params['ipavaulttype'],
vault_salt=module.params['ipavaultsalt'],
vault_public_key=module.params['ipavaultpublickey'],
service=module.params['service'])
ipa_vault = client.vault_find(name=name)
changed = False
if state == 'present':
if not ipa_vault:
# New vault
changed = True
if not module.check_mode:
ipa_vault = client.vault_add_internal(name, item=module_vault)
else:
# Already exists
if replace:
diff = get_vault_diff(client, ipa_vault, module_vault, module)
if len(diff) > 0:
changed = True
if not module.check_mode:
data = {}
for key in diff:
data[key] = module_vault.get(key)
client.vault_mod_internal(name=name, item=data)
else:
if ipa_vault:
changed = True
if not module.check_mode:
client.vault_del(name)
return changed, client.vault_find(name=name)
def main():
argument_spec = ipa_argument_spec()
argument_spec.update(cn=dict(type='str', required=True, aliases=['name']),
description=dict(type='str'),
ipavaulttype=dict(type='str', default='symmetric',
choices=['standard', 'symmetric', 'asymmetric'], aliases=['vault_type']),
ipavaultsalt=dict(type='str', aliases=['vault_salt']),
ipavaultpublickey=dict(type='str', aliases=['vault_public_key']),
service=dict(type='str'),
replace=dict(type='bool', default=False, choices=[True, False]),
state=dict(type='str', default='present', choices=['present', 'absent']),
username=dict(type='list', aliases=['user']))
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True,
mutually_exclusive=[['username', 'service']])
client = VaultIPAClient(module=module,
host=module.params['ipa_host'],
port=module.params['ipa_port'],
protocol=module.params['ipa_prot'])
try:
client.login(username=module.params['ipa_user'],
password=module.params['ipa_pass'])
changed, vault = ensure(module, client)
module.exit_json(changed=changed, vault=vault)
except Exception as e:
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
if __name__ == '__main__':
main()
| gpl-3.0 |
deepakar/DCNDN | PyNDN/nre.py | 15 | 22562 | # -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
#
# Copyright (c) 2013, Regents of the University of California
# Yingdi Yu, Alexander Afanasyev
#
# BSD license, See the doc/LICENSE file for more information
#
# Author: Yingdi Yu <yingdi@cs.ucla.edu>
# Alexander Afanasyev <alexander.afanasyev@ucla.edu>
#
import sys
import re
import logging
from Name import Name
_LOG = logging.getLogger ("ndn.nre")
class RegexError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class BaseMatcher(object):
def __init__(self, expr, backRef, exact=True):
_LOG.debug(self.__class__.__name__ + ".Constructor")
self.expr = expr
self.backRef = backRef
self.exact = exact
self.matchResult = []
self.matcherList = []
def match(self, name, offset, len):
_LOG.debug(self.__class__.__name__ + ".match(): " + "expr: " + self.expr + " offset: " + str(offset) + " length: " + str(len))
self.matchResult = []
if self._recursiveMatch(0, name, offset, len):
for i in range(offset, offset + len):
self.matchResult.append(str (name[i]))
return True
else:
return False
def _recursiveMatch(self, mId, name, offset, length):
_LOG.debug(self.__class__.__name__ + "._recursiveMatch(): " + self.expr)
_LOG.debug("mId: " + str(mId) + " name: " + str(name) + " offset: " + str(offset) + " length: " + str(length) + " matcherListSize: " + str(len(self.matcherList)))
tried = 0
if mId >= len(self.matcherList) :
if length != 0 :
_LOG.debug("Fail " + self.__class__.__name__ + "._recursiveMatch(): no more matcher, but more components")
return False
else:
_LOG.debug("Succeed " + self.__class__.__name__ + "._recursiveMatch(): no more matcher, no more components")
return True
matcher = self.matcherList[mId]
while tried <= length:
if matcher.match(name, offset, tried) and self._recursiveMatch(mId + 1, name, offset + tried, length - tried) :
return True
_LOG.debug(self.__class__.__name__ + " expr: " + self.expr + " mId: " + str(mId) + " tried: " + str(tried) + " length: " + str(length))
tried += 1
return False
def aggressiveMatch(self, name, offset, len):
_LOG.debug(self.__class__.__name__ + ".aggressiveMatch(): " + "expr: " + self.expr + " offset: " + str(offset) + " length: " + str(len))
self.matchResult = []
if self._aRecursiveMatch(0, name, offset, len):
for i in range(offset, offset + len):
self.matchResult.append(str (name[i]))
return True
else:
return False
def _aRecursiveMatch(self, mId, name, offset, length):
_LOG.debug(self.__class__.__name__ + "._aRecursiveMatch(): " + self.expr)
_LOG.debug("mId: " + str(mId) + " name: " + str(name) + " offset: " + str(offset) + " length: " + str(length) + " matcherListSize: " + str(len(self.matcherList)))
tried = length
if mId >= len(self.matcherList) :
if length != 0 :
_LOG.debug("Fail " + self.__class__.__name__ + "._recursiveMatch(): no more matcher, but more components")
return False
else:
_LOG.debug("Succeed " + self.__class__.__name__ + "._recursiveMatch(): no more matcher, no more components")
return True
matcher = self.matcherList[mId]
while tried >= 0:
if matcher.aggressiveMatch(name, offset, tried) and self._aRecursiveMatch(mId + 1, name, offset + tried, length - tried):
return True
_LOG.debug(self.__class__.__name__ + " expr: " + self.expr + " mId: " + str(mId) + " tried: " + str(tried) + " length: " + str(length))
tried -= 1
return False
class ComponentMatcher(BaseMatcher):
def __init__(self, expr, backRef, exact=True):
_LOG.debug(self.__class__.__name__ + ".Constructor")
_LOG.debug("expr " + expr)
super(ComponentMatcher, self).__init__(expr, backRef, exact)
pattern = re.compile(self.expr)
self.pseudoBackRefMatcher = []
for i in range(0, pattern.groups):
pseudoMatcher = BaseMatcher("", self.backRef)
self.pseudoBackRefMatcher.append(pseudoMatcher)
self.backRef.append(pseudoMatcher)
def _appendBackRef(self, res):
if res and 0 < len(res.groups()):
group = res.groups()
for i in range(0, len(group)):
self.pseudoBackRefMatcher[i].matchResult = []
self.pseudoBackRefMatcher[i].matchResult.append(group[i])
def match(self, name, offset, len):
_LOG.debug(self.__class__.__name__ + ".match(): " + self.expr)
_LOG.debug("Name " + str(name) + " offset " + str(offset) + " len " +str(len))
self.matchResult = []
if "" == self.expr:
res = self.matchResult.append(str (name[offset]))
self._appendBackRef(res)
_LOG.debug("Succeed " + self.__class__.__name__ + ".match() ")
return True
matcher = re.compile(self.expr)
if self.exact:
res = matcher.match(str(name[offset]))
if res:
self._appendBackRef(res)
self.matchResult.append(str (name[offset]))
_LOG.debug("Succeed " + self.__class__.__name__ + ".match() ")
return True
else:
res = matcher.search(str(name[offset]))
if res:
self._appendBackRef(res)
self.matchResult.append(str (name[offset]))
return True
return False
def aggressiveMatch(self, name, offset, len):
return self.match(name, offset, len)
class ComponentSetMatcher(BaseMatcher):
def __init__(self, expr, backRef, exact=True):
_LOG.debug(self.__class__.__name__ + ".Constructor")
errMsg = "Error: ComponentSetMatcher.Constructor: "
self.include = True
super(ComponentSetMatcher, self).__init__(expr, backRef, exact)
if '<' == self.expr[0]:
self._compileSingleComponent()
elif '[' == self.expr[0]:
lastIndex = len(self.expr) - 1
if ']' != self.expr[lastIndex]:
raise RegexError(errMsg + " No matched ']' " + self.expr)
if '^' == self.expr[1]:
self.include = False
self._compileMultipleComponents(2, lastIndex)
else:
self._compileMultipleComponents(1, lastIndex)
def _compileSingleComponent(self):
_LOG.debug(self.__class__.__name__ + "._compileSingleComponent")
errMsg = "Error: ComponentSetMatcher.CompileSingleComponent(): "
end = self._extractComponent(1)
if len(self.expr) != end:
raise RegexError(errMsg + "out of bound " + self.expr)
else:
self.matcherList.append(ComponentMatcher(self.expr[1:end-1], self.backRef))
def _compileMultipleComponents(self, start, lastIndex):
_LOG.debug(self.__class__.__name__ + "._compileMultipleComponents")
errMsg = "Error: ComponentSetMatcher.CompileMultipleComponents(): "
index = start
tmp_index = start
while index < lastIndex:
if '<' != self.expr[index]:
raise RegexError(errMsg + "Component expr error " + self.expr)
tmp_index = index + 1
index = self._extractComponent(tmp_index)
self.matcherList.append(ComponentMatcher(self.expr[tmp_index:index-1], self.backRef))
if index != lastIndex:
raise RegexError(errMsg + "Not sufficient expr to parse " + self.expr)
def _extractComponent(self, index):
_LOG.debug(self.__class__.__name__ + "._extractComponent")
lcount = 1
rcount = 0
while lcount > rcount :
if len(self.expr) == index:
break
elif '<' == self.expr[index]:
lcount += 1
elif '>' == self.expr[index]:
rcount += 1
index += 1
return index
def match(self, name, offset, len):
_LOG.debug(self.__class__.__name__ + ".match(): " + self.expr)
self.matchResult = []
matched = False
if 1 != len:
return False
for matcher in self.matcherList:
res = matcher.match(name, offset, len)
if True == res:
matched = True
break
if(matched if self.include else (not matched)):
self.matchResult.append(str (name[offset]))
return True
else:
return False
def aggressiveMatch(self, name, offset, len):
return self.match(name, offset, len)
class BackRefMatcher(BaseMatcher):
def __init__(self, expr, backRef, exact=True):
_LOG.debug (self.__class__.__name__ + ".Constructor")
super(BackRefMatcher, self).__init__(expr, backRef, exact)
errMsg = "Error: BackRefMatcher Constructor: "
_LOG.debug ("expr: " + self.expr);
_LOG.debug ("backRefManager " + str(self.backRef) + " size: " + str(len(self.backRef)))
lastIndex = len(self.expr) - 1
if '(' == self.expr[0] and ')' == self.expr[lastIndex]:
self.backRef.append(self)
self.matcherList.append(PatternListMatcher(self.expr[1:lastIndex], self.backRef, self.exact))
else:
raise RegexError(errMsg + " Unrecognoized format " + self.expr)
class PatternListMatcher(BaseMatcher):
def __init__(self, expr, backRef, exact=True):
_LOG.debug(self.__class__.__name__ + ".Constructor")
super(PatternListMatcher, self).__init__(expr, backRef, exact)
_LOG.debug("expr: " + self.expr)
exprSize = len(self.expr)
index = 0
subHead = index
while index < exprSize:
subHead = index
(r_res, r_index) = self._extractPattern(subHead, index)
index = r_index
if not r_res:
raise RegexError("Fail to create PatternListMatcher")
def _extractPattern(self, index, next):
_LOG.debug(self.__class__.__name__ + "._extractPattern")
errMsg = "Error: PatternListMatcher._extractPattern: "
start = index
End = index
indicator = index
_LOG.debug ("expr: " + self.expr + " index: " + str(index))
if '(' == self.expr[index]:
index += 1
index = self._extractSubPattern('(', ')', index)
indicator = index
end = self._extractRepetition(index)
if indicator == end:
self.matcherList.append(BackRefMatcher(self.expr[start:end], self.backRef, self.exact))
else:
self.matcherList.append(RepeatMatcher(self.expr[start:end], self.backRef, indicator-start, self.exact))
elif '<' == self.expr[index]:
index += 1
index = self._extractSubPattern('<', '>', index)
indicator = index
end = self._extractRepetition(index)
self.matcherList.append(RepeatMatcher(self.expr[start:end], self.backRef, indicator-start, self.exact))
_LOG.debug("start: " + str(start) + " end: " + str(end) + " indicator: " + str(indicator))
elif '[' == self.expr[index]:
index += 1
index = self._extractSubPattern('[', ']', index)
indicator = index
end = self._extractRepetition(index)
self.matcherList.append(RepeatMatcher(self.expr[start:end], self.backRef, indicator-start, self.exact))
_LOG.debug("start: " + str(start) + " end: " + str(end) + " indicator: " + str(indicator))
else:
raise RegexError(errMsg +"unexpected syntax")
return (True, end)
def _extractSubPattern(self, left, right, index):
_LOG.debug(self.__class__.__name__ + "._extractSubPattern")
lcount = 1
rcount = 0
while lcount > rcount:
if index >= len(self.expr):
raise RegexError("Error: parenthesis mismatch")
if left == self.expr[index]:
lcount += 1
if right == self.expr[index]:
rcount += 1
index += 1
return index
def _extractRepetition(self, index):
_LOG.debug(self.__class__.__name__ + "._extractRepetition")
exprSize = len(self.expr)
_LOG.debug("expr: " + self.expr + " index: " + str(index))
errMsg = "Error: PatternListMatcher._extractRepetition: "
if index == exprSize:
return index
if '+' == self.expr[index] or '?' == self.expr[index] or '*' == self.expr[index] :
index += 1
return index
if '{' == self.expr[index]:
while '}' != self.expr[index]:
index += 1
if index == exprSize:
break
if index == exprSize:
raise RegexError(errMsg + "Missing right brace bracket")
else:
index += 1
return index
else:
_LOG.debug ("return index: " + str(index))
return index
class RepeatMatcher(BaseMatcher):
def __init__(self, expr, backRef, indicator, exact=True):
_LOG.debug(self.__class__.__name__ + ".Constructor")
_LOG.debug("expr: " + expr);
super(RepeatMatcher, self).__init__(expr, backRef, exact)
self.indicator = indicator
if '(' == self.expr[0]:
self.matcherList.append(BackRefMatcher(self.expr[0:self.indicator], self.backRef))
else:
self.matcherList.append(ComponentSetMatcher(self.expr[0:self.indicator], self.backRef))
self._parseRepetition()
_LOG.debug("repeatMin: " + str(self.repeatMin) + " repeatMax: " + str(self.repeatMax))
def _parseRepetition(self):
_LOG.debug(self.__class__.__name__ + "._parseRepetition")
errMsg = "Error: RepeatMatcher._parseRepetition(): ";
exprSize = len(self.expr)
intMax = sys.maxint
if exprSize == self.indicator:
self.repeatMin = 1
self.repeatMax = 1
return
else:
if exprSize == (self.indicator + 1):
if '?' == self.expr[self.indicator]:
self.repeatMin = 0
self.repeatMax = 1
if '+' == self.expr[self.indicator]:
self.repeatMin = 1
self.repeatMax = intMax
if '*' == self.expr[self.indicator]:
self.repeatMin = 0
self.repeatMax = intMax
return
else:
repeatStruct = self.expr[self.indicator:exprSize]
min = 0
max = 0
if re.match('{[0-9]+,[0-9]+}$', repeatStruct):
repeats = repeatStruct[1:-1].split(',')
min = int(repeats[0])
max = int(repeats[1])
elif re.match('{[0-9]+,}$', repeatStruct):
repeats = repeatStruct[1:-1].split(',')
min = int(repeats[0])
max = intMax
elif re.match('{,[0-9]+}$', repeatStruct):
repeats = repeatStruct[1:-1].split(',')
min = 0
max = int(repeats[1])
elif re.match('{[0-9]+}$', repeatStruct):
min = int(repeatStruct[1:- 1])
max = min;
else:
raise RegexError(errMsg + "Unrecognized format "+ self.expr);
if min > intMax or max > intMax or min > max:
raise RegexError(errMsg + "Wrong number " + self.expr);
self.repeatMin = min
self.repeatMax = max
def match(self, name, offset, len):
_LOG.debug(self.__class__.__name__ + ".match(): " + "expr: " + self.expr + " offset: " + str(offset) + " len: " + str(len) + " repeatMin: " + str(self.repeatMin))
self.matchResult = []
if 0 == self.repeatMin:
if 0 == len:
return True
if self._recursiveMatch(0, name, offset, len):
for i in range(offset, offset+len):
self.matchResult.append(str (name[i]))
return True
else:
return False
def _recursiveMatch(self, repeat, name, offset, len):
_LOG.debug (self.__class__.__name__ + "._recursiveMatch()" + " repeat: " + str(repeat) + " offset: " + str(offset) + " len: " + str(len) + " rMin: " + str(self.repeatMin) + " rMax: " + str(self.repeatMax))
tried = 0
matcher = self.matcherList[0]
if 0 < len and repeat >= self.repeatMax:
_LOG.debug("Match Fail: Reach m_repeatMax && More components")
return False
if 0 == len and repeat < self.repeatMin:
_LOG.debug("Match Fail: No more components && have NOT reached m_repeatMin " + str(len) + ", " + str(self.repeatMin))
return False
if 0 == len and repeat >= self.repeatMin:
_LOG.debug("Match Succeed: No more components && reach m_repeatMin")
return True
while tried <= len:
_LOG.debug("Attempt tried: " + str(tried))
if matcher.match(name, offset, tried) and self._recursiveMatch(repeat + 1, name, offset + tried, len - tried):
return True;
_LOG.debug("Failed at tried: " + str(tried));
tried += 1
return False
def aggressiveMatch(self, name, offset, len):
_LOG.debug(self.__class__.__name__ + ".aggressiveMatch(): " + "expr: " + self.expr + " offset: " + str(offset) + " len: " + str(len) + " repeatMin: " + str(self.repeatMin))
self.matchResult = []
if 0 == self.repeatMin:
if 0 == len:
return True
if self._aRecursiveMatch(0, name, offset, len):
for i in range(offset, offset+len):
self.matchResult.append(str (name[i]))
return True
else:
return False
def _aRecursiveMatch(self, repeat, name, offset, len):
_LOG.debug (self.__class__.__name__ + "._aRecursiveMatch()" + " repeat: " + str(repeat) + " offset: " + str(offset) + " len: " + str(len) + " rMin: " + str(self.repeatMin) + " rMax: " + str(self.repeatMax))
tried = len
matcher = self.matcherList[0]
if 0 < len and repeat >= self.repeatMax:
_LOG.debug("Match Fail: Reach m_repeatMax && More components")
return False
if 0 == len and repeat < self.repeatMin:
_LOG.debug("Match Fail: No more components && have NOT reached m_repeatMin " + str(len) + ", " + str(self.repeatMin))
return False
if 0 == len and repeat >= self.repeatMin:
_LOG.debug("Match Succeed: No more components && reach m_repeatMin")
return True
while tried >= 0:
_LOG.debug("Attempt tried: " + str(tried))
if matcher.aggressiveMatch(name, offset, tried) and self._aRecursiveMatch(repeat + 1, name, offset + tried, len - tried):
return True;
_LOG.debug("Failed at tried: " + str(tried));
tried -= 1
return False
class RegexMatcher(BaseMatcher):
def __init__(self, expr, exact=True):
_LOG.debug(self.__class__.__name__ + ".Constructor")
super(RegexMatcher, self).__init__(expr, None, exact)
self.backRef = []
self.second_backRef = []
self.secondaryMatcher = None
errMsg = "Error: RegexTopMatcher Constructor: "
tmp_expr = self.expr
if '$' != tmp_expr[-1]:
tmp_expr = tmp_expr + "<.*>*";
else:
tmp_expr = tmp_expr[0:-1]
if '^' != tmp_expr[0]:
self.secondaryMatcher = PatternListMatcher("<.*>*" + tmp_expr, self.second_backRef, self.exact)
else:
tmp_expr = tmp_expr[1:]
_LOG.debug ("reconstructed expr " + tmp_expr);
self.primaryMatcher = PatternListMatcher(tmp_expr, self.backRef, self.exact)
def firstMatcher():
return None
def matchName(self, name):
_LOG.debug(self.__class__.__name__ + ".matchName")
self.secondaryUsed = False
res = self.primaryMatcher.match(name, 0, len(name))
self.matchResult += self.primaryMatcher.matchResult
if False == res and None != self.secondaryMatcher:
res = self.secondaryMatcher.match(name, 0, len(name))
self.matchResult += self.secondaryMatcher.matchResult
self.secondaryUsed = True
return res
def extract(self, rule):
_LOG.debug(self.__class__.__name__ + ".extract")
if not re.match('(\\\\[0-9]+)+$', rule):
raise RegexError("Wrong format of rule")
refs = rule.split('\\')
refs.pop(0)
backRef = self.backRef
if self.secondaryUsed:
backRef = self.second_backRef
result = []
for index in refs:
i = int(index) - 1
if len(backRef) <= i or 0 > i:
raise RegexError("Wrong back reference number!")
result += backRef[i].matchResult
return result
def matchN(self, name):
_LOG.debug(self.__class__.__name__ + ".matchN")
self.secondaryUsed = False
res = self.primaryMatcher.aggressiveMatch(name, 0, len(name))
self.matchResult += self.primaryMatcher.matchResult
if False == res and None != self.secondaryMatcher:
res = self.secondaryMatcher.aggressiveMatch(name, 0, len(name))
self.matchResult += self.secondaryMatcher.matchResult
self.secondaryUsed = True
return res
def expand (self, rule):
return self.extract (rule)
def match (pattern, name, flags=0):
"""
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding matches as a list. Return None if the string does not match the pattern.
"""
if not isinstance (name, Name):
raise TypeError ("name is not ndn.Name type")
m = RegexMatcher (pattern)
res = m.matchN (Name (name))
if not res:
return None
return m
| gpl-3.0 |
JasonLai256/plumbca | tests/test_backend.py | 1 | 9456 | # -*- coding:utf-8 -*-
"""
tests.backend
~~~~~~~~~~~~~
:copyright: (c) 2015 by Jason Lai.
:license: BSD, see LICENSE for more details.
"""
from faker import Factory
from functools import partial
fake = Factory.create()
def test_redis_backend_basic(rb, fake_manager, fake_coll):
fake_manager.collmap = {'t1': fake_coll, 't2': fake_coll}
for name, coll in fake_manager.collmap.items():
rb.set_collection_index(name, coll)
for name, coll in fake_manager.collmap.items():
pair = rb.get_collection_index(name)
assert pair == [name, fake_coll.__class__.__name__]
# ---------------------- check get all indexes ----------------------
rv = rb.get_collection_indexes()
matching = {'t1': '_t', 't2': '_t'}
assert rv == matching
# if name not exist get_collection_index should return None
pair = rb.get_collection_index('not-exists')
assert pair is None
def test_redis_backend_metadata(rb, fake_coll):
taggings = [fake.domain_name() for i in range(10)]
ts_pairs = [(exp, exp-100) for exp in range(200, 300, 10)]
first_ts, mid_ts, last_ts = ts_pairs[0][1], ts_pairs[4][1], ts_pairs[-1][1]
args = ['hello', 'world', 42]
# ---------------- check metadata set and query operation ----------------
for i, pair in enumerate(ts_pairs, 1):
exp, ts = pair
for t in taggings:
rb.set_collection_metadata(fake_coll, t, exp, ts, *args)
assert rb.get_collection_length(fake_coll) == [i]
rv = rb.query_collection_metadata(fake_coll, t, 0, 1000)
assert len(rv) == i
assert rv[i-1] == ([exp] + args, ts)
rv = rb.query_collection_metadata_tagging(fake_coll, 0, 1000)
assert len(rv) == i
assert len(rv[ts]) == len(taggings)
rv = rb.query_collection_metadata_all(fake_coll, 0, 1000)
assert len(rv) == i
assert len(rv[ts]) == len(taggings)
for info in rv[ts].values():
assert info == [exp] + args
# ------------------- check metadata delete operations -------------------
# delete one tagging info in first ts
rb.del_collection_metadata_by_range(fake_coll, taggings[0],
first_ts, first_ts)
rv = rb.query_collection_metadata(fake_coll, t, 0, 1000)
assert len(rv) == len(ts_pairs)
rv = rb.query_collection_metadata_tagging(fake_coll, 0, 1000)
assert len(rv) == len(ts_pairs)
assert len(rv[first_ts]) == len(taggings) - 1
assert len(rv[last_ts]) == len(rv[mid_ts]) == len(taggings)
assert rb.get_collection_length(fake_coll) == [len(taggings)]
# delete all the taggings in first ts
for t in taggings[1:]:
rb.del_collection_metadata_by_range(fake_coll, t, first_ts, first_ts)
rv = rb.query_collection_metadata(fake_coll, t, 0, 1000)
assert len(rv) == len(ts_pairs) - 1
rv = rb.query_collection_metadata_tagging(fake_coll, 0, 1000)
assert len(rv) == len(ts_pairs) - 1
assert first_ts not in rv
assert len(rv[last_ts]) == len(rv[mid_ts]) == len(taggings)
assert rb.get_collection_length(fake_coll) == [len(taggings) - 1]
# delete all taggings info in last five ts
for exp, ts in ts_pairs[-5:]:
for t in taggings:
rb.del_collection_metadata_by_range(fake_coll, t, ts, ts)
rv = rb.query_collection_metadata(fake_coll, t, 0, 1000)
assert len(rv) == len(ts_pairs) - 6
rv = rb.query_collection_metadata_tagging(fake_coll, 0, 1000)
assert len(rv) == len(ts_pairs) - 6
assert first_ts not in rv and last_ts not in rv
assert len(rv[mid_ts]) == len(taggings)
assert rb.get_collection_length(fake_coll) == [len(taggings) - 6]
# ------------------ check no metadata exists situations ------------------
# delete a not exists ts
rb.del_collection_metadata_by_range(fake_coll, taggings[4], 9999, 9999)
# delete a not exists tagging in mid_ts
rb.del_collection_metadata_by_range(fake_coll, taggings[4], mid_ts, mid_ts)
rb.del_collection_metadata_by_range(fake_coll, taggings[4], mid_ts, mid_ts)
# query a unexists ts
assert rb.query_collection_metadata(fake_coll, mid_ts, 9999, 9999) is None
assert rb.query_collection_metadata_tagging(fake_coll, 9999, 9999) is None
assert rb.query_collection_metadata_all(fake_coll, 9999, 9999) is None
def _add_inc_coll_item(rb, coll, tagging, ts, value):
rb.set_collection_metadata(coll, tagging, ts+100, ts)
rb.inc_coll_cache_set(coll, _mk_inc_coll_field(tagging, ts), value)
def _mk_inc_coll_field(tagging, ts):
field_key = '{}:{}'.format(ts, tagging)
return field_key
def _assert_inc_coll_cache_size(rb, coll, cache_len, md_len):
_md_len, _cache_len = rb.get_collection_length(coll, klass="IncreaseCollection")
assert _md_len == md_len
assert _cache_len == cache_len
def test_redis_backend_inc_coll(rb, fake_coll):
tagging, other_tagging = 'day', 'for_diff'
v = {i: i for i in range(20)}
timestamps = [100, 110, 120, 130, 140]
assert_cache_size = partial(_assert_inc_coll_cache_size, rb, fake_coll)
# ---------------- check the operation of item adding ----------------
for ts in timestamps:
_add_inc_coll_item(rb, fake_coll, tagging, ts, v)
# double adding for checking the logic of duplacate handle
for ts in timestamps:
_add_inc_coll_item(rb, fake_coll, tagging, ts, v)
# adding the other_tagging for the cache size check below
for ts in timestamps:
_add_inc_coll_item(rb, fake_coll, other_tagging, ts, v)
print('Success Adding datas...\n\n\n')
assert_cache_size(10, 5)
# ------------------ check the cache data get operations ------------------
fields = [_mk_inc_coll_field(tagging, ts) for ts in timestamps]
rv = rb.inc_coll_caches_get(fake_coll, *fields)
for r in rv:
assert r == v
rb.inc_coll_caches_del(fake_coll, *fields)
rv = rb.inc_coll_caches_get(fake_coll, *fields)
for r in rv:
assert r is None
assert_cache_size(5, 5)
# if no fields specified
assert rb.inc_coll_caches_get(fake_coll) == []
# ---------------- check for the inc_coll_keys_delete ----------------
assert_cache_size(5, 5)
rb.delete_collection_keys(fake_coll, klass="IncreaseCollection")
assert_cache_size(0, 0)
def test_redis_backend_unique_count_coll(rb, fake_coll):
items_num = 200
tagging = 'day'
v = {fake.uuid4() for i in range(items_num)}
timestamps = [100, 200, 300]
# ----------- check the operation of item adding and getting ----------
for ts in timestamps:
rv = rb.uniq_count_coll_cache_set(fake_coll, ts, tagging, v)
assert rv == items_num
rv = rb.uniq_count_coll_cache_set(fake_coll, ts, tagging, v)
assert rv == 0
rv = rb.uniq_count_coll_cache_get(fake_coll, tagging, timestamps)
for item in rv:
assert item == v
assert len(item) == items_num
rv = rb.uniq_count_coll_cache_get(fake_coll, tagging,
timestamps, count_only=True)
for count in rv:
assert count == items_num
# ---------------- check for the operation of deleting ----------------
rv = rb.uniq_count_coll_cache_del(fake_coll, tagging, timestamps[0:1])
assert rv == 1
rv = rb.uniq_count_coll_cache_get(fake_coll, tagging, timestamps[0:1])
assert rv == [set()]
rv = rb.uniq_count_coll_cache_get(fake_coll, tagging, timestamps[1:])
for item in rv:
assert item == v
assert len(item) == items_num
# uniq_count_coll_cache_pop 50 items
rv = rb.uniq_count_coll_cache_pop(fake_coll, tagging, timestamps[1:], 50)
for item in rv:
assert len(item) == 50
rv = rb.uniq_count_coll_cache_get(fake_coll, tagging, timestamps[1:])
for item in rv:
assert len(item) == items_num - 50
# delete remain items
rv = rb.uniq_count_coll_cache_del(fake_coll, tagging, timestamps[1:])
assert rv == 2
rv = rb.uniq_count_coll_cache_get(fake_coll, tagging, timestamps)
assert rv == [set(), set(), set()]
def test_redis_backend_sorted_count_coll(rb, fake_coll):
tagging = 'day'
v = {fake.uuid4(): i for i in range(200)}
v2 = [(member, score) for member, score in v.items()]
v2 = sorted(v2, key=lambda x: x[1])
timestamps = [100, 200, 300]
# ----------- check the operation of item adding and getting ----------
for ts in timestamps:
rv = rb.sorted_count_coll_cache_set(fake_coll, ts, tagging, v)
assert rv == 200
rv = rb.sorted_count_coll_cache_get(fake_coll, tagging, timestamps)
for item in rv:
assert item == v2
rv = rb.sorted_count_coll_cache_get(fake_coll, tagging,
timestamps, topN=100)
for item in rv:
assert item == v2[100:]
# ---------------- check for the operation of deleting ----------------
rv = rb.sorted_count_coll_cache_del(fake_coll, tagging, timestamps[0:1])
assert rv == 1
rv = rb.sorted_count_coll_cache_get(fake_coll, tagging, timestamps[0:1])
assert rv == [[]]
rv = rb.sorted_count_coll_cache_get(fake_coll, tagging, timestamps[1:])
for item in rv:
assert item == v2
rv = rb.sorted_count_coll_cache_del(fake_coll, tagging, timestamps[1:])
assert rv == 2
rv = rb.sorted_count_coll_cache_get(fake_coll, tagging, timestamps)
assert rv == [[], [], []]
| bsd-3-clause |
dwighthubbard/micropython-redis | tests/test_hash.py | 1 | 4592 | #!/usr/bin/env python3
"""
Tests to validate redis list functionality is working properly with micropython
"""
# Notes:
#
# 1. These tests should be run with a cpython interpreter with the redislite module installed.
# 2. The micropython executable should be accesible in the path.
import logging
import redis
import redislite
from unittest import main, TestCase
import uredis
class TestRedisConnection(TestCase):
redis_test_port = 7901
def setUp(self):
self.redis_server = redislite.Redis(serverconfig={'port': self.redis_test_port})
self.uredis_client = uredis.Redis(host='127.0.0.1', port=self.redis_test_port)
def tearDown(self):
if self.redis_server:
self.redis_server.shutdown()
def test_hset(self):
result = self.redis_server.hset("testkey", 'key', 'value')
uresult = self.uredis_client.hset("testkey2", 'key', 'value')
self.assertEqual(uresult, result)
def test_hdel(self, *args):
self.redis_server.hset("testkey", 'key', 'value')
result = self.redis_server.hdel("testkey", 'key', 'value')
self.redis_server.hset("testkey2", 'key', 'value')
uresult = self.uredis_client.hdel("testkey2", 'key', 'value')
self.assertEqual(uresult, result)
def test_hexists(self, *args):
self.redis_server.hset("testkey", 'key', 'value')
result = self.redis_server.hexists("testkey", 'key')
self.redis_server.hset("testkey2", 'key', 'value')
uresult = self.uredis_client.hexists("testkey2", 'key')
self.assertEqual(uresult, result)
def test_hget(self, *args):
self.redis_server.hset("testkey", 'key', 'value')
result = self.redis_server.hget("testkey", 'key')
self.redis_server.hset("testkey2", 'key', 'value')
uresult = self.uredis_client.hget("testkey2", 'key')
self.assertEqual(uresult, result)
def test_hgetall(self, *args):
self.redis_server.hset("testkey", 'key', 'value')
result = self.redis_server.hgetall("testkey")
self.redis_server.hset("testkey2", 'key', 'value')
uresult = self.uredis_client.hgetall("testkey2")
self.assertEqual(uresult, result)
def test_hincrby(self, *args):
self.redis_server.hset("testkey", 'key', 1)
result = self.redis_server.hincrby("testkey", 'key', 1)
self.redis_server.hset("testkey2", 'key', 1)
uresult = self.uredis_client.hincrby("testkey2", 'key', 1)
self.assertEqual(uresult, result)
def test_hincrbyfloat(self, *args):
self.redis_server.hset("testkey", 'key', 1.0)
result = self.redis_server.hincrbyfloat("testkey", 'key', .1)
self.redis_server.hset("testkey2", 'key', 1.0)
uresult = self.uredis_client.hincrbyfloat("testkey2", 'key', .1)
self.assertEqual(uresult, result)
def test_hkeys(self, *args):
self.redis_server.hset("testkey", 'key', 'value')
result = self.redis_server.hkeys("testkey")
uresult = self.uredis_client.hkeys("testkey")
self.assertEqual(uresult, result)
def test_hlen(self, *args):
self.redis_server.hset("testkey", 'key', 'value')
result = self.redis_server.hlen("testkey")
uresult = self.uredis_client.hlen("testkey")
self.assertEqual(uresult, result)
def test_hmget(self, *args):
self.redis_server.hset("testkey", 'key', 'value')
result = self.redis_server.hmget("testkey", 'key')
uresult = self.uredis_client.hmget("testkey", 'key')
self.assertEqual(uresult, result)
def test_hsetnx(self, *args):
result = self.redis_server.hsetnx("testkey", 'key', 'value')
uresult = self.uredis_client.hsetnx("testkey2", 'key', 'value')
self.assertEqual(uresult, result)
def hstrlen(self, *args):
result = self.redis_server.hstrlen("testkey", 'key', 'value')
uresult = self.uredis_client.hstrlen("testkey2", 'key', 'value')
self.assertEqual(uresult, result)
def hvals(self, *args):
result = self.redis_server.hset("testkey", 'key', 'value')
uresult = self.uredis_client.hset("testkey2", 'key', 'value')
self.assertEqual(uresult, result)
def hscan(self, *args):
result = self.redis_server.hset("testkey", 'key', 'value')
uresult = self.uredis_client.hset("testkey2", 'key', 'value')
self.assertEqual(uresult, result)
if __name__ == '__main__':
logger = logging.getLogger('redislite.client')
logger.setLevel(logging.INFO)
logger.propagate = False
main()
| mit |
jambolo/bitcoin | test/functional/rpc_dumptxoutset.py | 20 | 1928 | #!/usr/bin/env python3
# Copyright (c) 2019-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the generation of UTXO snapshots using `dumptxoutset`.
"""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
import hashlib
from pathlib import Path
class DumptxoutsetTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
"""Test a trivial usage of the dumptxoutset RPC command."""
node = self.nodes[0]
mocktime = node.getblockheader(node.getblockhash(0))['time'] + 1
node.setmocktime(mocktime)
node.generate(100)
FILENAME = 'txoutset.dat'
out = node.dumptxoutset(FILENAME)
expected_path = Path(node.datadir) / self.chain / FILENAME
assert expected_path.is_file()
assert_equal(out['coins_written'], 100)
assert_equal(out['base_height'], 100)
assert_equal(out['path'], str(expected_path))
# Blockhash should be deterministic based on mocked time.
assert_equal(
out['base_hash'],
'6fd417acba2a8738b06fee43330c50d58e6a725046c3d843c8dd7e51d46d1ed6')
with open(str(expected_path), 'rb') as f:
digest = hashlib.sha256(f.read()).hexdigest()
# UTXO snapshot hash should be deterministic based on mocked time.
assert_equal(
digest, 'be032e5f248264ba08e11099ac09dbd001f6f87ffc68bf0f87043d8146d50664')
# Specifying a path to an existing file will fail.
assert_raises_rpc_error(
-8, '{} already exists'.format(FILENAME), node.dumptxoutset, FILENAME)
if __name__ == '__main__':
DumptxoutsetTest().main()
| mit |
praekelt/hellomama-registration | registrations/management/commands/update_initial_sequence.py | 1 | 2934 | from os import environ
from django.core.management.base import BaseCommand, CommandError
from registrations.models import SubscriptionRequest
from seed_services_client import StageBasedMessagingApiClient
from ._utils import validate_and_return_url
class Command(BaseCommand):
help = ("This command will loop all subscription requests and find the "
"corresponding subscription in SBM and update the "
"initial_sequence_number field, we need this to fast forward the "
"subscription.")
def add_arguments(self, parser):
parser.add_argument(
'--sbm-url', dest='sbm_url', type=validate_and_return_url,
default=environ.get('STAGE_BASED_MESSAGING_URL'),
help=('The Stage Based Messaging Service to verify '
'subscriptions for.'))
parser.add_argument(
'--sbm-token', dest='sbm_token', type=str,
default=environ.get('STAGE_BASED_MESSAGING_TOKEN'),
help=('The Authorization token for the SBM Service'))
def handle(self, *args, **kwargs):
sbm_url = kwargs['sbm_url']
sbm_token = kwargs['sbm_token']
if not sbm_url:
raise CommandError(
'Please make sure either the STAGE_BASED_MESSAGING_URL '
'environment variable or --sbm-url is set.')
if not sbm_token:
raise CommandError(
'Please make sure either the STAGE_BASED_MESSAGING_TOKEN '
'environment variable or --sbm-token is set.')
sbm_client = StageBasedMessagingApiClient(sbm_token, sbm_url)
sub_requests = SubscriptionRequest.objects.all().iterator()
updated = 0
for sub_request in sub_requests:
subscriptions = sbm_client.get_subscriptions({
'identity': sub_request.identity,
'created_at__gt': sub_request.created_at,
'messageset': sub_request.messageset,
})
first = None
first_date = None
for sub in subscriptions['results']:
created_at = sub['created_at']
if not first_date or created_at < first_date:
first_date = created_at
first = sub
if first:
data = {
'initial_sequence_number': sub_request.next_sequence_number
}
sbm_client.update_subscription(first['id'], data)
updated += 1
else:
self.warning("Subscription not found: %s" %
(sub_request.identity,))
self.success('Updated %d subscriptions.' % (updated,))
def log(self, level, msg):
self.stdout.write(level(msg))
def warning(self, msg):
self.log(self.style.WARNING, msg)
def success(self, msg):
self.log(self.style.SUCCESS, msg)
| bsd-3-clause |
highco-groupe/odoo | addons/l10n_in_hr_payroll/report/report_payroll_advice.py | 374 | 3442 | #-*- coding:utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 OpenERP SA (<http://openerp.com>). All Rights Reserved
# d$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from datetime import datetime
from openerp.osv import osv
from openerp.report import report_sxw
from openerp.tools import amount_to_text_en
class payroll_advice_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(payroll_advice_report, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
'time': time,
'get_month': self.get_month,
'convert': self.convert,
'get_detail': self.get_detail,
'get_bysal_total': self.get_bysal_total,
})
self.context = context
def get_month(self, input_date):
payslip_pool = self.pool.get('hr.payslip')
res = {
'from_name': '', 'to_name': ''
}
slip_ids = payslip_pool.search(self.cr, self.uid, [('date_from','<=',input_date), ('date_to','>=',input_date)], context=self.context)
if slip_ids:
slip = payslip_pool.browse(self.cr, self.uid, slip_ids, context=self.context)[0]
from_date = datetime.strptime(slip.date_from, '%Y-%m-%d')
to_date = datetime.strptime(slip.date_to, '%Y-%m-%d')
res['from_name']= from_date.strftime('%d')+'-'+from_date.strftime('%B')+'-'+from_date.strftime('%Y')
res['to_name']= to_date.strftime('%d')+'-'+to_date.strftime('%B')+'-'+to_date.strftime('%Y')
return res
def convert(self, amount, cur):
return amount_to_text_en.amount_to_text(amount, 'en', cur);
def get_bysal_total(self):
return self.total_bysal
def get_detail(self, line_ids):
result = []
self.total_bysal = 0.00
for l in line_ids:
res = {}
res.update({
'name': l.employee_id.name,
'acc_no': l.name,
'ifsc_code': l.ifsc_code,
'bysal': l.bysal,
'debit_credit': l.debit_credit,
})
self.total_bysal += l.bysal
result.append(res)
return result
class wrapped_report_payroll_advice(osv.AbstractModel):
_name = 'report.l10n_in_hr_payroll.report_payrolladvice'
_inherit = 'report.abstract_report'
_template = 'l10n_in_hr_payroll.report_payrolladvice'
_wrapped_report_class = payroll_advice_report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
arborh/tensorflow | tensorflow/python/debug/cli/command_parser.py | 79 | 17451 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# ==============================================================================
"""Command parsing module for TensorFlow Debugger (tfdbg)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import ast
import re
import sys
_BRACKETS_PATTERN = re.compile(r"\[[^\]]*\]")
_QUOTES_PATTERN = re.compile(r"(\"[^\"]*\"|\'[^\']*\')")
_WHITESPACE_PATTERN = re.compile(r"\s+")
_NUMBER_PATTERN = re.compile(r"[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?")
class Interval(object):
"""Represents an interval between a start and end value."""
def __init__(self, start, start_included, end, end_included):
self.start = start
self.start_included = start_included
self.end = end
self.end_included = end_included
def contains(self, value):
if value < self.start or value == self.start and not self.start_included:
return False
if value > self.end or value == self.end and not self.end_included:
return False
return True
def __eq__(self, other):
return (self.start == other.start and
self.start_included == other.start_included and
self.end == other.end and
self.end_included == other.end_included)
def parse_command(command):
"""Parse command string into a list of arguments.
- Disregards whitespace inside double quotes and brackets.
- Strips paired leading and trailing double quotes in arguments.
- Splits the command at whitespace.
Nested double quotes and brackets are not handled.
Args:
command: (str) Input command.
Returns:
(list of str) List of arguments.
"""
command = command.strip()
if not command:
return []
brackets_intervals = [f.span() for f in _BRACKETS_PATTERN.finditer(command)]
quotes_intervals = [f.span() for f in _QUOTES_PATTERN.finditer(command)]
whitespaces_intervals = [
f.span() for f in _WHITESPACE_PATTERN.finditer(command)
]
if not whitespaces_intervals:
return [command]
arguments = []
idx0 = 0
for start, end in whitespaces_intervals + [(len(command), None)]:
# Skip whitespace stretches enclosed in brackets or double quotes.
if not any(interval[0] < start < interval[1]
for interval in brackets_intervals + quotes_intervals):
argument = command[idx0:start]
# Strip leading and trailing double quote if they are paired.
if (argument.startswith("\"") and argument.endswith("\"") or
argument.startswith("'") and argument.endswith("'")):
argument = argument[1:-1]
arguments.append(argument)
idx0 = end
return arguments
def extract_output_file_path(args):
"""Extract output file path from command arguments.
Args:
args: (list of str) command arguments.
Returns:
(list of str) Command arguments with the output file path part stripped.
(str or None) Output file path (if any).
Raises:
SyntaxError: If there is no file path after the last ">" character.
"""
if args and args[-1].endswith(">"):
raise SyntaxError("Redirect file path is empty")
elif args and args[-1].startswith(">"):
try:
_parse_interval(args[-1])
if len(args) > 1 and args[-2].startswith("-"):
output_file_path = None
else:
output_file_path = args[-1][1:]
args = args[:-1]
except ValueError:
output_file_path = args[-1][1:]
args = args[:-1]
elif len(args) > 1 and args[-2] == ">":
output_file_path = args[-1]
args = args[:-2]
elif args and args[-1].count(">") == 1:
gt_index = args[-1].index(">")
if gt_index > 0 and args[-1][gt_index - 1] == "=":
output_file_path = None
else:
output_file_path = args[-1][gt_index + 1:]
args[-1] = args[-1][:gt_index]
elif len(args) > 1 and args[-2].endswith(">"):
output_file_path = args[-1]
args = args[:-1]
args[-1] = args[-1][:-1]
else:
output_file_path = None
return args, output_file_path
def parse_tensor_name_with_slicing(in_str):
"""Parse tensor name, potentially suffixed by slicing string.
Args:
in_str: (str) Input name of the tensor, potentially followed by a slicing
string. E.g.: Without slicing string: "hidden/weights/Variable:0", with
slicing string: "hidden/weights/Variable:0[1, :]"
Returns:
(str) name of the tensor
(str) slicing string, if any. If no slicing string is present, return "".
"""
if in_str.count("[") == 1 and in_str.endswith("]"):
tensor_name = in_str[:in_str.index("[")]
tensor_slicing = in_str[in_str.index("["):]
else:
tensor_name = in_str
tensor_slicing = ""
return tensor_name, tensor_slicing
def validate_slicing_string(slicing_string):
"""Validate a slicing string.
Check if the input string contains only brackets, digits, commas and
colons that are valid characters in numpy-style array slicing.
Args:
slicing_string: (str) Input slicing string to be validated.
Returns:
(bool) True if and only if the slicing string is valid.
"""
return bool(re.search(r"^\[(\d|,|\s|:)+\]$", slicing_string))
def _parse_slices(slicing_string):
"""Construct a tuple of slices from the slicing string.
The string must be a valid slicing string.
Args:
slicing_string: (str) Input slicing string to be parsed.
Returns:
tuple(slice1, slice2, ...)
Raises:
ValueError: If tensor_slicing is not a valid numpy ndarray slicing str.
"""
parsed = []
for slice_string in slicing_string[1:-1].split(","):
indices = slice_string.split(":")
if len(indices) == 1:
parsed.append(int(indices[0].strip()))
elif 2 <= len(indices) <= 3:
parsed.append(
slice(*[
int(index.strip()) if index.strip() else None for index in indices
]))
else:
raise ValueError("Invalid tensor-slicing string.")
return tuple(parsed)
def parse_indices(indices_string):
"""Parse a string representing indices.
For example, if the input is "[1, 2, 3]", the return value will be a list of
indices: [1, 2, 3]
Args:
indices_string: (str) a string representing indices. Can optionally be
surrounded by a pair of brackets.
Returns:
(list of int): Parsed indices.
"""
# Strip whitespace.
indices_string = re.sub(r"\s+", "", indices_string)
# Strip any brackets at the two ends.
if indices_string.startswith("[") and indices_string.endswith("]"):
indices_string = indices_string[1:-1]
return [int(element) for element in indices_string.split(",")]
def parse_ranges(range_string):
"""Parse a string representing numerical range(s).
Args:
range_string: (str) A string representing a numerical range or a list of
them. For example:
"[-1.0,1.0]", "[-inf, 0]", "[[-inf, -1.0], [1.0, inf]]"
Returns:
(list of list of float) A list of numerical ranges parsed from the input
string.
Raises:
ValueError: If the input doesn't represent a range or a list of ranges.
"""
range_string = range_string.strip()
if not range_string:
return []
if "inf" in range_string:
range_string = re.sub(r"inf", repr(sys.float_info.max), range_string)
ranges = ast.literal_eval(range_string)
if isinstance(ranges, list) and not isinstance(ranges[0], list):
ranges = [ranges]
# Verify that ranges is a list of list of numbers.
for item in ranges:
if len(item) != 2:
raise ValueError("Incorrect number of elements in range")
elif not isinstance(item[0], (int, float)):
raise ValueError("Incorrect type in the 1st element of range: %s" %
type(item[0]))
elif not isinstance(item[1], (int, float)):
raise ValueError("Incorrect type in the 2nd element of range: %s" %
type(item[0]))
return ranges
def parse_memory_interval(interval_str):
"""Convert a human-readable memory interval to a tuple of start and end value.
Args:
interval_str: (`str`) A human-readable str representing an interval
(e.g., "[10kB, 20kB]", "<100M", ">100G"). Only the units "kB", "MB", "GB"
are supported. The "B character at the end of the input `str` may be
omitted.
Returns:
`Interval` object where start and end are in bytes.
Raises:
ValueError: if the input is not valid.
"""
str_interval = _parse_interval(interval_str)
interval_start = 0
interval_end = float("inf")
if str_interval.start:
interval_start = parse_readable_size_str(str_interval.start)
if str_interval.end:
interval_end = parse_readable_size_str(str_interval.end)
if interval_start > interval_end:
raise ValueError(
"Invalid interval %s. Start of interval must be less than or equal "
"to end of interval." % interval_str)
return Interval(interval_start, str_interval.start_included,
interval_end, str_interval.end_included)
def parse_time_interval(interval_str):
"""Convert a human-readable time interval to a tuple of start and end value.
Args:
interval_str: (`str`) A human-readable str representing an interval
(e.g., "[10us, 20us]", "<100s", ">100ms"). Supported time suffixes are
us, ms, s.
Returns:
`Interval` object where start and end are in microseconds.
Raises:
ValueError: if the input is not valid.
"""
str_interval = _parse_interval(interval_str)
interval_start = 0
interval_end = float("inf")
if str_interval.start:
interval_start = parse_readable_time_str(str_interval.start)
if str_interval.end:
interval_end = parse_readable_time_str(str_interval.end)
if interval_start > interval_end:
raise ValueError(
"Invalid interval %s. Start must be before end of interval." %
interval_str)
return Interval(interval_start, str_interval.start_included,
interval_end, str_interval.end_included)
def _parse_interval(interval_str):
"""Convert a human-readable interval to a tuple of start and end value.
Args:
interval_str: (`str`) A human-readable str representing an interval
(e.g., "[1M, 2M]", "<100k", ">100ms"). The items following the ">", "<",
">=" and "<=" signs have to start with a number (e.g., 3.0, -2, .98).
The same requirement applies to the items in the parentheses or brackets.
Returns:
Interval object where start or end can be None
if the range is specified as "<N" or ">N" respectively.
Raises:
ValueError: if the input is not valid.
"""
interval_str = interval_str.strip()
if interval_str.startswith("<="):
if _NUMBER_PATTERN.match(interval_str[2:].strip()):
return Interval(start=None, start_included=False,
end=interval_str[2:].strip(), end_included=True)
else:
raise ValueError("Invalid value string after <= in '%s'" % interval_str)
if interval_str.startswith("<"):
if _NUMBER_PATTERN.match(interval_str[1:].strip()):
return Interval(start=None, start_included=False,
end=interval_str[1:].strip(), end_included=False)
else:
raise ValueError("Invalid value string after < in '%s'" % interval_str)
if interval_str.startswith(">="):
if _NUMBER_PATTERN.match(interval_str[2:].strip()):
return Interval(start=interval_str[2:].strip(), start_included=True,
end=None, end_included=False)
else:
raise ValueError("Invalid value string after >= in '%s'" % interval_str)
if interval_str.startswith(">"):
if _NUMBER_PATTERN.match(interval_str[1:].strip()):
return Interval(start=interval_str[1:].strip(), start_included=False,
end=None, end_included=False)
else:
raise ValueError("Invalid value string after > in '%s'" % interval_str)
if (not interval_str.startswith(("[", "("))
or not interval_str.endswith(("]", ")"))):
raise ValueError(
"Invalid interval format: %s. Valid formats are: [min, max], "
"(min, max), <max, >min" % interval_str)
interval = interval_str[1:-1].split(",")
if len(interval) != 2:
raise ValueError(
"Incorrect interval format: %s. Interval should specify two values: "
"[min, max] or (min, max)." % interval_str)
start_item = interval[0].strip()
if not _NUMBER_PATTERN.match(start_item):
raise ValueError("Invalid first item in interval: '%s'" % start_item)
end_item = interval[1].strip()
if not _NUMBER_PATTERN.match(end_item):
raise ValueError("Invalid second item in interval: '%s'" % end_item)
return Interval(start=start_item,
start_included=(interval_str[0] == "["),
end=end_item,
end_included=(interval_str[-1] == "]"))
def parse_readable_size_str(size_str):
"""Convert a human-readable str representation to number of bytes.
Only the units "kB", "MB", "GB" are supported. The "B character at the end
of the input `str` may be omitted.
Args:
size_str: (`str`) A human-readable str representing a number of bytes
(e.g., "0", "1023", "1.1kB", "24 MB", "23GB", "100 G".
Returns:
(`int`) The parsed number of bytes.
Raises:
ValueError: on failure to parse the input `size_str`.
"""
size_str = size_str.strip()
if size_str.endswith("B"):
size_str = size_str[:-1]
if size_str.isdigit():
return int(size_str)
elif size_str.endswith("k"):
return int(float(size_str[:-1]) * 1024)
elif size_str.endswith("M"):
return int(float(size_str[:-1]) * 1048576)
elif size_str.endswith("G"):
return int(float(size_str[:-1]) * 1073741824)
else:
raise ValueError("Failed to parsed human-readable byte size str: \"%s\"" %
size_str)
def parse_readable_time_str(time_str):
"""Parses a time string in the format N, Nus, Nms, Ns.
Args:
time_str: (`str`) string consisting of an integer time value optionally
followed by 'us', 'ms', or 's' suffix. If suffix is not specified,
value is assumed to be in microseconds. (e.g. 100us, 8ms, 5s, 100).
Returns:
Microseconds value.
"""
def parse_positive_float(value_str):
value = float(value_str)
if value < 0:
raise ValueError(
"Invalid time %s. Time value must be positive." % value_str)
return value
time_str = time_str.strip()
if time_str.endswith("us"):
return int(parse_positive_float(time_str[:-2]))
elif time_str.endswith("ms"):
return int(parse_positive_float(time_str[:-2]) * 1e3)
elif time_str.endswith("s"):
return int(parse_positive_float(time_str[:-1]) * 1e6)
return int(parse_positive_float(time_str))
def evaluate_tensor_slice(tensor, tensor_slicing):
"""Call eval on the slicing of a tensor, with validation.
Args:
tensor: (numpy ndarray) The tensor value.
tensor_slicing: (str or None) Slicing of the tensor, e.g., "[:, 1]". If
None, no slicing will be performed on the tensor.
Returns:
(numpy ndarray) The sliced tensor.
Raises:
ValueError: If tensor_slicing is not a valid numpy ndarray slicing str.
"""
_ = tensor
if not validate_slicing_string(tensor_slicing):
raise ValueError("Invalid tensor-slicing string.")
return tensor[_parse_slices(tensor_slicing)]
def get_print_tensor_argparser(description):
"""Get an ArgumentParser for a command that prints tensor values.
Examples of such commands include print_tensor and print_feed.
Args:
description: Description of the ArgumentParser.
Returns:
An instance of argparse.ArgumentParser.
"""
ap = argparse.ArgumentParser(
description=description, usage=argparse.SUPPRESS)
ap.add_argument(
"tensor_name",
type=str,
help="Name of the tensor, followed by any slicing indices, "
"e.g., hidden1/Wx_plus_b/MatMul:0, "
"hidden1/Wx_plus_b/MatMul:0[1, :]")
ap.add_argument(
"-n",
"--number",
dest="number",
type=int,
default=-1,
help="0-based dump number for the specified tensor. "
"Required for tensor with multiple dumps.")
ap.add_argument(
"-r",
"--ranges",
dest="ranges",
type=str,
default="",
help="Numerical ranges to highlight tensor elements in. "
"Examples: -r 0,1e-8, -r [-0.1,0.1], "
"-r \"[[-inf, -0.1], [0.1, inf]]\"")
ap.add_argument(
"-a",
"--all",
dest="print_all",
action="store_true",
help="Print the tensor in its entirety, i.e., do not use ellipses.")
ap.add_argument(
"-s",
"--numeric_summary",
action="store_true",
help="Include summary for non-empty tensors of numeric (int*, float*, "
"complex*) and Boolean types.")
ap.add_argument(
"-w",
"--write_path",
type=str,
default="",
help="Path of the numpy file to write the tensor data to, using "
"numpy.save().")
return ap
| apache-2.0 |
timrae/anki | anki/models.py | 1 | 18761 | # -*- coding: utf-8 -*-
# Copyright: Damien Elmes <anki@ichi2.net>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import copy, re
from anki.utils import intTime, joinFields, splitFields, ids2str,\
checksum, json
from anki.lang import _
from anki.consts import *
from anki.hooks import runHook
import time
# Models
##########################################################################
# - careful not to add any lists/dicts/etc here, as they aren't deep copied
defaultModel = {
'sortf': 0,
'did': 1,
'latexPre': """\
\\documentclass[12pt]{article}
\\special{papersize=3in,5in}
\\usepackage[utf8]{inputenc}
\\usepackage{amssymb,amsmath}
\\pagestyle{empty}
\\setlength{\\parindent}{0in}
\\begin{document}
""",
'latexPost': "\\end{document}",
'mod': 0,
'usn': 0,
'vers': [], # FIXME: remove when other clients have caught up
'type': MODEL_STD,
'css': """\
.card {
font-family: arial;
font-size: 20px;
text-align: center;
color: black;
background-color: white;
}
"""
}
defaultField = {
'name': "",
'ord': None,
'sticky': False,
# the following alter editing, and are used as defaults for the
# template wizard
'rtl': False,
'font': "Arial",
'size': 20,
# reserved for future use
'media': [],
}
defaultTemplate = {
'name': "",
'ord': None,
'qfmt': "",
'afmt': "",
'did': None,
'bqfmt': "",
'bafmt': "",
# we don't define these so that we pick up system font size until set
#'bfont': "Arial",
#'bsize': 12,
}
class ModelManager(object):
# Saving/loading registry
#############################################################
def __init__(self, col):
self.col = col
def load(self, json_):
"Load registry from JSON."
self.changed = False
self.models = json.loads(json_)
def save(self, m=None, templates=False):
"Mark M modified if provided, and schedule registry flush."
if m and m['id']:
m['mod'] = intTime()
m['usn'] = self.col.usn()
self._updateRequired(m)
if templates:
self._syncTemplates(m)
self.changed = True
runHook("newModel")
def flush(self):
"Flush the registry if any models were changed."
if self.changed:
self.col.db.execute("update col set models = ?",
json.dumps(self.models))
self.changed = False
# Retrieving and creating models
#############################################################
def current(self, forDeck=True):
"Get current model."
m = self.get(self.col.decks.current().get('mid'))
if not forDeck or not m:
m = self.get(self.col.conf['curModel'])
return m or self.models.values()[0]
def setCurrent(self, m):
self.col.conf['curModel'] = m['id']
self.col.setMod()
def get(self, id):
"Get model with ID, or None."
id = str(id)
if id in self.models:
return self.models[id]
def all(self):
"Get all models."
return self.models.values()
def allNames(self):
return [m['name'] for m in self.all()]
def byName(self, name):
"Get model with NAME."
for m in self.models.values():
if m['name'] == name:
return m
def new(self, name):
"Create a new model, save it in the registry, and return it."
# caller should call save() after modifying
m = defaultModel.copy()
m['name'] = name
m['mod'] = intTime()
m['flds'] = []
m['tmpls'] = []
m['tags'] = []
m['id'] = None
return m
def rem(self, m):
"Delete model, and all its cards/notes."
self.col.modSchema()
current = self.current()['id'] == m['id']
# delete notes/cards
self.col.remCards(self.col.db.list("""
select id from cards where nid in (select id from notes where mid = ?)""",
m['id']))
# then the model
del self.models[str(m['id'])]
self.save()
# GUI should ensure last model is not deleted
if current:
self.setCurrent(self.models.values()[0])
def add(self, m):
self._setID(m)
self.update(m)
self.setCurrent(m)
self.save(m)
def ensureNameUnique(self, m):
for mcur in self.all():
if (mcur['name'] == m['name'] and
mcur['id'] != m['id']):
m['name'] += "-" + checksum(str(time.time()))[:5]
break
def update(self, m):
"Add or update an existing model. Used for syncing and merging."
self.ensureNameUnique(m)
self.models[str(m['id'])] = m
# mark registry changed, but don't bump mod time
self.save()
def _setID(self, m):
while 1:
id = str(intTime(1000))
if id not in self.models:
break
m['id'] = id
def have(self, id):
return str(id) in self.models
def ids(self):
return self.models.keys()
# Tools
##################################################
def nids(self, m):
"Note ids for M."
return self.col.db.list(
"select id from notes where mid = ?", m['id'])
def useCount(self, m):
"Number of note using M."
return self.col.db.scalar(
"select count() from notes where mid = ?", m['id'])
def tmplUseCount(self, m, ord):
return self.col.db.scalar("""
select count() from cards, notes where cards.nid = notes.id
and notes.mid = ? and cards.ord = ?""", m['id'], ord)
# Copying
##################################################
def copy(self, m):
"Copy, save and return."
m2 = copy.deepcopy(m)
m2['name'] = _("%s copy") % m2['name']
self.add(m2)
return m2
# Fields
##################################################
def newField(self, name):
f = defaultField.copy()
f['name'] = name
return f
def fieldMap(self, m):
"Mapping of field name -> (ord, field)."
return dict((f['name'], (f['ord'], f)) for f in m['flds'])
def fieldNames(self, m):
return [f['name'] for f in m['flds']]
def sortIdx(self, m):
return m['sortf']
def setSortIdx(self, m, idx):
assert idx >= 0 and idx < len(m['flds'])
self.col.modSchema()
m['sortf'] = idx
self.col.updateFieldCache(self.nids(m))
self.save(m)
def addField(self, m, field):
# only mod schema if model isn't new
if m['id']:
self.col.modSchema()
m['flds'].append(field)
self._updateFieldOrds(m)
self.save(m)
def add(fields):
fields.append("")
return fields
self._transformFields(m, add)
def remField(self, m, field):
self.col.modSchema()
# save old sort field
sortFldName = m['flds'][m['sortf']]['name']
idx = m['flds'].index(field)
m['flds'].remove(field)
# restore old sort field if possible, or revert to first field
m['sortf'] = 0
for c, f in enumerate(m['flds']):
if f['name'] == sortFldName:
m['sortf'] = c
break
self._updateFieldOrds(m)
def delete(fields):
del fields[idx]
return fields
self._transformFields(m, delete)
if m['flds'][m['sortf']]['name'] != sortFldName:
# need to rebuild sort field
self.col.updateFieldCache(self.nids(m))
# saves
self.renameField(m, field, None)
def moveField(self, m, field, idx):
self.col.modSchema()
oldidx = m['flds'].index(field)
if oldidx == idx:
return
# remember old sort field
sortf = m['flds'][m['sortf']]
# move
m['flds'].remove(field)
m['flds'].insert(idx, field)
# restore sort field
m['sortf'] = m['flds'].index(sortf)
self._updateFieldOrds(m)
self.save(m)
def move(fields, oldidx=oldidx):
val = fields[oldidx]
del fields[oldidx]
fields.insert(idx, val)
return fields
self._transformFields(m, move)
def renameField(self, m, field, newName):
self.col.modSchema()
pat = r'{{([:#^/]|[^:#/^}][^:}]*?:|)%s}}'
def wrap(txt):
def repl(match):
return '{{' + match.group(1) + txt + '}}'
return repl
for t in m['tmpls']:
for fmt in ('qfmt', 'afmt'):
if newName:
t[fmt] = re.sub(
pat % re.escape(field['name']), wrap(newName), t[fmt])
else:
t[fmt] = re.sub(
pat % re.escape(field['name']), "", t[fmt])
field['name'] = newName
self.save(m)
def _updateFieldOrds(self, m):
for c, f in enumerate(m['flds']):
f['ord'] = c
def _transformFields(self, m, fn):
# model hasn't been added yet?
if not m['id']:
return
r = []
for (id, flds) in self.col.db.execute(
"select id, flds from notes where mid = ?", m['id']):
r.append((joinFields(fn(splitFields(flds))),
intTime(), self.col.usn(), id))
self.col.db.executemany(
"update notes set flds=?,mod=?,usn=? where id = ?", r)
# Templates
##################################################
def newTemplate(self, name):
t = defaultTemplate.copy()
t['name'] = name
return t
def addTemplate(self, m, template):
"Note: should col.genCards() afterwards."
if m['id']:
self.col.modSchema()
m['tmpls'].append(template)
self._updateTemplOrds(m)
self.save(m)
def remTemplate(self, m, template):
"False if removing template would leave orphan notes."
assert len(m['tmpls']) > 1
# find cards using this template
ord = m['tmpls'].index(template)
cids = self.col.db.list("""
select c.id from cards c, notes f where c.nid=f.id and mid = ? and ord = ?""",
m['id'], ord)
# all notes with this template must have at least two cards, or we
# could end up creating orphaned notes
if self.col.db.scalar("""
select nid, count() from cards where
nid in (select nid from cards where id in %s)
group by nid
having count() < 2
limit 1""" % ids2str(cids)):
return False
# ok to proceed; remove cards
self.col.modSchema()
self.col.remCards(cids)
# shift ordinals
self.col.db.execute("""
update cards set ord = ord - 1, usn = ?, mod = ?
where nid in (select id from notes where mid = ?) and ord > ?""",
self.col.usn(), intTime(), m['id'], ord)
m['tmpls'].remove(template)
self._updateTemplOrds(m)
self.save(m)
return True
def _updateTemplOrds(self, m):
for c, t in enumerate(m['tmpls']):
t['ord'] = c
def moveTemplate(self, m, template, idx):
oldidx = m['tmpls'].index(template)
if oldidx == idx:
return
oldidxs = dict((id(t), t['ord']) for t in m['tmpls'])
m['tmpls'].remove(template)
m['tmpls'].insert(idx, template)
self._updateTemplOrds(m)
# generate change map
map = []
for t in m['tmpls']:
map.append("when ord = %d then %d" % (oldidxs[id(t)], t['ord']))
# apply
self.save(m)
self.col.db.execute("""
update cards set ord = (case %s end),usn=?,mod=? where nid in (
select id from notes where mid = ?)""" % " ".join(map),
self.col.usn(), intTime(), m['id'])
def _syncTemplates(self, m):
rem = self.col.genCards(self.nids(m))
# Model changing
##########################################################################
# - maps are ord->ord, and there should not be duplicate targets
# - newModel should be self if model is not changing
def change(self, m, nids, newModel, fmap, cmap):
self.col.modSchema()
assert newModel['id'] == m['id'] or (fmap and cmap)
if fmap:
self._changeNotes(nids, newModel, fmap)
if cmap:
self._changeCards(nids, m, newModel, cmap)
self.col.genCards(nids)
def _changeNotes(self, nids, newModel, map):
d = []
nfields = len(newModel['flds'])
for (nid, flds) in self.col.db.execute(
"select id, flds from notes where id in "+ids2str(nids)):
newflds = {}
flds = splitFields(flds)
for old, new in map.items():
newflds[new] = flds[old]
flds = []
for c in range(nfields):
flds.append(newflds.get(c, ""))
flds = joinFields(flds)
d.append(dict(nid=nid, flds=flds, mid=newModel['id'],
m=intTime(),u=self.col.usn()))
self.col.db.executemany(
"update notes set flds=:flds,mid=:mid,mod=:m,usn=:u where id = :nid", d)
self.col.updateFieldCache(nids)
def _changeCards(self, nids, oldModel, newModel, map):
d = []
deleted = []
for (cid, ord) in self.col.db.execute(
"select id, ord from cards where nid in "+ids2str(nids)):
# if the src model is a cloze, we ignore the map, as the gui
# doesn't currently support mapping them
if oldModel['type'] == MODEL_CLOZE:
new = ord
if newModel['type'] != MODEL_CLOZE:
# if we're mapping to a regular note, we need to check if
# the destination ord is valid
if len(newModel['tmpls']) <= ord:
new = None
else:
# mapping from a regular note, so the map should be valid
new = map[ord]
if new is not None:
d.append(dict(
cid=cid,new=new,u=self.col.usn(),m=intTime()))
else:
deleted.append(cid)
self.col.db.executemany(
"update cards set ord=:new,usn=:u,mod=:m where id=:cid",
d)
self.col.remCards(deleted)
# Schema hash
##########################################################################
def scmhash(self, m):
"Return a hash of the schema, to see if models are compatible."
s = ""
for f in m['flds']:
s += f['name']
for t in m['tmpls']:
s += t['name']
return checksum(s)
# Required field/text cache
##########################################################################
def _updateRequired(self, m):
if m['type'] == MODEL_CLOZE:
# nothing to do
return
req = []
flds = [f['name'] for f in m['flds']]
for t in m['tmpls']:
ret = self._reqForTemplate(m, flds, t)
req.append((t['ord'], ret[0], ret[1]))
m['req'] = req
def _reqForTemplate(self, m, flds, t):
a = []
b = []
for f in flds:
a.append("ankiflag")
b.append("")
data = [1, 1, m['id'], 1, t['ord'], "", joinFields(a)]
full = self.col._renderQA(data)['q']
data = [1, 1, m['id'], 1, t['ord'], "", joinFields(b)]
empty = self.col._renderQA(data)['q']
# if full and empty are the same, the template is invalid and there is
# no way to satisfy it
if full == empty:
return "none", [], []
type = 'all'
req = []
for i in range(len(flds)):
tmp = a[:]
tmp[i] = ""
data[6] = joinFields(tmp)
# if no field content appeared, field is required
if "ankiflag" not in self.col._renderQA(data)['q']:
req.append(i)
if req:
return type, req
# if there are no required fields, switch to any mode
type = 'any'
req = []
for i in range(len(flds)):
tmp = b[:]
tmp[i] = "1"
data[6] = joinFields(tmp)
# if not the same as empty, this field can make the card non-blank
if self.col._renderQA(data)['q'] != empty:
req.append(i)
return type, req
def availOrds(self, m, flds):
"Given a joined field string, return available template ordinals."
if m['type'] == MODEL_CLOZE:
return self._availClozeOrds(m, flds)
fields = {}
for c, f in enumerate(splitFields(flds)):
fields[c] = f.strip()
avail = []
for ord, type, req in m['req']:
# unsatisfiable template
if type == "none":
continue
# AND requirement?
elif type == "all":
ok = True
for idx in req:
if not fields[idx]:
# missing and was required
ok = False
break
if not ok:
continue
# OR requirement?
elif type == "any":
ok = False
for idx in req:
if fields[idx]:
ok = True
break
if not ok:
continue
avail.append(ord)
return avail
def _availClozeOrds(self, m, flds, allowEmpty=True):
sflds = splitFields(flds)
map = self.fieldMap(m)
ords = set()
matches = re.findall("{{[^}]*?cloze:(?:.*?:)*(.+?)}}", m['tmpls'][0]['qfmt'])
matches += re.findall("<%cloze:(.+?)%>", m['tmpls'][0]['qfmt'])
for fname in matches:
if fname not in map:
continue
ord = map[fname][0]
ords.update([int(m)-1 for m in re.findall(
"{{c(\d+)::.+?}}", sflds[ord])])
if -1 in ords:
ords.remove(-1)
if not ords and allowEmpty:
# empty clozes use first ord
return [0]
return list(ords)
# Sync handling
##########################################################################
def beforeUpload(self):
for m in self.all():
m['usn'] = 0
self.save()
| agpl-3.0 |
mrquim/repository.mrquim | repo/script.module.pycryptodome/lib/Crypto/SelfTest/Hash/test_SHA1.py | 5 | 2277 | # -*- coding: utf-8 -*-
#
# SelfTest/Hash/SHA1.py: Self-test for the SHA-1 hash function
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""Self-test suite for Crypto.Hash.SHA"""
from Crypto.Util.py3compat import *
# Test vectors from various sources
# This is a list of (expected_result, input[, description]) tuples.
test_data = [
# FIPS PUB 180-2, A.1 - "One-Block Message"
('a9993e364706816aba3e25717850c26c9cd0d89d', 'abc'),
# FIPS PUB 180-2, A.2 - "Multi-Block Message"
('84983e441c3bd26ebaae4aa1f95129e5e54670f1',
'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'),
# FIPS PUB 180-2, A.3 - "Long Message"
# ('34aa973cd4c4daa4f61eeb2bdbad27316534016f',
# 'a' * 10**6,
# '"a" * 10**6'),
# RFC 3174: Section 7.3, "TEST4" (multiple of 512 bits)
('dea356a2cddd90c7a7ecedc5ebb563934f460452',
'01234567' * 80,
'"01234567" * 80'),
]
def get_tests(config={}):
from Crypto.Hash import SHA1
from common import make_hash_tests
return make_hash_tests(SHA1, "SHA1", test_data,
digest_size=20,
oid="1.3.14.3.2.26")
if __name__ == '__main__':
import unittest
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
# vim:set ts=4 sw=4 sts=4 expandtab:
| gpl-2.0 |
MaxMorais/frappe | frappe/custom/doctype/custom_field/custom_field.py | 33 | 3162 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr
from frappe import _
from frappe.model.document import Document
class CustomField(Document):
def autoname(self):
self.set_fieldname()
self.name = self.dt + "-" + self.fieldname
def set_fieldname(self):
if not self.fieldname:
if not self.label:
frappe.throw(_("Label is mandatory"))
# remove special characters from fieldname
self.fieldname = filter(lambda x: x.isdigit() or x.isalpha() or '_',
cstr(self.label).lower().replace(' ','_'))
def validate(self):
if not self.idx:
self.idx = len(frappe.get_meta(self.dt).get("fields")) + 1
if not self.fieldname:
frappe.throw(_("Fieldname not set for Custom Field"))
def on_update(self):
frappe.clear_cache(doctype=self.dt)
if not self.flags.ignore_validate:
# validate field
from frappe.core.doctype.doctype.doctype import validate_fields_for_doctype
validate_fields_for_doctype(self.dt)
# create property setter to emulate insert after
self.create_property_setter()
# update the schema
# if not frappe.flags.in_test:
from frappe.model.db_schema import updatedb
updatedb(self.dt)
def on_trash(self):
# delete property setter entries
frappe.db.sql("""\
DELETE FROM `tabProperty Setter`
WHERE doc_type = %s
AND field_name = %s""",
(self.dt, self.fieldname))
frappe.clear_cache(doctype=self.dt)
def create_property_setter(self):
if not self.insert_after: return
dt_meta = frappe.get_meta(self.dt)
if not dt_meta.get_field(self.insert_after):
frappe.throw(_("Insert After field '{0}' mentioned in Custom Field '{1}', does not exist")
.format(self.insert_after, self.label), frappe.DoesNotExistError)
frappe.db.sql("""\
DELETE FROM `tabProperty Setter`
WHERE doc_type = %s
AND field_name = %s
AND property = 'previous_field'""", (self.dt, self.fieldname))
frappe.make_property_setter({
"doctype":self.dt,
"fieldname": self.fieldname,
"property": "previous_field",
"value": self.insert_after
}, validate_fields_for_doctype=False)
@frappe.whitelist()
def get_fields_label(doctype=None):
return [{"value": df.fieldname or "", "label": _(df.label or "")} for df in frappe.get_meta(doctype).get("fields")]
def create_custom_field_if_values_exist(doctype, df):
df = frappe._dict(df)
if df.fieldname in frappe.db.get_table_columns(doctype) and \
frappe.db.sql("""select count(*) from `tab{doctype}`
where ifnull({fieldname},'')!=''""".format(doctype=doctype, fieldname=df.fieldname))[0][0]:
create_custom_field(doctype, df)
def create_custom_field(doctype, df):
if not frappe.db.get_value("Custom Field", {"dt": doctype, "fieldname": df.fieldname}):
frappe.get_doc({
"doctype":"Custom Field",
"dt": doctype,
"permlevel": df.get("permlevel") or 0,
"label": df.get("label"),
"fieldname": df.get("fieldname"),
"fieldtype": df.get("fieldtype"),
"options": df.get("options"),
"insert_after": df.get("insert_after"),
"print_hide": df.get("print_hide")
}).insert()
| mit |
justinpotts/mozillians | mozillians/groups/models.py | 4 | 12236 | from django.core.exceptions import ValidationError
from django.db import models
from django.utils.timezone import now
from autoslug.fields import AutoSlugField
from funfactory.urlresolvers import reverse
from funfactory.utils import absolutify
from tower import ugettext as _
from tower import ugettext_lazy as _lazy
from mozillians.groups.managers import GroupBaseManager, GroupManager
from mozillians.groups.helpers import slugify
from mozillians.groups.tasks import email_membership_change, member_removed_email
from mozillians.users.tasks import update_basket_task
class GroupBase(models.Model):
name = models.CharField(db_index=True, max_length=50,
unique=True, verbose_name=_lazy(u'Name'))
url = models.SlugField(blank=True)
objects = GroupBaseManager()
class Meta:
abstract = True
ordering = ['name']
def clean(self):
"""Verify that name is unique in ALIAS_MODEL.
We have to duplicate code here and in
forms.GroupForm.clean_name due to bug
https://code.djangoproject.com/ticket/16986. To update when we
upgrade to Django 1.7.
"""
super(GroupBase, self).clean()
query = self.ALIAS_MODEL.objects.filter(name=self.name)
if self.pk:
query = query.exclude(alias=self)
if query.exists():
raise ValidationError({'name': _('This name already exists.')})
return self.name
@classmethod
def search(cls, query):
query = query.lower()
results = cls.objects.filter(aliases__name__contains=query)
results = results.distinct()
return results
def save(self, *args, **kwargs):
self.name = self.name.lower()
super(GroupBase, self).save()
if not self.url:
alias = self.ALIAS_MODEL.objects.create(name=self.name, alias=self)
self.url = alias.url
super(GroupBase, self).save()
def __unicode__(self):
return self.name
def merge_groups(self, group_list):
for group in group_list:
map(lambda x: self.add_member(x),
group.members.all())
group.aliases.update(alias=self)
group.delete()
def user_can_leave(self, userprofile):
return (
# some groups don't allow leaving
getattr(self, 'members_can_leave', True)
and
# curators cannot leave their own groups
getattr(self, 'curator', None) != userprofile
and
# only makes sense to leave a group they belong to (at least pending)
(self.has_member(userprofile=userprofile)
or self.has_pending_member(userprofile=userprofile))
)
def user_can_join(self, userprofile):
return (
# Must be vouched
userprofile.is_vouched
and
# some groups don't allow
(getattr(self, 'accepting_new_members', 'yes') != 'no')
and
# only makes sense to join if not already a member (full or pending)
not (self.has_member(userprofile=userprofile)
or self.has_pending_member(userprofile=userprofile))
)
# Read-only properties so clients don't care which subclasses have some fields
@property
def is_visible(self):
return getattr(self, 'visible', True)
def add_member(self, userprofile):
self.members.add(userprofile)
def remove_member(self, userprofile):
self.members.remove(userprofile)
def has_member(self, userprofile):
return self.members.filter(user=userprofile.user).exists()
def has_pending_member(self, userprofile):
# skills have no pending members, just members
return False
class GroupAliasBase(models.Model):
name = models.CharField(max_length=50, unique=True)
url = AutoSlugField(populate_from='name', unique=True,
editable=False, blank=True,
slugify=slugify)
class Meta:
abstract = True
class GroupAlias(GroupAliasBase):
alias = models.ForeignKey('Group', related_name='aliases')
class GroupMembership(models.Model):
"""
Through model for UserProfile <-> Group relationship
"""
# Possible membership statuses:
MEMBER = u'member'
PENDING = u'pending' # Has requested to join group, not a member yet
MEMBERSHIP_STATUS_CHOICES = (
(MEMBER, _lazy(u'Member')),
(PENDING, _lazy(u'Pending')),
)
userprofile = models.ForeignKey('users.UserProfile', db_index=True)
group = models.ForeignKey('groups.Group', db_index=True)
status = models.CharField(choices=MEMBERSHIP_STATUS_CHOICES, max_length=10)
date_joined = models.DateTimeField(null=True, blank=True)
class Meta:
unique_together = ('userprofile', 'group')
def __unicode__(self):
return u'%s in %s' % (self.userprofile, self.group)
class Group(GroupBase):
ALIAS_MODEL = GroupAlias
# Has a steward taken ownership of this group?
description = models.TextField(max_length=255,
verbose_name=_lazy(u'Description'),
default='', blank=True)
curator = models.ForeignKey('users.UserProfile',
blank=True, null=True,
on_delete=models.SET_NULL,
related_name='groups_curated')
irc_channel = models.CharField(
max_length=63,
verbose_name=_lazy(u'IRC Channel'),
help_text=_lazy(u'An IRC channel where this group is discussed (optional).'),
default='', blank=True)
website = models.URLField(
max_length=200, verbose_name=_lazy(u'Website'),
help_text=_lazy(u'A URL of a web site with more information about this group (optional).'),
default='', blank=True)
wiki = models.URLField(
max_length=200, verbose_name=_lazy(u'Wiki'),
help_text=_lazy(u'A URL of a wiki with more information about this group (optional).'),
default='', blank=True)
members_can_leave = models.BooleanField(default=True)
accepting_new_members = models.CharField(
verbose_name=_lazy(u'Accepting new members'),
choices=(
('yes', _lazy(u'Yes')),
('by_request', _lazy(u'By request')),
('no', _lazy(u'No')),
),
default='yes',
max_length=10
)
new_member_criteria = models.TextField(
max_length=255,
default='',
blank=True,
verbose_name=_lazy(u'New Member Criteria'),
help_text=_lazy(u'Specify the criteria you will use to decide whether or not '
u'you will accept a membership request.'))
functional_area = models.BooleanField(default=False)
visible = models.BooleanField(
default=True,
help_text=_lazy(u'Whether group is shown on the UI (in group lists, search, etc). Mainly '
u'intended to keep system groups like "staff" from cluttering up the '
u'interface.')
)
max_reminder = models.IntegerField(
default=0,
help_text=(u'The max PK of pending membership requests the last time we sent the '
u'curator a reminder')
)
objects = GroupManager()
@classmethod
def get_functional_areas(cls):
"""Return all visible groups that are functional areas."""
return cls.objects.visible().filter(functional_area=True)
@classmethod
def get_non_functional_areas(cls, **kwargs):
"""
Return all visible groups that are not functional areas.
Use kwargs to apply additional filtering to the groups.
"""
return cls.objects.visible().filter(functional_area=False, **kwargs)
@classmethod
def get_curated(cls):
"""Return all non-functional areas that are curated."""
return cls.get_non_functional_areas(curator__isnull=False)
@classmethod
def search(cls, query):
return super(Group, cls).search(query).visible()
def get_absolute_url(self):
return absolutify(reverse('groups:show_group', args=[self.url]))
def merge_groups(self, group_list):
for membership in GroupMembership.objects.filter(group__in=group_list):
# add_member will never demote someone, so just add them with the current membership
# level from the merging group and they'll end up with the highest level from
# either group.
self.add_member(membership.userprofile, membership.status)
for group in group_list:
group.aliases.update(alias=self)
group.delete()
def add_member(self, userprofile, status=GroupMembership.MEMBER):
"""
Add a user to this group. Optionally specify status other than member.
If user is already in the group with the given status, this is a no-op.
If user is already in the group with a different status, their status will
be updated if the change is a promotion. Otherwise, their status will not change.
"""
defaults = dict(status=status,
date_joined=now())
membership, created = GroupMembership.objects.get_or_create(userprofile=userprofile,
group=self,
defaults=defaults)
if created:
if status == GroupMembership.MEMBER:
# Joined
# Group is functional area, we want to sent this update to Basket
if self.functional_area:
update_basket_task.delay(userprofile.id)
else:
if membership.status != status:
# Status changed
old_status = membership.status
membership.status = status
if (old_status, status) == (GroupMembership.PENDING, GroupMembership.MEMBER):
# Request accepted
membership.save()
if self.functional_area:
# Group is functional area, we want to sent this update to Basket.
update_basket_task.delay(userprofile.id)
email_membership_change.delay(self.pk, userprofile.user.pk, old_status, status)
# else? never demote people from full member to requested, that doesn't make sense
def remove_member(self, userprofile, send_email=True):
try:
membership = GroupMembership.objects.get(group=self, userprofile=userprofile)
except GroupMembership.DoesNotExist:
return
old_status = membership.status
membership.delete()
# If group is functional area, we want to sent this update to Basket
if self.functional_area:
update_basket_task.delay(userprofile.id)
if old_status == GroupMembership.PENDING and send_email:
# Request denied
email_membership_change.delay(self.pk, userprofile.user.pk,
old_status, None)
elif old_status == GroupMembership.MEMBER and send_email:
# Member removed
member_removed_email.delay(self.pk, userprofile.user.pk)
def has_member(self, userprofile):
"""
Return True if this user is in this group with status MEMBER.
"""
return self.groupmembership_set.filter(userprofile=userprofile,
status=GroupMembership.MEMBER).exists()
def has_pending_member(self, userprofile):
"""
Return True if this user is in this group with status PENDING.
"""
return self.groupmembership_set.filter(userprofile=userprofile,
status=GroupMembership.PENDING).exists()
class SkillAlias(GroupAliasBase):
alias = models.ForeignKey('Skill', related_name='aliases')
class Meta:
verbose_name_plural = 'skill aliases'
class Skill(GroupBase):
ALIAS_MODEL = SkillAlias
| bsd-3-clause |
a-parhom/edx-platform | common/djangoapps/student/management/tests/test_manage_group.py | 50 | 7602 | """
Unit tests for user_management management commands.
"""
import sys
import ddt
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.management import call_command, CommandError
from django.test import TestCase
TEST_EMAIL = 'test@example.com'
TEST_GROUP = 'test-group'
TEST_USERNAME = 'test-user'
TEST_DATA = (
{},
{
TEST_GROUP: ['add_group', 'change_group', 'change_group'],
},
{
'other-group': ['add_group', 'change_group', 'change_group'],
},
)
@ddt.ddt
class TestManageGroupCommand(TestCase):
"""
Tests the `manage_group` command.
"""
def set_group_permissions(self, group_permissions):
"""
Sets up a before-state for groups and permissions in tests, which
can be checked afterward to ensure that a failed atomic
operation has not had any side effects.
"""
content_type = ContentType.objects.get_for_model(Group)
for group_name, permission_codenames in group_permissions.items():
group = Group.objects.create(name=group_name)
for codename in permission_codenames:
group.permissions.add(
Permission.objects.get(content_type=content_type, codename=codename) # pylint: disable=no-member
)
def check_group_permissions(self, group_permissions):
"""
Checks that the current state of the database matches the specified groups and
permissions.
"""
self.check_groups(group_permissions.keys())
for group_name, permission_codenames in group_permissions.items():
self.check_permissions(group_name, permission_codenames)
def check_groups(self, group_names):
"""
DRY helper.
"""
self.assertEqual(set(group_names), {g.name for g in Group.objects.all()}) # pylint: disable=no-member
def check_permissions(self, group_name, permission_codenames):
"""
DRY helper.
"""
self.assertEqual(
set(permission_codenames),
{p.codename for p in Group.objects.get(name=group_name).permissions.all()} # pylint: disable=no-member
)
@ddt.data(
*(
(data, args, exception)
for data in TEST_DATA
for args, exception in (
((), 'too few arguments' if sys.version_info.major == 2 else 'required: group_name'), # no group name
(('x' * 81,), 'invalid group name'), # invalid group name
((TEST_GROUP, 'some-other-group'), 'unrecognized arguments'), # multiple arguments
((TEST_GROUP, '--some-option', 'dummy'), 'unrecognized arguments') # unexpected option name
)
)
)
@ddt.unpack
def test_invalid_input(self, initial_group_permissions, command_args, exception_message):
"""
Ensures that invalid inputs result in errors with relevant output,
and that no persistent state is changed.
"""
self.set_group_permissions(initial_group_permissions)
with self.assertRaises(CommandError) as exc_context:
call_command('manage_group', *command_args)
self.assertIn(exception_message, str(exc_context.exception).lower())
self.check_group_permissions(initial_group_permissions)
@ddt.data(*TEST_DATA)
def test_invalid_permission(self, initial_group_permissions):
"""
Ensures that a permission that cannot be parsed or resolved results in
and error and that no persistent state is changed.
"""
self.set_group_permissions(initial_group_permissions)
# not parseable
with self.assertRaises(CommandError) as exc_context:
call_command('manage_group', TEST_GROUP, '--permissions', 'fail')
self.assertIn('invalid permission option', str(exc_context.exception).lower())
self.check_group_permissions(initial_group_permissions)
# not parseable
with self.assertRaises(CommandError) as exc_context:
call_command('manage_group', TEST_GROUP, '--permissions', 'f:a:i:l')
self.assertIn('invalid permission option', str(exc_context.exception).lower())
self.check_group_permissions(initial_group_permissions)
# invalid app label
with self.assertRaises(CommandError) as exc_context:
call_command('manage_group', TEST_GROUP, '--permissions', 'nonexistent-label:dummy-model:dummy-perm')
self.assertIn('no installed app', str(exc_context.exception).lower())
self.assertIn('nonexistent-label', str(exc_context.exception).lower())
self.check_group_permissions(initial_group_permissions)
# invalid model name
with self.assertRaises(CommandError) as exc_context:
call_command('manage_group', TEST_GROUP, '--permissions', 'auth:nonexistent-model:dummy-perm')
self.assertIn('nonexistent-model', str(exc_context.exception).lower())
self.check_group_permissions(initial_group_permissions)
# invalid model name
with self.assertRaises(CommandError) as exc_context:
call_command('manage_group', TEST_GROUP, '--permissions', 'auth:Group:nonexistent-perm')
self.assertIn('invalid permission codename', str(exc_context.exception).lower())
self.assertIn('nonexistent-perm', str(exc_context.exception).lower())
self.check_group_permissions(initial_group_permissions)
def test_group(self):
"""
Ensures that groups are created if they don't exist and reused if they do.
"""
self.check_groups([])
call_command('manage_group', TEST_GROUP)
self.check_groups([TEST_GROUP])
# check idempotency
call_command('manage_group', TEST_GROUP)
self.check_groups([TEST_GROUP])
def test_group_remove(self):
"""
Ensures that groups are removed if they exist and we exit cleanly otherwise.
"""
self.set_group_permissions({TEST_GROUP: ['add_group']})
self.check_groups([TEST_GROUP])
call_command('manage_group', TEST_GROUP, '--remove')
self.check_groups([])
# check idempotency
call_command('manage_group', TEST_GROUP, '--remove')
self.check_groups([])
def test_permissions(self):
"""
Ensures that permissions are set on the group as specified.
"""
self.check_groups([])
call_command('manage_group', TEST_GROUP, '--permissions', 'auth:Group:add_group')
self.check_groups([TEST_GROUP])
self.check_permissions(TEST_GROUP, ['add_group'])
# check idempotency
call_command('manage_group', TEST_GROUP, '--permissions', 'auth:Group:add_group')
self.check_groups([TEST_GROUP])
self.check_permissions(TEST_GROUP, ['add_group'])
# check adding a permission
call_command('manage_group', TEST_GROUP, '--permissions', 'auth:Group:add_group', 'auth:Group:change_group')
self.check_groups([TEST_GROUP])
self.check_permissions(TEST_GROUP, ['add_group', 'change_group'])
# check removing a permission
call_command('manage_group', TEST_GROUP, '--permissions', 'auth:Group:change_group')
self.check_groups([TEST_GROUP])
self.check_permissions(TEST_GROUP, ['change_group'])
# check removing all permissions
call_command('manage_group', TEST_GROUP)
self.check_groups([TEST_GROUP])
self.check_permissions(TEST_GROUP, [])
| agpl-3.0 |
Denisolt/Tensorflow_Chat_Bot | local/lib/python2.7/site-packages/tensorflow/python/training/device_setter.py | 6 | 7943 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# ==============================================================================
"""Device function for replicated training."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.core.framework import node_def_pb2
from tensorflow.python.framework import device as pydev
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import server_lib
class _RoundRobinStrategy(object):
"""Returns the next ps task index for placement in round-robin order.
This class is not to be used directly by users. See instead
`replica_device_setter()` below.
"""
def __init__(self, num_tasks):
"""Create a new `_RoundRobinStrategy`.
Args:
num_tasks: Number of ps tasks to cycle among.
"""
self._num_tasks = num_tasks
self._next_task = 0
def __call__(self, unused_op):
"""Choose a ps task index for the given `Operation`.
Args:
unused_op: An `Operation` to be placed on ps.
Returns:
The next ps task index to use for the `Operation`. Returns the next
index, in the range `[offset, offset + num_tasks)`.
"""
task = self._next_task
self._next_task = (self._next_task + 1) % self._num_tasks
return task
class _ReplicaDeviceChooser(object):
"""Class to choose devices for Ops in a replicated training setup.
This class is not to be used directly by users. See instead
`replica_device_setter()` below.
"""
def __init__(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops,
ps_strategy):
"""Create a new `_ReplicaDeviceChooser`.
Args:
ps_tasks: Number of tasks in the `ps` job.
ps_device: String. Name of the `ps` job.
worker_device: String. Name of the `worker` job.
merge_devices: Boolean. Set to True to allow merging of device specs.
ps_ops: List of strings representing `Operation` types that need to be
placed on `ps` devices.
ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by
`ps_ops`), that takes the `Operation` and returns the ps task index to
use.
"""
self._ps_tasks = ps_tasks
self._ps_device = ps_device
self._worker_device = worker_device
self._merge_devices = merge_devices
self._ps_ops = ps_ops
self._ps_strategy = ps_strategy
def device_function(self, op):
"""Choose a device for `op`.
Args:
op: an `Operation`.
Returns:
The device to use for the `Operation`.
"""
if not self._merge_devices and op.device:
return op.device
current_device = pydev.DeviceSpec.from_string(op.device or "")
spec = pydev.DeviceSpec()
if self._ps_tasks and self._ps_device:
node_def = op if isinstance(op, node_def_pb2.NodeDef) else op.node_def
if node_def.op in self._ps_ops:
device_string = "%s/task:%d" % (
self._ps_device, self._ps_strategy(op))
if self._merge_devices:
spec = pydev.DeviceSpec.from_string(device_string)
spec.merge_from(current_device)
return spec.to_string()
else:
return device_string
if self._worker_device:
if not self._merge_devices:
return self._worker_device
spec = pydev.DeviceSpec.from_string(self._worker_device)
if not self._merge_devices:
return ""
spec.merge_from(current_device)
return spec.to_string()
def replica_device_setter(ps_tasks=0, ps_device="/job:ps",
worker_device="/job:worker", merge_devices=True,
cluster=None, ps_ops=None, ps_strategy=None):
"""Return a `device function` to use when building a Graph for replicas.
Device Functions are used in `with tf.device(device_function):` statement to
automatically assign devices to `Operation` objects as they are constructed,
Device constraints are added from the inner-most context first, working
outwards. The merging behavior adds constraints to fields that are yet unset
by a more inner context. Currently the fields are (job, task, cpu/gpu).
If `cluster` is `None`, and `ps_tasks` is 0, the returned function is a no-op.
Otherwise, the value of `ps_tasks` is derived from `cluster`.
By default, only Variable ops are placed on ps tasks, and the placement
strategy is round-robin over all ps tasks. A custom `ps_strategy` may be used
to do more intelligent placement, such as
`tf.contrib.training.GreedyLoadBalancingStrategy`.
For example,
```python
# To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker
# jobs on hosts worker0, worker1 and worker2.
cluster_spec = {
"ps": ["ps0:2222", "ps1:2222"],
"worker": ["worker0:2222", "worker1:2222", "worker2:2222"]}
with tf.device(tf.replica_device_setter(cluster=cluster_spec)):
# Build your graph
v1 = tf.Variable(...) # assigned to /job:ps/task:0
v2 = tf.Variable(...) # assigned to /job:ps/task:1
v3 = tf.Variable(...) # assigned to /job:ps/task:0
# Run compute
```
Args:
ps_tasks: Number of tasks in the `ps` job. Ignored if `cluster` is
provided.
ps_device: String. Device of the `ps` job. If empty no `ps` job is used.
Defaults to `ps`.
worker_device: String. Device of the `worker` job. If empty no `worker`
job is used.
merge_devices: `Boolean`. If `True`, merges or only sets a device if the
device constraint is completely unset. merges device specification rather
than overriding them.
cluster: `ClusterDef` proto or `ClusterSpec`.
ps_ops: List of strings representing `Operation` types that need to be
placed on `ps` devices. If `None`, defaults to `["Variable"]`.
ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by
`ps_ops`), that takes the `Operation` and returns the ps task index to
use. If `None`, defaults to a round-robin strategy across all `ps`
devices.
Returns:
A function to pass to `tf.device()`.
Raises:
TypeError if `cluster` is not a dictionary or `ClusterDef` protocol buffer,
or if `ps_strategy` is provided but not a callable.
"""
if cluster is not None:
if isinstance(cluster, server_lib.ClusterSpec):
cluster_spec = cluster.as_dict()
else:
cluster_spec = server_lib.ClusterSpec(cluster).as_dict()
# Get ps_job_name from ps_device by striping "/job:".
ps_job_name = pydev.DeviceSpec.from_string(ps_device).job
if ps_job_name not in cluster_spec or cluster_spec[ps_job_name] is None:
return None
ps_tasks = len(cluster_spec[ps_job_name])
if ps_tasks == 0:
return None
if ps_ops is None:
# TODO(sherrym): Variables in the LOCAL_VARIABLES collection should not be
# placed in the parameter server.
ps_ops = ["Variable"]
if not merge_devices:
logging.warning(
"DEPRECATION: It is recommended to set merge_devices=true in "
"replica_device_setter")
if ps_strategy is None:
ps_strategy = _RoundRobinStrategy(ps_tasks)
if not six.callable(ps_strategy):
raise TypeError("ps_strategy must be callable")
chooser = _ReplicaDeviceChooser(
ps_tasks, ps_device, worker_device, merge_devices, ps_ops, ps_strategy)
return chooser.device_function
| gpl-3.0 |
slush0/trezor-signer | signer/protobuf_json.py | 1 | 5009 | # JSON serialization support for Google's protobuf Messages
# Copyright (c) 2009, Paul Dovbush
# All rights reserved.
# http://code.google.com/p/protobuf-json/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of <ORGANIZATION> nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
Provide serialization and de-serialization of Google's protobuf Messages into/from JSON format.
'''
# groups are deprecated and not supported;
# Note that preservation of unknown fields is currently not available for Python (c) google docs
# extensions is not supported from 0.0.5 (due to gpb2.3 changes)
__version__ = '0.0.5'
__author__ = 'Paul Dovbush <dpp@dpp.su>'
import json # py2.6+ TODO: add support for other JSON serialization modules
from google.protobuf.descriptor import FieldDescriptor as FD
class ParseError(Exception): pass
def json2pb(pb, js):
''' convert JSON string to google.protobuf.descriptor instance '''
for field in pb.DESCRIPTOR.fields:
if field.name not in js:
continue
if field.type == FD.TYPE_MESSAGE:
pass
elif field.type in _js2ftype:
ftype = _js2ftype[field.type]
else:
raise ParseError("Field %s.%s of type '%d' is not supported" % (pb.__class__.__name__, field.name, field.type,))
value = js[field.name]
if field.label == FD.LABEL_REPEATED:
pb_value = getattr(pb, field.name, None)
for v in value:
if field.type == FD.TYPE_MESSAGE:
json2pb(pb_value.add(), v)
else:
pb_value.append(ftype(v))
else:
if field.type == FD.TYPE_MESSAGE:
json2pb(getattr(pb, field.name, None), value)
else:
setattr(pb, field.name, ftype(value))
return pb
def pb2json(pb):
''' convert google.protobuf.descriptor instance to JSON string '''
js = {}
# fields = pb.DESCRIPTOR.fields #all fields
fields = pb.ListFields() # only filled (including extensions)
for field, value in fields:
if field.type == FD.TYPE_MESSAGE:
ftype = pb2json
elif field.type in _ftype2js:
ftype = _ftype2js[field.type]
else:
raise ParseError("Field %s.%s of type '%d' is not supported" % (pb.__class__.__name__, field.name, field.type,))
if field.label == FD.LABEL_REPEATED:
js_value = []
for v in value:
js_value.append(ftype(v))
else:
js_value = ftype(value)
js[field.name] = js_value
return js
_ftype2js = {
FD.TYPE_DOUBLE: float,
FD.TYPE_FLOAT: float,
FD.TYPE_INT64: long,
FD.TYPE_UINT64: long,
FD.TYPE_INT32: int,
FD.TYPE_FIXED64: float,
FD.TYPE_FIXED32: float,
FD.TYPE_BOOL: bool,
FD.TYPE_STRING: unicode,
# FD.TYPE_MESSAGE: pb2json, #handled specially
FD.TYPE_BYTES: lambda x: x.encode('string_escape'),
FD.TYPE_UINT32: int,
FD.TYPE_ENUM: int,
FD.TYPE_SFIXED32: float,
FD.TYPE_SFIXED64: float,
FD.TYPE_SINT32: int,
FD.TYPE_SINT64: long,
}
_js2ftype = {
FD.TYPE_DOUBLE: float,
FD.TYPE_FLOAT: float,
FD.TYPE_INT64: long,
FD.TYPE_UINT64: long,
FD.TYPE_INT32: int,
FD.TYPE_FIXED64: float,
FD.TYPE_FIXED32: float,
FD.TYPE_BOOL: bool,
FD.TYPE_STRING: unicode,
# FD.TYPE_MESSAGE: json2pb, #handled specially
FD.TYPE_BYTES: lambda x: x.decode('string_escape'),
FD.TYPE_UINT32: int,
FD.TYPE_ENUM: int,
FD.TYPE_SFIXED32: float,
FD.TYPE_SFIXED64: float,
FD.TYPE_SINT32: int,
FD.TYPE_SINT64: long,
}
| gpl-3.0 |
bzennn/blog_flask | python/lib/python3.5/site-packages/pip/_vendor/requests/packages/chardet/codingstatemachine.py | 2931 | 2318 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .constants import eStart
from .compat import wrap_ord
class CodingStateMachine:
def __init__(self, sm):
self._mModel = sm
self._mCurrentBytePos = 0
self._mCurrentCharLen = 0
self.reset()
def reset(self):
self._mCurrentState = eStart
def next_state(self, c):
# for each byte we get its class
# if it is first byte, we also get byte length
# PY3K: aBuf is a byte stream, so c is an int, not a byte
byteCls = self._mModel['classTable'][wrap_ord(c)]
if self._mCurrentState == eStart:
self._mCurrentBytePos = 0
self._mCurrentCharLen = self._mModel['charLenTable'][byteCls]
# from byte's class and stateTable, we get its next state
curr_state = (self._mCurrentState * self._mModel['classFactor']
+ byteCls)
self._mCurrentState = self._mModel['stateTable'][curr_state]
self._mCurrentBytePos += 1
return self._mCurrentState
def get_current_charlen(self):
return self._mCurrentCharLen
def get_coding_state_machine(self):
return self._mModel['name']
| gpl-3.0 |
pwkalana9/ARSDKBuildUtils | Utils/Python/Common_RemoveVersionsFromSo.py | 2 | 3418 | '''
Copyright (C) 2014 Parrot SA
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Parrot nor the names
of its contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
'''
from ARFuncs import *
import os
import shutil
import re
if sys.version_info < (3,):
range = xrange
def Common_RemoveVersionsFromSo(rootSo, soext, depLibs):
# This script needs rpl to be in the path
if not ARExistsInPath('rpl'):
ARLog('rpl is needed to strip versioning informations from shared object files')
return False
outputName = rootSo
inputName = rootSo
# Can't work on a lib if it does not exists
if not os.path.exists(inputName):
ARLog('%(inputName)s does not exists' % locals())
return False
# If the lib is not a symlink to the main library, assume it was already stripped of versioning symbols
# and remove input if different from output
if os.path.exists(outputName) and not os.path.islink(outputName):
if inputName is not outputName:
ARDeleteIfExists(inputName)
return True
DirName = os.path.dirname(inputName)
# Remove symlink and copy acutal lib
ActualName = os.readlink(inputName)
ARDeleteIfExists(outputName)
ARDeleteIfExists(inputName)
shutil.copy2(os.path.join(DirName, ActualName), outputName)
for BaseName in os.path.basename(inputName) and depLibs:
# Find other names
OtherNames = [ f for f in os.listdir(DirName) if BaseName in f and not f.endswith('.' + soext) ]
# Iterate over other names
for name in OtherNames:
# Compute new string to replace
lenDiff = len(name) - len(BaseName)
newString = BaseName
for i in range(lenDiff):
newString = newString + r'\0'
# Call rpl
if not ARExecute('rpl -e %(name)s "%(newString)s" %(outputName)s >/dev/null 2>&1' % locals()):
ARLog('Error while running rpl')
return False
return True
| bsd-3-clause |
else/mosquitto | test/broker/08-ssl-connect-cert-auth-expired.py | 7 | 1504 | #!/usr/bin/env python
# Test whether a valid CONNECT results in the correct CONNACK packet using an
# SSL connection with client certificates required.
import subprocess
import socket
import ssl
import sys
import time
if sys.version < '2.7':
print("WARNING: SSL not supported on Python 2.6")
exit(0)
import inspect, os, sys
# From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"..")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
import mosq_test
rc = 1
keepalive = 10
connect_packet = mosq_test.gen_connect("connect-success-test", keepalive=keepalive)
connack_packet = mosq_test.gen_connack(rc=0)
broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=1889)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", certfile="../ssl/client-expired.crt", keyfile="../ssl/client.key", cert_reqs=ssl.CERT_REQUIRED)
ssock.settimeout(20)
try:
ssock.connect(("localhost", 1888))
except ssl.SSLError as err:
if err.errno == 1:
rc = 0
else:
broker.terminate()
raise ValueError(err.errno)
finally:
time.sleep(0.5)
broker.terminate()
broker.wait()
if rc:
(stdo, stde) = broker.communicate()
print(stde)
exit(rc)
| bsd-3-clause |
wileeam/airflow | airflow/migrations/versions/338e90f54d61_more_logging_into_task_isntance.py | 7 | 1425 | #
# 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.
"""More logging into task_instance
Revision ID: 338e90f54d61
Revises: 13eb55f81627
Create Date: 2015-08-25 06:09:20.460147
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '338e90f54d61'
down_revision = '13eb55f81627'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('task_instance', sa.Column('operator', sa.String(length=1000), nullable=True))
op.add_column('task_instance', sa.Column('queued_dttm', sa.DateTime(), nullable=True))
def downgrade():
op.drop_column('task_instance', 'queued_dttm')
op.drop_column('task_instance', 'operator')
| apache-2.0 |
HiroIshikawa/21playground | learning/venv/lib/python3.5/site-packages/pip/_vendor/requests/api.py | 435 | 5415 | # -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a (`connect timeout, read timeout
<user/advanced.html#timeouts>`_) tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Usage::
>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]>
"""
session = sessions.Session()
response = session.request(method=method, url=url, **kwargs)
# By explicitly closing the session, we avoid leaving sockets open which
# can trigger a ResourceWarning in some cases, and look like a memory leak
# in others.
session.close()
return response
def get(url, params=None, **kwargs):
"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('get', url, params=params, **kwargs)
def options(url, **kwargs):
"""Sends a OPTIONS request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('options', url, **kwargs)
def head(url, **kwargs):
"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', False)
return request('head', url, **kwargs)
def post(url, data=None, json=None, **kwargs):
"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('post', url, data=data, json=json, **kwargs)
def put(url, data=None, **kwargs):
"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('put', url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('patch', url, data=data, **kwargs)
def delete(url, **kwargs):
"""Sends a DELETE request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('delete', url, **kwargs)
| mit |
vchudinov/dynamic_memory_networks_with_keras | attention_cells.py | 1 | 11757 | from tensorflow.python.ops import array_ops
from keras import backend as K
from keras import activations
from keras import initializers
from keras import regularizers
from keras import constraints
from keras.engine.topology import Layer
from keras import regularizers
class SoftAttnGRU(Layer):
def __init__(self,
units,
activation='sigmoid',
batch_size=0,
recurrent_activation='hard_sigmoid',
use_bias=True,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros',
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
dropout=0.,
recurrent_dropout=0.,
implementation=1,
return_sequences=False,
**kwargs):
"""Identical to keras.recurrent.GRUCell.
The difference comes from the computation in self.call
"""
super(SoftAttnGRU, self).__init__(**kwargs)
self.batch_size = batch_size
self.units = units
self.return_sequences = return_sequences
self.activation = activations.get(activation)
self.recurrent_activation = activations.get(recurrent_activation)
self.use_bias = use_bias
self.kernel_initializer = initializers.get(kernel_initializer)
self.recurrent_initializer = initializers.get(recurrent_initializer)
self.bias_initializer = initializers.get(bias_initializer)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.recurrent_regularizer = regularizers.get(recurrent_regularizer)
self.bias_regularizer = regularizers.get(bias_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.recurrent_constraint = constraints.get(recurrent_constraint)
self.bias_constraint = constraints.get(bias_constraint)
self.dropout = min(1., max(0., dropout))
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.implementation = implementation
self.state_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
self._input_map = {}
super(SoftAttnGRU, self).__init__(**kwargs)
def compute_output_shape(self, input_shape):
out = list(input_shape)
out[-1] = self.units
if self.return_sequences:
return out
else:
return (out[0], out[-1])
def build(self, input_shape):
input_dim = input_shape[-1] - 1
self.kernel = self.add_weight(shape=(input_dim, self.units * 3),
name='kernel',
initializer=self.kernel_initializer,
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint)
self.recurrent_kernel = self.add_weight(
shape=(self.units, self.units * 3),
name='recurrent_kernel',
initializer=self.recurrent_initializer,
regularizer=self.recurrent_regularizer,
constraint=self.recurrent_constraint)
if self.use_bias:
self.bias = self.add_weight(shape=(self.units * 3,),
name='bias',
initializer=self.bias_initializer,
regularizer=self.bias_regularizer,
constraint=self.bias_constraint)
else:
self.bias = None
self.kernel_z = self.kernel[:, :self.units]
self.recurrent_kernel_z = self.recurrent_kernel[:, :self.units]
self.kernel_r = self.kernel[:, self.units: self.units * 2]
self.recurrent_kernel_r = self.recurrent_kernel[:,
self.units:
self.units * 2]
self.kernel_h = self.kernel[:, self.units * 2:]
self.recurrent_kernel_h = self.recurrent_kernel[:, self.units * 2:]
if self.use_bias:
self.bias_z = self.bias[:self.units]
self.bias_r = self.bias[self.units: self.units * 2]
self.bias_h = self.bias[self.units * 2:]
else:
self.bias_z = None
self.bias_r = None
self.bias_h = None
super(SoftAttnGRU, self).build(input_shape)
def step(self, inputs, states, training=None):
"""Computes the output of a single step. Unlike the vanilla GRU, attention is applied to the
output, as per https://arxiv.org/pdf/1603.01417.pdf
----------
inputs : (K.Tensor)
A tensor of shape [batch_size, input_size+1]. The last element of each example is the
attention score.
states : (K.Tensor)
Initial (list) of states
training : (bool)
Whether the network is in training mode or not.
Returns
-------
(K.Tensor)
The output for the current step, modified by attention
"""
# Needs question as an input
x_i, attn_gate = array_ops.split(inputs,
num_or_size_splits=[self.units, 1], axis=1)
h_tm1 = states[0]
# dropout matrices for input units
dp_mask = self._dropout_mask
# dropout matrices for recurrent units
rec_dp_mask = self._recurrent_dropout_mask
if self.implementation == 1:
if 0. < self.dropout < 1.:
inputs_z = x_i * dp_mask[0]
inputs_r = x_i * dp_mask[1]
inputs_h = x_i * dp_mask[2]
else:
inputs_z = x_i
inputs_r = x_i
inputs_h = x_i
x_z = K.dot(inputs_z, self.kernel_z)
x_r = K.dot(inputs_r, self.kernel_r)
x_h = K.dot(inputs_h, self.kernel_h)
if self.use_bias:
x_z = K.bias_add(x_z, self.bias_z)
x_r = K.bias_add(x_r, self.bias_r)
x_h = K.bias_add(x_h, self.bias_h)
if 0. < self.recurrent_dropout < 1.:
h_tm1_z = h_tm1 * rec_dp_mask[0]
h_tm1_r = h_tm1 * rec_dp_mask[1]
h_tm1_h = h_tm1 * rec_dp_mask[2]
else:
h_tm1_z = h_tm1
h_tm1_r = h_tm1
h_tm1_h = h_tm1
z = self.recurrent_activation(
x_z + K.dot(h_tm1_z, self.recurrent_kernel_z))
r = self.recurrent_activation(
x_r + K.dot(h_tm1_r, self.recurrent_kernel_r))
hh = self.activation(x_h + K.dot(r * h_tm1_h,
self.recurrent_kernel_h))
else:
if 0. < self.dropout < 1.:
x_i *= dp_mask[0]
matrix_x = K.dot(x_i, self.kernel)
if self.use_bias:
matrix_x = K.bias_add(matrix_x, self.bias)
if 0. < self.recurrent_dropout < 1.:
h_tm1 *= rec_dp_mask[0]
matrix_inner = K.dot(h_tm1,
self.recurrent_kernel[:, :2 * self.units])
x_z = matrix_x[:, :self.units]
x_r = matrix_x[:, self.units: 2 * self.units]
recurrent_z = matrix_inner[:, :self.units]
recurrent_r = matrix_inner[:, self.units: 2 * self.units]
z = self.recurrent_activation(x_z + recurrent_z)
r = self.recurrent_activation(x_r + recurrent_r)
x_h = matrix_x[:, 2 * self.units:]
recurrent_h = K.dot(r * h_tm1,
self.recurrent_kernel[:, 2 * self.units:])
hh = self.activation(x_h + recurrent_h)
h = z * h_tm1 + (1 - z) * hh
# Attention modulated output.
h = attn_gate * h + (1 - attn_gate) * h_tm1
if 0 < self.dropout + self.recurrent_dropout:
if training is None:
h._uses_learning_phase = True
return h, [h]
def call(self, input_list, initial_state=None, mask=None, training=None):
inputs = input_list
self._generate_dropout_mask(inputs, training=training)
self._generate_recurrent_dropout_mask(inputs, training=training)
# if has_arg(self.layer.call, 'training'):
self.training = training
uses_learning_phase = False
# initial_state = self.get_initial_state(inputs)
last_output, outputs, _ = K.rnn(self.step,
inputs=inputs,
constants=[],
initial_states=[K.zeros(shape= [self.batch_size, self.units])],
#input_length=input_shape,
unroll=False)
if self.return_sequences:
y = outputs
else:
y = last_output
if (hasattr(self, 'activity_regularizer') and
self.activity_regularizer is not None):
regularization_loss = self.activity_regularizer(y)
self.add_loss(regularization_loss, inputs)
if uses_learning_phase:
y._uses_learning_phase = True
if self.return_sequences:
timesteps = input_shape[1]
new_time_steps = list(y.get_shape())
new_time_steps[1] = timesteps
y.set_shape(new_time_steps)
return y
def _generate_dropout_mask(self, inputs, training=None):
if 0 < self.dropout < 1:
ones = K.ones_like(K.squeeze(inputs[:, 0:1, :-1], axis=1))
def dropped_inputs():
return K.dropout(ones, self.dropout)
self._dropout_mask = [K.in_train_phase(
dropped_inputs,
ones,
training=training)
for _ in range(3)]
else:
self._dropout_mask = None
def _generate_recurrent_dropout_mask(self, inputs, training=None):
if 0 < self.recurrent_dropout < 1:
ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1)))
ones = K.tile(ones, (1, self.units))
def dropped_inputs():
return K.dropout(ones, self.dropout)
self._recurrent_dropout_mask = [K.in_train_phase(
dropped_inputs,
ones,
training=training)
for _ in range(3)]
else:
self._recurrent_dropout_mask = None
def get_initial_state(self, inputs):
return K.zeros(shape= [self.batch_size, self.units])
# build an all-zero tensor of shape (samples, output_dim)
# What the hell am I doing here?
# print("--------------------")
# initial_state = K.zeros_like(inputs) # (samples, timesteps, input_dim)
# print(initial_state.shape)
# initial_state = initial_state[:, :, :-1]
#initial_state = K.sum(initial_state, axis=(1, 2)) # (samples,)
#print(initial_state.shape)
#initial_state = K.expand_dims(initial_state) # (samples, 1)
#print(initial_state.shape)
#raise SystemExit
# if hasattr(self.state_size, '__len__'):
# return [K.tile(initial_state, [1, dim])
# for dim in self.state_size]
# else:
# return [K.tile(initial_state, [1, self.state_size])]
| gpl-3.0 |
crosswalk-project/chromium-crosswalk-efl | third_party/closure_linter/setup.py | 83 | 1324 | #!/usr/bin/env python
#
# Copyright 2010 The Closure Linter Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='closure_linter',
version='2.3.14',
description='Closure Linter',
license='Apache',
author='The Closure Linter Authors',
author_email='opensource@google.com',
url='http://code.google.com/p/closure-linter',
install_requires=['python-gflags'],
package_dir={'closure_linter': 'closure_linter'},
packages=['closure_linter', 'closure_linter.common'],
entry_points = {
'console_scripts': [
'gjslint = closure_linter.gjslint:main',
'fixjsstyle = closure_linter.fixjsstyle:main'
]
}
)
| bsd-3-clause |
UrcanProject/Urcan | lib/1.0.46.0/shaderc/third_party/googletest/googlemock/scripts/generator/cpp/gmock_class.py | 520 | 8293 | #!/usr/bin/env python
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate Google Mock classes from base classes.
This program will read in a C++ source file and output the Google Mock
classes for the specified classes. If no class is specified, all
classes in the source file are emitted.
Usage:
gmock_class.py header-file.h [ClassName]...
Output is sent to stdout.
"""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os
import re
import sys
from cpp import ast
from cpp import utils
# Preserve compatibility with Python 2.3.
try:
_dummy = set
except NameError:
import sets
set = sets.Set
_VERSION = (1, 0, 1) # The version of this script.
# How many spaces to indent. Can set me with the INDENT environment variable.
_INDENT = 2
def _GenerateMethods(output_lines, source, class_node):
function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL |
ast.FUNCTION_OVERRIDE)
ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
indent = ' ' * _INDENT
for node in class_node.body:
# We only care about virtual functions.
if (isinstance(node, ast.Function) and
node.modifiers & function_type and
not node.modifiers & ctor_or_dtor):
# Pick out all the elements we need from the original function.
const = ''
if node.modifiers & ast.FUNCTION_CONST:
const = 'CONST_'
return_type = 'void'
if node.return_type:
# Add modifiers like 'const'.
modifiers = ''
if node.return_type.modifiers:
modifiers = ' '.join(node.return_type.modifiers) + ' '
return_type = modifiers + node.return_type.name
template_args = [arg.name for arg in node.return_type.templated_types]
if template_args:
return_type += '<' + ', '.join(template_args) + '>'
if len(template_args) > 1:
for line in [
'// The following line won\'t really compile, as the return',
'// type has multiple template arguments. To fix it, use a',
'// typedef for the return type.']:
output_lines.append(indent + line)
if node.return_type.pointer:
return_type += '*'
if node.return_type.reference:
return_type += '&'
num_parameters = len(node.parameters)
if len(node.parameters) == 1:
first_param = node.parameters[0]
if source[first_param.start:first_param.end].strip() == 'void':
# We must treat T(void) as a function with no parameters.
num_parameters = 0
tmpl = ''
if class_node.templated_types:
tmpl = '_T'
mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl)
args = ''
if node.parameters:
# Due to the parser limitations, it is impossible to keep comments
# while stripping the default parameters. When defaults are
# present, we choose to strip them and comments (and produce
# compilable code).
# TODO(nnorwitz@google.com): Investigate whether it is possible to
# preserve parameter name when reconstructing parameter text from
# the AST.
if len([param for param in node.parameters if param.default]) > 0:
args = ', '.join(param.type.name for param in node.parameters)
else:
# Get the full text of the parameters from the start
# of the first parameter to the end of the last parameter.
start = node.parameters[0].start
end = node.parameters[-1].end
# Remove // comments.
args_strings = re.sub(r'//.*', '', source[start:end])
# Condense multiple spaces and eliminate newlines putting the
# parameters together on a single line. Ensure there is a
# space in an argument which is split by a newline without
# intervening whitespace, e.g.: int\nBar
args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
# Create the mock method definition.
output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name),
'%s%s(%s));' % (indent*3, return_type, args)])
def _GenerateMocks(filename, source, ast_list, desired_class_names):
processed_class_names = set()
lines = []
for node in ast_list:
if (isinstance(node, ast.Class) and node.body and
# desired_class_names being None means that all classes are selected.
(not desired_class_names or node.name in desired_class_names)):
class_name = node.name
parent_name = class_name
processed_class_names.add(class_name)
class_node = node
# Add namespace before the class.
if class_node.namespace:
lines.extend(['namespace %s {' % n for n in class_node.namespace]) # }
lines.append('')
# Add template args for templated classes.
if class_node.templated_types:
# TODO(paulchang): The AST doesn't preserve template argument order,
# so we have to make up names here.
# TODO(paulchang): Handle non-type template arguments (e.g.
# template<typename T, int N>).
template_arg_count = len(class_node.templated_types.keys())
template_args = ['T%d' % n for n in range(template_arg_count)]
template_decls = ['typename ' + arg for arg in template_args]
lines.append('template <' + ', '.join(template_decls) + '>')
parent_name += '<' + ', '.join(template_args) + '>'
# Add the class prolog.
lines.append('class Mock%s : public %s {' # }
% (class_name, parent_name))
lines.append('%spublic:' % (' ' * (_INDENT // 2)))
# Add all the methods.
_GenerateMethods(lines, source, class_node)
# Close the class.
if lines:
# If there are no virtual methods, no need for a public label.
if len(lines) == 2:
del lines[-1]
# Only close the class if there really is a class.
lines.append('};')
lines.append('') # Add an extra newline.
# Close the namespace.
if class_node.namespace:
for i in range(len(class_node.namespace)-1, -1, -1):
lines.append('} // namespace %s' % class_node.namespace[i])
lines.append('') # Add an extra newline.
if desired_class_names:
missing_class_name_list = list(desired_class_names - processed_class_names)
if missing_class_name_list:
missing_class_name_list.sort()
sys.stderr.write('Class(es) not found in %s: %s\n' %
(filename, ', '.join(missing_class_name_list)))
elif not processed_class_names:
sys.stderr.write('No class found in %s\n' % filename)
return lines
def main(argv=sys.argv):
if len(argv) < 2:
sys.stderr.write('Google Mock Class Generator v%s\n\n' %
'.'.join(map(str, _VERSION)))
sys.stderr.write(__doc__)
return 1
global _INDENT
try:
_INDENT = int(os.environ['INDENT'])
except KeyError:
pass
except:
sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
filename = argv[1]
desired_class_names = None # None means all classes in the source file.
if len(argv) >= 3:
desired_class_names = set(argv[2:])
source = utils.ReadFile(filename)
if source is None:
return 1
builder = ast.BuilderFromSource(source, filename)
try:
entire_ast = filter(None, builder.Generate())
except KeyboardInterrupt:
return
except:
# An error message was already printed since we couldn't parse.
sys.exit(1)
else:
lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
sys.stdout.write('\n'.join(lines))
if __name__ == '__main__':
main(sys.argv)
| gpl-3.0 |
benjixx/ansible | lib/ansible/plugins/action/set_fact.py | 59 | 1914 | # Copyright 2013 Dag Wieers <dag@wieers.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.six import iteritems
from ansible.plugins.action import ActionBase
from ansible.utils.boolean import boolean
from ansible.utils.vars import isidentifier
class ActionModule(ActionBase):
TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=None):
if task_vars is None:
task_vars = dict()
result = super(ActionModule, self).run(tmp, task_vars)
facts = dict()
if self._task.args:
for (k, v) in iteritems(self._task.args):
k = self._templar.template(k)
if not isidentifier(k):
result['failed'] = True
result['msg'] = "The variable name '%s' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores." % k
return result
if isinstance(v, basestring) and v.lower() in ('true', 'false', 'yes', 'no'):
v = boolean(v)
facts[k] = v
result['changed'] = False
result['ansible_facts'] = facts
return result
| gpl-3.0 |
beni55/sympy | sympy/printing/conventions.py | 94 | 2410 | """
A few practical conventions common to all printers.
"""
from __future__ import print_function, division
import re
import collections
def split_super_sub(text):
"""Split a symbol name into a name, superscripts and subscripts
The first part of the symbol name is considered to be its actual
'name', followed by super- and subscripts. Each superscript is
preceded with a "^" character or by "__". Each subscript is preceded
by a "_" character. The three return values are the actual name, a
list with superscripts and a list with subscripts.
>>> from sympy.printing.conventions import split_super_sub
>>> split_super_sub('a_x^1')
('a', ['1'], ['x'])
>>> split_super_sub('var_sub1__sup_sub2')
('var', ['sup'], ['sub1', 'sub2'])
"""
pos = 0
name = None
supers = []
subs = []
while pos < len(text):
start = pos + 1
if text[pos:pos + 2] == "__":
start += 1
pos_hat = text.find("^", start)
if pos_hat < 0:
pos_hat = len(text)
pos_usc = text.find("_", start)
if pos_usc < 0:
pos_usc = len(text)
pos_next = min(pos_hat, pos_usc)
part = text[pos:pos_next]
pos = pos_next
if name is None:
name = part
elif part.startswith("^"):
supers.append(part[1:])
elif part.startswith("__"):
supers.append(part[2:])
elif part.startswith("_"):
subs.append(part[1:])
else:
raise RuntimeError("This should never happen.")
# make a little exception when a name ends with digits, i.e. treat them
# as a subscript too.
m = re.match('(^[a-zA-Z]+)([0-9]+)$', name)
if m is not None:
name, sub = m.groups()
subs.insert(0, sub)
return name, supers, subs
def requires_partial(expr):
"""Return whether a partial derivative symbol is required for printing
This requires checking how many free variables there are,
filtering out the ones that are integers. Some expressions don't have
free variables. In that case, check its variable list explicitly to
get the context of the expression.
"""
if not isinstance(expr.free_symbols, collections.Iterable):
return len(set(expr.variables)) > 1
return sum(not s.is_integer for s in expr.free_symbols) > 1
| bsd-3-clause |
yyljlyy/kubernetes | cluster/juju/charms/trusty/kubernetes/hooks/hooks.py | 93 | 8164 | #!/usr/bin/env python
# Copyright 2015 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""
The main hook file that is called by Juju.
"""
import json
import httplib
import os
import time
import socket
import subprocess
import sys
import urlparse
from charmhelpers.core import hookenv, host
from kubernetes_installer import KubernetesInstaller
from path import path
from lib.registrator import Registrator
hooks = hookenv.Hooks()
@hooks.hook('api-relation-changed')
def api_relation_changed():
"""
On the relation to the api server, this function determines the appropriate
architecture and the configured version to copy the kubernetes binary files
from the kubernetes-master charm and installs it locally on this machine.
"""
hookenv.log('Starting api-relation-changed')
charm_dir = path(hookenv.charm_dir())
# Get the package architecture, rather than the from the kernel (uname -m).
arch = subprocess.check_output(['dpkg', '--print-architecture']).strip()
kubernetes_bin_dir = path('/opt/kubernetes/bin')
# Get the version of kubernetes to install.
version = subprocess.check_output(['relation-get', 'version']).strip()
print('Relation version: ', version)
if not version:
print('No version present in the relation.')
exit(0)
version_file = charm_dir / '.version'
if version_file.exists():
previous_version = version_file.text()
print('Previous version: ', previous_version)
if version == previous_version:
exit(0)
# Can not download binaries while the service is running, so stop it.
# TODO: Figure out a better way to handle upgraded kubernetes binaries.
for service in ('kubelet', 'proxy'):
if host.service_running(service):
host.service_stop(service)
command = ['relation-get', 'private-address']
# Get the kubernetes-master address.
server = subprocess.check_output(command).strip()
print('Kubernetes master private address: ', server)
installer = KubernetesInstaller(arch, version, server, kubernetes_bin_dir)
installer.download()
installer.install()
# Write the most recently installed version number to the file.
version_file.write_text(version)
relation_changed()
@hooks.hook('etcd-relation-changed',
'network-relation-changed')
def relation_changed():
"""Connect the parts and go :-)
"""
template_data = get_template_data()
# Check required keys
for k in ('etcd_servers', 'kubeapi_server'):
if not template_data.get(k):
print('Missing data for %s %s' % (k, template_data))
return
print('Running with\n%s' % template_data)
# Setup kubernetes supplemental group
setup_kubernetes_group()
# Register upstart managed services
for n in ('kubelet', 'proxy'):
if render_upstart(n, template_data) or not host.service_running(n):
print('Starting %s' % n)
host.service_restart(n)
# Register machine via api
print('Registering machine')
register_machine(template_data['kubeapi_server'])
# Save the marker (for restarts to detect prev install)
template_data.save()
def get_template_data():
rels = hookenv.relations()
template_data = hookenv.Config()
template_data.CONFIG_FILE_NAME = '.unit-state'
overlay_type = get_scoped_rel_attr('network', rels, 'overlay_type')
etcd_servers = get_rel_hosts('etcd', rels, ('hostname', 'port'))
api_servers = get_rel_hosts('api', rels, ('hostname', 'port'))
# kubernetes master isn't ha yet.
if api_servers:
api_info = api_servers.pop()
api_servers = 'http://%s:%s' % (api_info[0], api_info[1])
template_data['overlay_type'] = overlay_type
template_data['kubelet_bind_addr'] = _bind_addr(
hookenv.unit_private_ip())
template_data['proxy_bind_addr'] = _bind_addr(
hookenv.unit_get('public-address'))
template_data['kubeapi_server'] = api_servers
template_data['etcd_servers'] = ','.join([
'http://%s:%s' % (s[0], s[1]) for s in sorted(etcd_servers)])
template_data['identifier'] = os.environ['JUJU_UNIT_NAME'].replace(
'/', '-')
return _encode(template_data)
def _bind_addr(addr):
if addr.replace('.', '').isdigit():
return addr
try:
return socket.gethostbyname(addr)
except socket.error:
raise ValueError('Could not resolve private address')
def _encode(d):
for k, v in d.items():
if isinstance(v, unicode):
d[k] = v.encode('utf8')
return d
def get_scoped_rel_attr(rel_name, rels, attr):
private_ip = hookenv.unit_private_ip()
for r, data in rels.get(rel_name, {}).items():
for unit_id, unit_data in data.items():
if unit_data.get('private-address') != private_ip:
continue
if unit_data.get(attr):
return unit_data.get(attr)
def get_rel_hosts(rel_name, rels, keys=('private-address',)):
hosts = []
for r, data in rels.get(rel_name, {}).items():
for unit_id, unit_data in data.items():
if unit_id == hookenv.local_unit():
continue
values = [unit_data.get(k) for k in keys]
if not all(values):
continue
hosts.append(len(values) == 1 and values[0] or values)
return hosts
def render_upstart(name, data):
tmpl_path = os.path.join(
os.environ.get('CHARM_DIR'), 'files', '%s.upstart.tmpl' % name)
with open(tmpl_path) as fh:
tmpl = fh.read()
rendered = tmpl % data
tgt_path = '/etc/init/%s.conf' % name
if os.path.exists(tgt_path):
with open(tgt_path) as fh:
contents = fh.read()
if contents == rendered:
return False
with open(tgt_path, 'w') as fh:
fh.write(rendered)
return True
def register_machine(apiserver, retry=False):
parsed = urlparse.urlparse(apiserver)
# identity = hookenv.local_unit().replace('/', '-')
private_address = hookenv.unit_private_ip()
with open('/proc/meminfo') as fh:
info = fh.readline()
mem = info.strip().split(':')[1].strip().split()[0]
cpus = os.sysconf('SC_NPROCESSORS_ONLN')
# https://github.com/kubernetes/kubernetes/blob/master/docs/admin/node.md
registration_request = Registrator()
registration_request.data['kind'] = 'Node'
registration_request.data['id'] = private_address
registration_request.data['name'] = private_address
registration_request.data['metadata']['name'] = private_address
registration_request.data['spec']['capacity']['mem'] = mem + ' K'
registration_request.data['spec']['capacity']['cpu'] = cpus
registration_request.data['spec']['externalID'] = private_address
registration_request.data['status']['hostIP'] = private_address
response, result = registration_request.register(parsed.hostname,
parsed.port,
'/api/v1/nodes')
print(response)
try:
registration_request.command_succeeded(response, result)
except ValueError:
# This happens when we have already registered
# for now this is OK
pass
def setup_kubernetes_group():
output = subprocess.check_output(['groups', 'kubernetes'])
# TODO: check group exists
if 'docker' not in output:
subprocess.check_output(
['usermod', '-a', '-G', 'docker', 'kubernetes'])
if __name__ == '__main__':
hooks.execute(sys.argv)
| apache-2.0 |
jostmey/rwa | length_problem_1000/rwa_model/train.py | 1 | 5669 | #!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2017-01-01 (This is my new year's resolution)
# Purpose: Train recurrent neural network
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import os
import numpy as np
import tensorflow as tf
import dataplumbing as dp
##########################################################################################
# Settings
##########################################################################################
# Model settings
#
num_features = dp.train.num_features
max_steps = dp.train.max_length
num_cells = 250
num_classes = dp.train.num_classes
activation = tf.nn.tanh
initialization_factor = 1.0
# Training parameters
#
num_iterations = 20000
batch_size = 100
learning_rate = 0.001
##########################################################################################
# Model
##########################################################################################
# Inputs
#
x = tf.placeholder(tf.float32, [batch_size, max_steps, num_features]) # Features
l = tf.placeholder(tf.int32, [batch_size]) # Sequence length
y = tf.placeholder(tf.float32, [batch_size]) # Labels
# Trainable parameters
#
s = tf.Variable(tf.random_normal([num_cells], stddev=np.sqrt(initialization_factor))) # Determines initial state
W_g = tf.Variable(
tf.random_uniform(
[num_features+num_cells, num_cells],
minval=-np.sqrt(6.0*initialization_factor/(num_features+2.0*num_cells)),
maxval=np.sqrt(6.0*initialization_factor/(num_features+2.0*num_cells))
)
)
b_g = tf.Variable(tf.zeros([num_cells]))
W_u = tf.Variable(
tf.random_uniform(
[num_features, num_cells],
minval=-np.sqrt(6.0*initialization_factor/(num_features+num_cells)),
maxval=np.sqrt(6.0*initialization_factor/(num_features+num_cells))
)
)
b_u = tf.Variable(tf.zeros([num_cells]))
W_a = tf.Variable(
tf.random_uniform(
[num_features+num_cells, num_cells],
minval=-np.sqrt(6.0*initialization_factor/(num_features+2.0*num_cells)),
maxval=np.sqrt(6.0*initialization_factor/(num_features+2.0*num_cells))
)
)
W_o = tf.Variable(
tf.random_uniform(
[num_cells, num_classes],
minval=-np.sqrt(6.0*initialization_factor/(num_cells+num_classes)),
maxval=np.sqrt(6.0*initialization_factor/(num_cells+num_classes))
)
)
b_o = tf.Variable(tf.zeros([num_classes]))
# Internal states
#
n = tf.zeros([batch_size, num_cells])
d = tf.zeros([batch_size, num_cells])
h = tf.zeros([batch_size, num_cells])
a_max = tf.fill([batch_size, num_cells], -1E38) # Start off with lowest number possible
# Define model
#
h += activation(tf.expand_dims(s, 0))
for i in range(max_steps):
x_step = x[:,i,:]
xh_join = tf.concat(axis=1, values=[x_step, h]) # Combine the features and hidden state into one tensor
u = tf.matmul(x_step, W_u)+b_u
g = tf.matmul(xh_join, W_g)+b_g
a = tf.matmul(xh_join, W_a) # The bias term when factored out of the numerator and denominator cancels and is unnecessary
z = tf.multiply(u, tf.nn.tanh(g))
a_newmax = tf.maximum(a_max, a)
exp_diff = tf.exp(a_max-a_newmax)
exp_scaled = tf.exp(a-a_newmax)
n = tf.multiply(n, exp_diff)+tf.multiply(z, exp_scaled) # Numerically stable update of numerator
d = tf.multiply(d, exp_diff)+exp_scaled # Numerically stable update of denominator
h_new = activation(tf.div(n, d))
a_max = a_newmax
h = tf.where(tf.greater(l, i), h_new, h) # Use new hidden state only if the sequence length has not been exceeded
ly = tf.matmul(h, W_o)+b_o
ly_flat = tf.reshape(ly, [batch_size])
py = tf.nn.sigmoid(ly_flat)
##########################################################################################
# Optimizer/Analyzer
##########################################################################################
# Cost function and optimizer
#
cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=ly_flat, labels=y)) # Cross-entropy cost function
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
# Evaluate performance
#
correct = tf.equal(tf.round(py), tf.round(y))
accuracy = 100.0*tf.reduce_mean(tf.cast(correct, tf.float32))
##########################################################################################
# Train
##########################################################################################
# Operation to initialize session
#
initializer = tf.global_variables_initializer()
# Open session
#
with tf.Session() as session:
# Initialize variables
#
session.run(initializer)
# Each training session represents one batch
#
for iteration in range(num_iterations):
# Grab a batch of training data
#
xs, ls, ys = dp.train.batch(batch_size)
feed = {x: xs, l: ls, y: ys}
# Update parameters
#
out = session.run((cost, accuracy, optimizer), feed_dict=feed)
print('Iteration:', iteration, 'Dataset:', 'train', 'Cost:', out[0]/np.log(2.0), 'Accuracy:', out[1])
# Periodically run model on test data
#
if iteration%100 == 0:
# Grab a batch of test data
#
xs, ls, ys = dp.test.batch(batch_size)
feed = {x: xs, l: ls, y: ys}
# Run model
#
out = session.run((cost, accuracy), feed_dict=feed)
print('Iteration:', iteration, 'Dataset:', 'test', 'Cost:', out[0]/np.log(2.0), 'Accuracy:', out[1])
# Save the trained model
#
os.makedirs('bin', exist_ok=True)
saver = tf.train.Saver()
saver.save(session, 'bin/train.ckpt')
| bsd-3-clause |
ShoRit/shipping-costs-sample | v2/lib/python2.7/site-packages/pip/_vendor/colorama/initialise.py | 485 | 1917 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import atexit
import contextlib
import sys
from .ansitowin32 import AnsiToWin32
orig_stdout = None
orig_stderr = None
wrapped_stdout = None
wrapped_stderr = None
atexit_done = False
def reset_all():
if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
AnsiToWin32(orig_stdout).reset_all()
def init(autoreset=False, convert=None, strip=None, wrap=True):
if not wrap and any([autoreset, convert, strip]):
raise ValueError('wrap=False conflicts with any other arg=True')
global wrapped_stdout, wrapped_stderr
global orig_stdout, orig_stderr
orig_stdout = sys.stdout
orig_stderr = sys.stderr
if sys.stdout is None:
wrapped_stdout = None
else:
sys.stdout = wrapped_stdout = \
wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
if sys.stderr is None:
wrapped_stderr = None
else:
sys.stderr = wrapped_stderr = \
wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
global atexit_done
if not atexit_done:
atexit.register(reset_all)
atexit_done = True
def deinit():
if orig_stdout is not None:
sys.stdout = orig_stdout
if orig_stderr is not None:
sys.stderr = orig_stderr
@contextlib.contextmanager
def colorama_text(*args, **kwargs):
init(*args, **kwargs)
try:
yield
finally:
deinit()
def reinit():
if wrapped_stdout is not None:
sys.stdout = wrapped_stdout
if wrapped_stderr is not None:
sys.stderr = wrapped_stderr
def wrap_stream(stream, convert, strip, autoreset, wrap):
if wrap:
wrapper = AnsiToWin32(stream,
convert=convert, strip=strip, autoreset=autoreset)
if wrapper.should_wrap():
stream = wrapper.stream
return stream
| apache-2.0 |
nitsas/codejamsolutions | Speaking in Tongues/GooglereseTranslator.py | 1 | 2454 | """
GooglereseTranslator class for the Speaking in Tongues problem
for Google Code Jam 2012
Qualification
Link to problem description:
http://code.google.com/codejam/contest/1460488/dashboard#s=p0
author:
Christos Nitsas
(chrisn654)
language:
Python 3.2.1
date:
April, 2012
"""
from string import ascii_lowercase
class CantGuessMapFromExamplesError(Exception):
def __init__(self):
self.value = "Not enough examples! (missing more than one letter)"
def __str__(self):
return repr(self.value)
def guess_map_from_examples(examples):
"""
Guess a letter-mapping-dictionary from the given examples.
Assumptions:
- the mapping is one-to-one and onto
- the examples only contain lowercase ascii letters and spaces
- the examples are valid (no contradictions)
"""
result = {}
for googlerese_string, english_string in examples.items():
result.update(zip(googlerese_string, english_string))
# make sure that space maps to space
result[' '] = ' '
missing_letters = set(ascii_lowercase + " ") - set(result.keys())
if len(missing_letters) > 1:
raise(CantGuessMapFromExamplesError)
elif len(missing_letters) == 1:
# one letter is missing but, since the mapping is one-to-one and
# onto, we can guess its mapping
missing_letter = missing_letters.pop()
missing_mappings = set(ascii_lowercase + " ") - set(result.values())
result[missing_letter] = missing_mappings.pop()
return result
class GooglereseTranslator:
"""
A Googlerese-to-English translator.
Tries to guess the letter-mapping-dictionary from the examples.
"""
def __init__(self, examples=None):
if examples is not None:
self.letter_map_gtoe = guess_map_from_examples(examples)
else:
self.letter_map_gtoe = guess_map_from_examples(self.examples)
self.translation_table_gtoe = str.maketrans(self.letter_map_gtoe)
def to_english(self, message):
return message.translate(self.translation_table_gtoe)
examples = {"y qee":"a zoo",
"ejp mysljylc kd kxveddknmc re jsicpdrysi":"our language is impossible to understand",
"rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd":"there are twenty six factorial possibilities",
"de kr kd eoya kw aej tysr re ujdr lkgc jv":"so it is okay if you want to just give up"}
| mit |
paran0ids0ul/infernal-twin | build/reportlab/demos/gadflypaper/gfe.py | 15 | 32480 | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
__doc__=''
__version__=''' $Id$ '''
#REPORTLAB_TEST_SCRIPT
import sys
from reportlab.platypus import *
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
PAGE_HEIGHT=defaultPageSize[1]
styles = getSampleStyleSheet()
Title = "Integrating Diverse Data Sources with Gadfly 2"
Author = "Aaron Watters"
URL = "http://www.chordate.com/"
email = "arw@ifu.net"
Abstract = """This paper describes the primative methods underlying the implementation
of SQL query evaluation in Gadfly 2, a database management system implemented
in Python [Van Rossum]. The major design goals behind
the architecture described here are to simplify the implementation
and to permit flexible and efficient extensions to the gadfly
engine. Using this architecture and its interfaces programmers
can add functionality to the engine such as alternative disk based
indexed table implementations, dynamic interfaces to remote data
bases or or other data sources, and user defined computations."""
from reportlab.lib.units import inch
pageinfo = "%s / %s / %s" % (Author, email, Title)
def myFirstPage(canvas, doc):
canvas.saveState()
#canvas.setStrokeColorRGB(1,0,0)
#canvas.setLineWidth(5)
#canvas.line(66,72,66,PAGE_HEIGHT-72)
canvas.setFont('Times-Bold',16)
canvas.drawString(108, PAGE_HEIGHT-108, Title)
canvas.setFont('Times-Roman',9)
canvas.drawString(inch, 0.75 * inch, "First Page / %s" % pageinfo)
canvas.restoreState()
def myLaterPages(canvas, doc):
#canvas.drawImage("snkanim.gif", 36, 36)
canvas.saveState()
#canvas.setStrokeColorRGB(1,0,0)
#canvas.setLineWidth(5)
#canvas.line(66,72,66,PAGE_HEIGHT-72)
canvas.setFont('Times-Roman',9)
canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, pageinfo))
canvas.restoreState()
def go():
Elements.insert(0,Spacer(0,inch))
doc = SimpleDocTemplate('gfe.pdf')
doc.build(Elements,onFirstPage=myFirstPage, onLaterPages=myLaterPages)
Elements = []
HeaderStyle = styles["Heading1"] # XXXX
def header(txt, style=HeaderStyle, klass=Paragraph, sep=0.3):
s = Spacer(0.2*inch, sep*inch)
Elements.append(s)
para = klass(txt, style)
Elements.append(para)
ParaStyle = styles["Normal"]
def p(txt):
return header(txt, style=ParaStyle, sep=0.1)
#pre = p # XXX
PreStyle = styles["Code"]
def pre(txt):
s = Spacer(0.1*inch, 0.1*inch)
Elements.append(s)
p = Preformatted(txt, PreStyle)
Elements.append(p)
#header(Title, sep=0.1. style=ParaStyle)
header(Author, sep=0.1, style=ParaStyle)
header(URL, sep=0.1, style=ParaStyle)
header(email, sep=0.1, style=ParaStyle)
header("ABSTRACT")
p(Abstract)
header("Backgrounder")
p("""\
The term "database" usually refers to a persistent
collection of data. Data is persistent if it continues
to exist whether or not it is associated with a running
process on the computer, or even if the computer is
shut down and restarted at some future time. Database
management systems provide support for constructing databases,
maintaining databases, and extracting information from databases.""")
p("""\
Relational databases manipulate and store persistent
table structures called relations, such as the following
three tables""")
pre("""\
-- drinkers who frequent bars (this is a comment)
select * from frequents
DRINKER | PERWEEK | BAR
============================
adam | 1 | lolas
woody | 5 | cheers
sam | 5 | cheers
norm | 3 | cheers
wilt | 2 | joes
norm | 1 | joes
lola | 6 | lolas
norm | 2 | lolas
woody | 1 | lolas
pierre | 0 | frankies
)
""")
pre("""\
-- drinkers who like beers
select * from likes
DRINKER | PERDAY | BEER
===============================
adam | 2 | bud
wilt | 1 | rollingrock
sam | 2 | bud
norm | 3 | rollingrock
norm | 2 | bud
nan | 1 | sierranevada
woody | 2 | pabst
lola | 5 | mickies
""")
pre("""\
-- beers served from bars
select * from serves
BAR | QUANTITY | BEER
=================================
cheers | 500 | bud
cheers | 255 | samadams
joes | 217 | bud
joes | 13 | samadams
joes | 2222 | mickies
lolas | 1515 | mickies
lolas | 333 | pabst
winkos | 432 | rollingrock
frankies | 5 | snafu
""")
p("""
The relational model for database structures makes
the simplifying assumption that all data in a database
can be represented in simple table structures
such as these. Although this assumption seems extreme
it provides a good foundation for defining solid and
well defined database management systems and some
of the most successful software companies in the
world, such as Oracle, Sybase, IBM, and Microsoft,
have marketed database management systems based on
the relational model quite successfully.
""")
p("""
SQL stands for Structured Query Language.
The SQL language defines industry standard
mechanisms for creating, querying, and modified
relational tables. Several years ago SQL was one
of many Relational Database Management System
(RDBMS) query languages in use, and many would
argue not the best on. Now, largely due
to standardization efforts and the
backing of IBM, SQL is THE standard way to talk
to database systems.
""")
p("""
There are many advantages SQL offers over other
database query languages and alternative paradigms
at this time (please see [O'Neill] or [Korth and Silberschatz]
for more extensive discussions and comparisons between the
SQL/relational approach and others.)
""")
p("""
The chief advantage over all contenders at this time
is that SQL and the relational model are now widely
used as interfaces and back end data stores to many
different products with different performance characteristics,
user interfaces, and other qualities: Oracle, Sybase,
Ingres, SQL Server, Access, Outlook,
Excel, IBM DB2, Paradox, MySQL, MSQL, POSTgres, and many
others. For this reason a program designed to use
an SQL database as its data storage mechanism can
easily be ported from one SQL data manager to another,
possibly on different platforms. In fact the same
program can seamlessly use several backends and/or
import/export data between different data base platforms
with trivial ease.
No other paradigm offers such flexibility at the moment.
""")
p("""
Another advantage which is not as immediately
obvious is that the relational model and the SQL
query language are easily understood by semi-technical
and non-technical professionals, such as business
people and accountants. Human resources managers
who would be terrified by an object model diagram
or a snippet of code that resembles a conventional
programming language will frequently feel quite at
ease with a relational model which resembles the
sort of tabular data they deal with on paper in
reports and forms on a daily basis. With a little training the
same HR managers may be able to translate the request
"Who are the drinkers who like bud and frequent cheers?"
into the SQL query
""")
pre("""
select drinker
from frequents
where bar='cheers'
and drinker in (
select drinker
from likes
where beer='bud')
""")
p("""
(or at least they have some hope of understanding
the query once it is written by a technical person
or generated by a GUI interface tool). Thus the use
of SQL and the relational model enables communication
between different communities which must understand
and interact with stored information. In contrast
many other approaches cannot be understood easily
by people without extensive programming experience.
""")
p("""
Furthermore the declarative nature of SQL
lends itself to automatic query optimization,
and engines such as Gadfly can automatically translate a user query
into an optimized query plan which takes
advantage of available indices and other data characteristics.
In contrast more navigational techniques require the application
program itself to optimize the accesses to the database and
explicitly make use of indices.
""")
# HACK
Elements.append(PageBreak())
p("""
While it must be admitted that there are application
domains such as computer aided engineering design where
the relational model is unnatural, it is also important
to recognize that for many application domains (such
as scheduling, accounting, inventory, finance, personal
information management, electronic mail) the relational
model is a very natural fit and the SQL query language
make most accesses to the underlying data (even sophisticated
ones) straightforward. """)
p("""For an example of a moderately
sophisticated query using the tables given above,
the following query lists the drinkers who frequent lolas bar
and like at least two beers not served by lolas
""")
if 0:
go()
sys.exit(1)
pre("""
select f.drinker
from frequents f, likes l
where f.drinker=l.drinker and f.bar='lolas'
and l.beer not in
(select beer from serves where bar='lolas')
group by f.drinker
having count(distinct beer)>=2
""")
p("""
yielding the result
""")
pre("""
DRINKER
=======
norm
""")
p("""
Experience shows that queries of this sort are actually
quite common in many applications, and are often much more
difficult to formulate using some navigational database
organizations, such as some "object oriented" database
paradigms.
""")
p("""
Certainly,
SQL does not provide all you need to interact with
databases -- in order to do "real work" with SQL you
need to use SQL and at least one other language
(such as C, Pascal, C++, Perl, Python, TCL, Visual Basic
or others) to do work (such as readable formatting a report
from raw data) that SQL was not designed to do.
""")
header("Why Gadfly 1?")
p("""Gadfly 1.0 is an SQL based relational database implementation
implemented entirely in the Python programming language, with
optional fast data structure accellerators implemented in the
C programming language. Gadfly is relatively small, highly portable,
very easy to use (especially for programmers with previous experience
with SQL databases such as MS Access or Oracle), and reasonably
fast (especially when the kjbuckets C accellerators are used).
For moderate sized problems Gadfly offers a fairly complete
set of features such as transaction semantics, failure recovery,
and a TCP/IP based client/server mode (Please see [Gadfly] for
detailed discussion).""")
header("Why Gadfly 2?")
p("""Gadfly 1.0 also has significant limitations. An active Gadfly
1.0 database keeps all data in (virtual) memory, and hence a Gadfly
1.0 database is limited in size to available virtual memory. Important
features such as date/time/interval operations, regular expression
matching and other standard SQL features are not implemented in
Gadfly 1.0. The optimizer and the query evaluator perform optimizations
using properties of the equality predicate but do not optimize
using properties of inequalities such as BETWEEN or less-than.
It is possible to add "extension views" to a Gadfly
1.0 database, but the mechanism is somewhat clumsy and indices
over extension views are not well supported. The features of Gadfly
2.0 discussed here attempt to address these deficiencies by providing
a uniform extension model that permits addition of alternate table,
function, and predicate implementations.""")
p("""Other deficiencies, such as missing constructs like "ALTER
TABLE" and the lack of outer joins and NULL values are not
addressed here, although they may be addressed in Gadfly 2.0 or
a later release. This paper also does not intend to explain
the complete operations of the internals; it is intended to provide
at least enough information to understand the basic mechanisms
for extending gadfly.""")
p("""Some concepts and definitions provided next help with the description
of the gadfly interfaces. [Note: due to the terseness of this
format the ensuing is not a highly formal presentation, but attempts
to approach precision where precision is important.]""")
header("The semilattice of substitutions")
p("""Underlying the gadfly implementation are the basic concepts
associated with substitutions. A substitution is a mapping
of attribute names to values (implemented in gadfly using kjbuckets.kjDict
objects). Here an attribute refers to some sort of "descriptive
variable", such as NAME and a value is an assignment for that variable,
like "Dave Ascher". In Gadfly a table is implemented as a sequence
of substitutions, and substitutions are used in many other ways as well.
""")
p("""
For example consider the substitutions""")
pre("""
A = [DRINKER=>'sam']
B = [DRINKER=>'sam', BAR=>'cheers']
C = [DRINKER=>'woody', BEER=>'bud']
D = [DRINKER=>'sam', BEER=>'mickies']
E = [DRINKER=>'sam', BAR=>'cheers', BEER=>'mickies']
F = [DRINKER=>'sam', BEER=>'mickies']
G = [BEER=>'bud', BAR=>'lolas']
H = [] # the empty substitution
I = [BAR=>'cheers', CAPACITY=>300]""")
p("""A trivial but important observation is that since substitutions
are mappings, no attribute can assume more than one value in a
substitution. In the operations described below whenever an operator
"tries" to assign more than one value to an attribute
the operator yields an "overdefined" or "inconsistent"
result.""")
header("Information Semi-order:")
p("""Substitution B is said to be
more informative than A because B agrees with all assignments
in A (in addition to providing more information as well). Similarly
we say that E is more informative than A, B, D, F. and H but E
is not more informative than the others since, for example G disagrees
with E on the value assigned to the BEER attribute and I provides
additional CAPACITY information not provided in E.""")
header("Joins and Inconsistency:")
p("""A join of two substitutions
X and Y is the least informative substitution Z such that Z is
more informative (or equally informative) than both X and Y. For
example B is the join of B with A, E is the join of B with D and""")
pre("""
E join I =
[DRINKER=>'sam', BAR=>'cheers', BEER=>'mickies', CAPACITY=>300]""")
p("""For any two substitutions either (1) they disagree on the value
assigned to some attribute and have no join or (2) they agree
on all common attributes (if there are any) and their join is
the union of all (name, value) assignments in both substitutions.
Written in terms of kjbucket.kjDict operations two kjDicts X and
Y have a join Z = (X+Y) if and only if Z.Clean() is not None.
Two substitutions that have no join are said to be inconsistent.
For example I and G are inconsistent since they disagree on
the value assigned to the BAR attribute and therefore have no
join. The algebra of substitutions with joins technically defines
an abstract algebraic structure called a semilattice.""")
header("Name space remapping")
p("""Another primitive operation over substitutions is the remap
operation S2 = S.remap(R) where S is a substitution and R is a
graph of attribute names and S2 is a substitution. This operation
is defined to produce the substitution S2 such that""")
pre("""
Name=>Value in S2 if and only if
Name1=>Value in S and Name<=Name1 in R
""")
p("""or if there is no such substitution S2 the remap value is said
to be overdefined.""")
p("""For example the remap operation may be used to eliminate attributes
from a substitution. For example""")
pre("""
E.remap([DRINKER<=DRINKER, BAR<=BAR])
= [DRINKER=>'sam', BAR=>'cheers']
""")
p("""Illustrating that remapping using the [DRINKER<=DRINKER,
BAR<=BAR] graph eliminates all attributes except DRINKER and
BAR, such as BEER. More generally remap can be used in this way
to implement the classical relational projection operation. (See [Korth and Silberschatz]
for a detailed discussion of the projection operator and other relational
algebra operators such as selection, rename, difference and joins.)""")
p("""The remap operation can also be used to implement "selection
on attribute equality". For example if we are interested
in the employee names of employees who are their own bosses we
can use the remapping graph""")
pre("""
R1 = [NAME<=NAME, NAME<=BOSS]
""")
p("""and reject substitutions where remapping using R1 is overdefined.
For example""")
pre("""
S1 = [NAME=>'joe', BOSS=>'joe']
S1.remap(R1) = [NAME=>'joe']
S2 = [NAME=>'fred', BOSS=>'joe']
S2.remap(R1) is overdefined.
""")
p("""The last remap is overdefined because the NAME attribute cannot
assume both the values 'fred' and 'joe' in a substitution.""")
p("""Furthermore, of course, the remap operation can be used to
"rename attributes" or "copy attribute values"
in substitutions. Note below that the missing attribute CAPACITY
in B is effectively ignored in the remapping operation.""")
pre("""
B.remap([D<=DRINKER, B<=BAR, B2<=BAR, C<=CAPACITY])
= [D=>'sam', B=>'cheers', B2=>'cheers']
""")
p("""More interestingly, a single remap operation can be used to
perform a combination of renaming, projection, value copying,
and attribute equality selection as one operation. In kjbuckets the remapper
graph is implemented using a kjbuckets.kjGraph and the remap operation
is an intrinsic method of kjbuckets.kjDict objects.""")
header("Generalized Table Joins and the Evaluator Mainloop""")
p("""Strictly speaking the Gadfly 2.0 query evaluator only uses
the join and remap operations as its "basic assembly language"
-- all other computations, including inequality comparisons and
arithmetic, are implemented externally to the evaluator as "generalized
table joins." """)
p("""A table is a sequence of substitutions (which in keeping with
SQL semantics may contain redundant entries). The join between
two tables T1 and T2 is the sequence of all possible defined joins
between pairs of elements from the two tables. Procedurally we
might compute the join as""")
pre("""
T1JoinT2 = empty
for t1 in T1:
for t2 in T2:
if t1 join t2 is defined:
add t1 join t2 to T1joinT2""")
p("""In general circumstances this intuitive implementation is a
very inefficient way to compute the join, and Gadfly almost always
uses other methods, particularly since, as described below, a
"generalized table" can have an "infinite"
number of entries.""")
p("""For an example of a table join consider the EMPLOYEES table
containing""")
pre("""
[NAME=>'john', JOB=>'executive']
[NAME=>'sue', JOB=>'programmer']
[NAME=>'eric', JOB=>'peon']
[NAME=>'bill', JOB=>'peon']
""")
p("""and the ACTIVITIES table containing""")
pre("""
[JOB=>'peon', DOES=>'windows']
[JOB=>'peon', DOES=>'floors']
[JOB=>'programmer', DOES=>'coding']
[JOB=>'secretary', DOES=>'phone']""")
p("""then the join between EMPLOYEES and ACTIVITIES must containining""")
pre("""
[NAME=>'sue', JOB=>'programmer', DOES=>'coding']
[NAME=>'eric', JOB=>'peon', DOES=>'windows']
[NAME=>'bill', JOB=>'peon', DOES=>'windows']
[NAME=>'eric', JOB=>'peon', DOES=>'floors']
[NAME=>'bill', JOB=>'peon', DOES=>'floors']""")
p("""A compiled gadfly subquery ultimately appears to the evaluator
as a sequence of generalized tables that must be joined (in combination
with certain remapping operations that are beyond the scope of
this discussion). The Gadfly mainloop proceeds following the very
loose pseudocode:""")
pre("""
Subs = [ [] ] # the unary sequence containing "true"
While some table hasn't been chosen yet:
Choose an unchosen table with the least cost join estimate.
Subs = Subs joined with the chosen table
return Subs""")
p("""[Note that it is a property of the join operation that the
order in which the joins are carried out will not affect the result,
so the greedy strategy of evaluating the "cheapest join next"
will not effect the result. Also note that the treatment of logical
OR and NOT as well as EXIST, IN, UNION, and aggregation and so
forth are not discussed here, even though they do fit into this
approach.]""")
p("""The actual implementation is a bit more complex than this,
but the above outline may provide some useful intuition. The "cost
estimation" step and the implementation of the join operation
itself are left up to the generalized table object implementation.
A table implementation has the ability to give an "infinite"
cost estimate, which essentially means "don't join me in
yet under any circumstances." """)
header("Implementing Functions")
p("""As mentioned above operations such as arithmetic are implemented
using generalized tables. For example the arithmetic Add operation
is implemented in Gadfly internally as an "infinite generalized
table" containing all possible substitutions""")
pre("""
ARG0=>a, ARG1=>b, RESULT=>a+b]
""")
p("""Where a and b are all possible values which can be summed.
Clearly, it is not possible to enumerate this table, but given
a sequence of substitutions with defined values for ARG0 and ARG1
such as""")
pre("""
[ARG0=>1, ARG1=-4]
[ARG0=>2.6, ARG1=50]
[ARG0=>99, ARG1=1]
""")
p("""it is possible to implement a "join operation" against
this sequence that performs the same augmentation as a join with
the infinite table defined above:""")
pre("""
[ARG0=>1, ARG1=-4, RESULT=-3]
[ARG0=>2.6, ARG1=50, RESULT=52.6]
[ARG0=>99, ARG1=1, RESULT=100]
""")
p("""Furthermore by giving an "infinite estimate" for
all attempts to evaluate the join where ARG0 and ARG1 are not
available the generalized table implementation for the addition
operation can refuse to compute an "infinite join." """)
p("""More generally all functions f(a,b,c,d) are represented in
gadfly as generalized tables containing all possible relevant
entries""")
pre("""
[ARG0=>a, ARG1=>b, ARG2=>c, ARG3=>d, RESULT=>f(a,b,c,d)]""")
p("""and the join estimation function refuses all attempts to perform
a join unless all the arguments are provided by the input substitution
sequence.""")
header("Implementing Predicates")
p("""Similarly to functions, predicates such as less-than and BETWEEN
and LIKE are implemented using the generalized table mechanism.
For example the "x BETWEEN y AND z" predicate is implemented
as a generalized table "containing" all possible""")
pre("""
[ARG0=>a, ARG1=>b, ARG2=>c]""")
p("""where b<a<c. Furthermore joins with this table are not
permitted unless all three arguments are available in the sequence
of input substitutions.""")
header("Some Gadfly extension interfaces")
p("""A gadfly database engine may be extended with user defined
functions, predicates, and alternative table and index implementations.
This section snapshots several Gadfly 2.0 interfaces, currently under
development and likely to change before the package is released.""")
p("""The basic interface for adding functions and predicates (logical tests)
to a gadfly engine are relatively straightforward. For example to add the
ability to match a regular expression within a gadfly query use the
following implementation.""")
pre("""
from re import match
def addrematch(gadflyinstance):
gadflyinstance.add_predicate("rematch", match)
""")
p("""
Then upon connecting to the database execute
""")
pre("""
g = gadfly(...)
...
addrematch(g)
""")
p("""
In this case the "semijoin operation" associated with the new predicate
"rematch" is automatically generated, and after the add_predicate
binding operation the gadfly instance supports queries such as""")
pre("""
select drinker, beer
from likes
where rematch('b*', beer) and drinker not in
(select drinker from frequents where rematch('c*', bar))
""")
p("""
By embedding the "rematch" operation within the query the SQL
engine can do "more work" for the programmer and reduce or eliminate the
need to process the query result externally to the engine.
""")
p("""
In a similar manner functions may be added to a gadfly instance,""")
pre("""
def modulo(x,y):
return x % y
def addmodulo(gadflyinstance):
gadflyinstance.add_function("modulo", modulo)
...
g = gadfly(...)
...
addmodulo(g)
""")
p("""
Then after the binding the modulo function can be used whereever
an SQL expression can occur.
""")
p("""
Adding alternative table implementations to a Gadfly instance
is more interesting and more difficult. An "extension table" implementation
must conform to the following interface:""")
pre("""
# get the kjbuckets.kjSet set of attribute names for this table
names = table.attributes()
# estimate the difficulty of evaluating a join given known attributes
# return None for "impossible" or n>=0 otherwise with larger values
# indicating greater difficulty or expense
estimate = table.estimate(known_attributes)
# return the join of the rows of the table with
# the list of kjbuckets.kjDict mappings as a list of mappings.
resultmappings = table.join(listofmappings)
""")
p("""
In this case add the table to a gadfly instance using""")
pre("""
gadflyinstance.add_table("table_name", table)
""")
p("""
For example to add a table which automatically queries filenames
in the filesystems of the host computer a gadfly instance could
be augmented with a GLOB table implemented using the standard
library function glob.glob as follows:""")
pre("""
import kjbuckets
class GlobTable:
def __init__(self): pass
def attributes(self):
return kjbuckets.kjSet("PATTERN", "NAME")
def estimate(self, known_attributes):
if known_attributes.member("PATTERN"):
return 66 # join not too difficult
else:
return None # join is impossible (must have PATTERN)
def join(self, listofmappings):
from glob import glob
result = []
for m in listofmappings:
pattern = m["PATTERN"]
for name in glob(pattern):
newmapping = kjbuckets.kjDict(m)
newmapping["NAME"] = name
if newmapping.Clean():
result.append(newmapping)
return result
...
gadfly_instance.add_table("GLOB", GlobTable())
""")
p("""
Then one could formulate queries such as "list the files in directories
associated with packages installed by guido"
""")
pre("""
select g.name as filename
from packages p, glob g
where p.installer = 'guido' and g.pattern=p.root_directory
""")
p("""
Note that conceptually the GLOB table is an infinite table including
all filenames on the current computer in the "NAME" column, paired with
a potentially infinite number of patterns.
""")
p("""
More interesting examples would allow queries to remotely access
data served by an HTTP server, or from any other resource.
""")
p("""
Furthermore an extension table can be augmented with update methods
""")
pre("""
table.insert_rows(listofmappings)
table.update_rows(oldlist, newlist)
table.delete_rows(oldlist)
""")
p("""
Note: at present the implementation does not enforce recovery or
transaction semantics for updates to extension tables, although this
may change in the final release.
""")
p("""
The table implementation is free to provide its own implementations of
indices which take advantage of data provided by the join argument.
""")
header("Efficiency Notes")
p("""The following thought experiment attempts to explain why the
Gadfly implementation is surprisingly fast considering that it
is almost entirely implemented in Python (an interpreted programming
language which is not especially fast when compared to alternatives).
Although Gadfly is quite complex, at an abstract level the process
of query evaluation boils down to a series of embedded loops.
Consider the following nested loops:""")
pre("""
iterate 1000:
f(...) # fixed cost of outer loop
iterate 10:
g(...) # fixed cost of middle loop
iterate 10:
# the real work (string parse, matrix mul, query eval...)
h(...)""")
p("""In my experience many computations follow this pattern where
f, g, are complex, dynamic, special purpose and h is simple, general
purpose, static. Some example computations that follow this pattern
include: file massaging (perl), matrix manipulation (python, tcl),
database/cgi page generation, and vector graphics/imaging.""")
p("""Suppose implementing f, g, h in python is easy but result in
execution times10 times slower than a much harder implementation
in C, choosing arbitrary and debatable numbers assume each function
call consumes 1 tick in C, 5 ticks in java, 10 ticks in python
for a straightforward implementation of each function f, g, and
h. Under these conditions we get the following cost analysis,
eliminating some uninteresting combinations, of implementing the
function f, g, and h in combinations of Python, C and java:""")
pre("""
COST | FLANG | GLANG | HLANG
==================================
111000 | C | C | C
115000 | java | C | C
120000 | python | C | C
155000 | java | java | C
210000 | python | python | C
555000 | java | java | java
560000 | python | java | java
610000 | python | python | java
1110000 | python | python | python
""")
p("""Note that moving only the innermost loop to C (python/python/C)
speeds up the calculation by half an order of magnitude compared
to the python-only implementation and brings the speed to within
a factor of 2 of an implementation done entirely in C.""")
p("""Although this artificial and contrived thought experiment is
far from conclusive, we may be tempted to draw the conclusion
that generally programmers should focus first on obtaining a working
implementation (because as John Ousterhout is reported to have
said "the biggest performance improvement is the transition
from non-working to working") using the methodology that
is most likely to obtain a working solution the quickest (Python). Only then if the performance
is inadequate should the programmer focus on optimizing
the inner most loops, perhaps moving them to a very efficient
implementation (C). Optimizing the outer loops will buy little
improvement, and should be done later, if ever.""")
p("""This was precisely the strategy behind the gadfly implementations,
where most of the inner loops are implemented in the kjbuckets
C extension module and the higher level logic is all in Python.
This also explains why gadfly appears to be "slower"
for simple queries over small data sets, but seems to be relatively
"faster" for more complex queries over larger data sets,
since larger queries and data sets take better advantage of the
optimized inner loops.""")
header("A Gadfly variant for OLAP?")
p("""In private correspondence Andy Robinson points out that the
basic logical design underlying Gadfly could be adapted to provide
Online Analytical Processing (OLAP) and other forms of data warehousing
and data mining. Since SQL is not particularly well suited for
the kinds of requests common in these domains the higher level
interfaces would require modification, but the underlying logic
of substitutions and name mappings seems to be appropriate.""")
header("Conclusion")
p("""The revamped query engine design in Gadfly 2 supports
a flexible and general extension methodology that permits programmers
to extend the gadfly engine to include additional computations
and access to remote data sources. Among other possibilities this
will permit the gadfly engine to make use of disk based indexed
tables and to dynamically retrieve information from remote data
sources (such as an Excel spreadsheet or an Oracle database).
These features will make gadfly a very useful tool for data manipulation
and integration.""")
header("References")
p("""[Van Rossum] Van Rossum, Python Reference Manual, Tutorial, and Library Manuals,
please look to http://www.python.org
for the latest versions, downloads and links to printed versions.""")
p("""[O'Neill] O'Neill, P., Data Base Principles, Programming, Performance,
Morgan Kaufmann Publishers, San Francisco, 1994.""")
p("""[Korth and Silberschatz] Korth, H. and Silberschatz, A. and Sudarshan, S.
Data Base System Concepts, McGraw-Hill Series in Computer Science, Boston,
1997""")
p("""[Gadfly]Gadfly: SQL Relational Database in Python,
http://www.chordate.com/kwParsing/gadfly.html""")
go()
| gpl-3.0 |
mozilla/verbatim | vendor/lib/python/translate/lang/ug.py | 5 | 1130 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# translate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
"""This module represents the Uyghur language.
.. seealso:: http://en.wikipedia.org/wiki/Uyghur_language
"""
from translate.lang import common
class ug(common.Common):
"""This class represents Uyghur."""
listseperator = u"، "
puncdict = {
u",": u"،",
u";": u"؛",
u"?": u"؟",
}
ignoretests = ["startcaps", "simplecaps"]
| gpl-2.0 |
yfdyh000/olympia | scripts/xpitool.py | 25 | 1149 | #!/usr/bin/env python
import optparse
import os
import subprocess
def main():
p = optparse.OptionParser(
usage='%prog [options] [-x addon-1.0.xpi] [-c /path/to/addon-1.0/]')
p.add_option('-x', '--extract',
help='Extracts xpi into current directory',
action='store_true')
p.add_option('-c', '--recreate',
help='Zips an extracted xpi into current directory',
action='store_true')
(options, args) = p.parse_args()
if len(args) != 1:
p.error("Incorrect usage")
addon = os.path.abspath(args[0])
if options.extract:
d = os.path.splitext(addon)[0]
os.mkdir(d)
os.chdir(d)
subprocess.check_call(['unzip', addon])
print "Extracted to %s" % d
elif options.recreate:
xpi = "%s.xpi" % addon
if os.path.exists(xpi):
p.error("Refusing to overwrite %r" % xpi)
os.chdir(addon)
subprocess.check_call(['zip', '-r', xpi] + os.listdir(os.getcwd()))
print "Created %s" % xpi
else:
p.error("Incorrect usage")
if __name__ == '__main__':
main()
| bsd-3-clause |
ericsnowcurrently/micropython | tests/basics/string_index.py | 118 | 1712 | print("hello world".index("ll"))
print("hello world".index("ll", None))
print("hello world".index("ll", 1))
print("hello world".index("ll", 1, None))
print("hello world".index("ll", None, None))
print("hello world".index("ll", 1, -1))
try:
print("hello world".index("ll", 1, 1))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("hello world".index("ll", 1, 2))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("hello world".index("ll", 1, 3))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
print("hello world".index("ll", 1, 4))
print("hello world".index("ll", 1, 5))
print("hello world".index("ll", -100))
print("0000".index('0'))
print("0000".index('0', 0))
print("0000".index('0', 1))
print("0000".index('0', 2))
print("0000".index('0', 3))
try:
print("0000".index('0', 4))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('0', 5))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('-1', 3))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('1', 3))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('1', 4))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('1', 5))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
| mit |
brchiu/tensorflow | tensorflow/contrib/distributions/python/ops/poisson.py | 34 | 6985 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# ==============================================================================
"""The Poisson distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops.distributions import distribution
from tensorflow.python.ops.distributions import util as distribution_util
from tensorflow.python.util import deprecation
__all__ = [
"Poisson",
]
_poisson_sample_note = """
The Poisson distribution is technically only defined for non-negative integer
values. When `validate_args=False`, non-integral inputs trigger an assertion.
When `validate_args=False` calculations are otherwise unchanged despite
integral or non-integral inputs.
When `validate_args=False`, evaluating the pmf at non-integral values,
corresponds to evaluations of an unnormalized distribution, that does not
correspond to evaluations of the cdf.
"""
class Poisson(distribution.Distribution):
"""Poisson distribution.
The Poisson distribution is parameterized by an event `rate` parameter.
#### Mathematical Details
The probability mass function (pmf) is,
```none
pmf(k; lambda, k >= 0) = (lambda^k / k!) / Z
Z = exp(lambda).
```
where `rate = lambda` and `Z` is the normalizing constant.
"""
@deprecation.deprecated(
"2018-10-01",
"The TensorFlow Distributions library has moved to "
"TensorFlow Probability "
"(https://github.com/tensorflow/probability). You "
"should update all references to use `tfp.distributions` "
"instead of `tf.contrib.distributions`.",
warn_once=True)
def __init__(self,
rate=None,
log_rate=None,
validate_args=False,
allow_nan_stats=True,
name="Poisson"):
"""Initialize a batch of Poisson distributions.
Args:
rate: Floating point tensor, the rate parameter. `rate` must be positive.
Must specify exactly one of `rate` and `log_rate`.
log_rate: Floating point tensor, the log of the rate parameter.
Must specify exactly one of `rate` and `log_rate`.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `bool`, default `True`. When `True`, statistics
(e.g., mean, mode, variance) use the value "`NaN`" to indicate the
result is undefined. When `False`, an exception is raised if one or
more of the statistic's batch members are undefined.
name: Python `str` name prefixed to Ops created by this class.
Raises:
ValueError: if none or both of `rate`, `log_rate` are specified.
TypeError: if `rate` is not a float-type.
TypeError: if `log_rate` is not a float-type.
"""
parameters = dict(locals())
with ops.name_scope(name, values=[rate]) as name:
if (rate is None) == (log_rate is None):
raise ValueError("Must specify exactly one of `rate` and `log_rate`.")
elif log_rate is None:
rate = ops.convert_to_tensor(rate, name="rate")
if not rate.dtype.is_floating:
raise TypeError("rate.dtype ({}) is a not a float-type.".format(
rate.dtype.name))
with ops.control_dependencies([check_ops.assert_positive(rate)] if
validate_args else []):
self._rate = array_ops.identity(rate, name="rate")
self._log_rate = math_ops.log(rate, name="log_rate")
else:
log_rate = ops.convert_to_tensor(log_rate, name="log_rate")
if not log_rate.dtype.is_floating:
raise TypeError("log_rate.dtype ({}) is a not a float-type.".format(
log_rate.dtype.name))
self._rate = math_ops.exp(log_rate, name="rate")
self._log_rate = ops.convert_to_tensor(log_rate, name="log_rate")
super(Poisson, self).__init__(
dtype=self._rate.dtype,
reparameterization_type=distribution.NOT_REPARAMETERIZED,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
parameters=parameters,
graph_parents=[self._rate],
name=name)
@property
def rate(self):
"""Rate parameter."""
return self._rate
@property
def log_rate(self):
"""Log rate parameter."""
return self._log_rate
def _batch_shape_tensor(self):
return array_ops.shape(self.rate)
def _batch_shape(self):
return self.rate.shape
def _event_shape_tensor(self):
return constant_op.constant([], dtype=dtypes.int32)
def _event_shape(self):
return tensor_shape.scalar()
@distribution_util.AppendDocstring(_poisson_sample_note)
def _log_prob(self, x):
return self._log_unnormalized_prob(x) - self._log_normalization()
@distribution_util.AppendDocstring(_poisson_sample_note)
def _log_cdf(self, x):
return math_ops.log(self.cdf(x))
@distribution_util.AppendDocstring(_poisson_sample_note)
def _cdf(self, x):
if self.validate_args:
x = distribution_util.embed_check_nonnegative_integer_form(x)
return math_ops.igammac(1. + x, self.rate)
def _log_normalization(self):
return self.rate
def _log_unnormalized_prob(self, x):
if self.validate_args:
x = distribution_util.embed_check_nonnegative_integer_form(x)
return x * self.log_rate - math_ops.lgamma(1. + x)
def _mean(self):
return array_ops.identity(self.rate)
def _variance(self):
return array_ops.identity(self.rate)
@distribution_util.AppendDocstring(
"""Note: when `rate` is an integer, there are actually two modes: `rate`
and `rate - 1`. In this case we return the larger, i.e., `rate`.""")
def _mode(self):
return math_ops.floor(self.rate)
def _sample_n(self, n, seed=None):
return random_ops.random_poisson(
self.rate, [n], dtype=self.dtype, seed=seed)
| apache-2.0 |
pbreach/pysd | tests/unit_test_builder.py | 2 | 8454 | import textwrap
from unittest import TestCase
import xarray as xr
import numpy as np
from pysd.functions import cache
from numbers import Number
def runner(string, ns=None):
code = compile(string, '<string>', 'exec')
if not ns:
ns = dict()
ns.update({'cache': cache, 'xr': xr, 'np': np})
exec (code, ns)
return ns
class TestBuildElement(TestCase):
def test_no_subs_constant(self):
from pysd.builder import build_element
string = textwrap.dedent(
build_element(element={'kind': 'constant',
'subs': [[]],
'doc': '',
'py_name': 'my_variable',
'real_name': 'My Variable',
'py_expr': ['0.01'],
'unit': '',
'arguments': ''},
subscript_dict={})
)
ns = runner(string)
a = ns['my_variable']()
self.assertIsInstance(a, Number)
self.assertEqual(a, .01)
def test_no_subs_call(self):
from pysd.builder import build_element
string = textwrap.dedent(
build_element(element={'kind': 'constant',
'subs': [[]],
'doc': '',
'py_name': 'my_variable',
'real_name': 'My Variable',
'py_expr': ['other_variable()'],
'unit': '',
'arguments': ''},
subscript_dict={})
)
ns = {'other_variable': lambda: 3}
ns = runner(string, ns)
a = ns['my_variable']()
self.assertIsInstance(a, Number)
self.assertEqual(a, 3)
class TestBuild(TestCase):
def test_build(self):
# Todo: add other builder-specific inclusions to this test
from pysd.builder import build
actual = textwrap.dedent(
build(elements=[{'kind': 'component',
'subs': [[]],
'doc': '',
'py_name': 'stocka',
'real_name': 'StockA',
'py_expr': ["_state['stocka']"],
'unit': '',
'arguments':''},
{'kind': 'component',
'subs': [[]],
'doc': 'Provides derivative for stocka function',
'py_name': '_dstocka_dt',
'real_name': 'Implicit',
'py_expr': ['flowa()'],
'unit': 'See docs for stocka',
'arguments':''},
{'kind': 'setup',
'subs': [[]],
'doc': 'Provides initial conditions for stocka function',
'py_name': 'init_stocka',
'real_name': 'Implicit',
'py_expr': ['-10'],
'unit': 'See docs for stocka',
'arguments':''}],
namespace={'StockA': 'stocka'},
subscript_dict={'Dim1': ['A', 'B', 'C']},
outfile_name='return'))
self.assertIn("_subscript_dict = {'Dim1': ['A', 'B', 'C']}", actual)
self.assertIn("_namespace = {'StockA': 'stocka'}", actual)
class TestMergePartialElements(TestCase):
def test_single_set(self):
from pysd.builder import merge_partial_elements
self.assertEqual(
merge_partial_elements(
[{'py_name': 'a', 'py_expr': 'ms', 'subs': ['Name1', 'element1'],
'real_name': 'A', 'doc': 'Test', 'unit': None,
'kind': 'component', 'arguments': ''},
{'py_name': 'a', 'py_expr': 'njk', 'subs': ['Name1', 'element2'],
'real_name': 'A', 'doc': None, 'unit': None,
'kind': 'component', 'arguments': ''},
{'py_name': 'a', 'py_expr': 'as', 'subs': ['Name1', 'element3'],
'real_name': 'A', 'doc': '', 'unit': None,
'kind': 'component', 'arguments': ''}]),
[{'py_name': 'a',
'py_expr': ['ms', 'njk', 'as'],
'subs': [['Name1', 'element1'], ['Name1', 'element2'], ['Name1', 'element3']],
'kind': 'component',
'doc': 'Test',
'real_name': 'A',
'unit': None,
'arguments': ''
}])
def test_multiple_sets(self):
from pysd.builder import merge_partial_elements
actual = merge_partial_elements(
[{'py_name': 'a', 'py_expr': 'ms', 'subs': ['Name1', 'element1'],
'real_name': 'A', 'doc': 'Test', 'unit': None,
'kind': 'component', 'arguments': ''},
{'py_name': 'a', 'py_expr': 'njk', 'subs': ['Name1', 'element2'],
'real_name': 'A', 'doc': None, 'unit': None,
'kind': 'component', 'arguments': ''},
{'py_name': 'a', 'py_expr': 'as', 'subs': ['Name1', 'element3'],
'real_name': 'A', 'doc': '', 'unit': None,
'kind': 'component', 'arguments': ''},
{'py_name': 'b', 'py_expr': 'bgf', 'subs': ['Name1', 'element1'],
'real_name': 'B', 'doc': 'Test', 'unit': None,
'kind': 'component', 'arguments': ''},
{'py_name': 'b', 'py_expr': 'r4', 'subs': ['Name1', 'element2'],
'real_name': 'B', 'doc': None, 'unit': None,
'kind': 'component', 'arguments': ''},
{'py_name': 'b', 'py_expr': 'ymt', 'subs': ['Name1', 'element3'],
'real_name': 'B', 'doc': '', 'unit': None,
'kind': 'component', 'arguments': ''}])
expected = [{'py_name': 'a',
'py_expr': ['ms', 'njk', 'as'],
'subs': [['Name1', 'element1'], ['Name1', 'element2'], ['Name1', 'element3']],
'kind': 'component',
'doc': 'Test',
'real_name': 'A',
'unit': None,
'arguments': ''
},
{'py_name': 'b',
'py_expr': ['bgf', 'r4', 'ymt'],
'subs': [['Name1', 'element1'], ['Name1', 'element2'], ['Name1', 'element3']],
'kind': 'component',
'doc': 'Test',
'real_name': 'B',
'unit': None,
'arguments': ''
}]
self.assertIn(actual[0], expected)
self.assertIn(actual[1], expected)
def test_non_set(self):
from pysd.builder import merge_partial_elements
actual = merge_partial_elements(
[{'py_name': 'a', 'py_expr': 'ms', 'subs': ['Name1', 'element1'],
'real_name': 'A', 'doc': 'Test', 'unit': None,
'kind': 'component', 'arguments': ''},
{'py_name': 'a', 'py_expr': 'njk', 'subs': ['Name1', 'element2'],
'real_name': 'A', 'doc': None, 'unit': None,
'kind': 'component', 'arguments': ''},
{'py_name': 'c', 'py_expr': 'as', 'subs': ['Name1', 'element3'],
'real_name': 'C', 'doc': 'hi', 'unit': None,
'kind': 'component', 'arguments': ''},
])
expected = [{'py_name': 'a',
'py_expr': ['ms', 'njk'],
'subs': [['Name1', 'element1'], ['Name1', 'element2']],
'kind': 'component',
'doc': 'Test',
'real_name': 'A',
'unit': None,
'arguments': ''
},
{'py_name': 'c',
'py_expr': ['as'],
'subs': [['Name1', 'element3']],
'kind': 'component',
'doc': 'hi',
'real_name': 'C',
'unit': None,
'arguments': ''
}]
self.assertIn(actual[0], expected)
self.assertIn(actual[1], expected) | mit |
Godiyos/python-for-android | python-build/python-libs/gdata/tests/gdata_tests/base/service_test.py | 89 | 8650 | #!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'api.jscudder (Jeff Scudder)'
import unittest
import getpass
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import gdata.base.service
import gdata.service
import atom.service
import gdata.base
import atom
from gdata import test_data
username = ''
password = ''
class GBaseServiceUnitTest(unittest.TestCase):
def setUp(self):
self.gd_client = gdata.base.service.GBaseService()
self.gd_client.email = username
self.gd_client.password = password
self.gd_client.source = 'BaseClient "Unit" Tests'
self.gd_client.api_key = 'ABQIAAAAoLioN3buSs9KqIIq9VmkFxT2yXp_ZAY8_ufC' +\
'3CFXhHIE1NvwkxRK8C1Q8OWhsWA2AIKv-cVKlVrNhQ'
def tearDown(self):
# No teardown needed
pass
def testProperties(self):
email_string = 'Test Email'
password_string = 'Passwd'
api_key_string = 'my API key'
self.gd_client.email = email_string
self.assertEquals(self.gd_client.email, email_string)
self.gd_client.password = password_string
self.assertEquals(self.gd_client.password, password_string)
self.gd_client.api_key = api_key_string
self.assertEquals(self.gd_client.api_key, api_key_string)
self.gd_client.api_key = None
self.assert_(self.gd_client.api_key is None)
def testQuery(self):
my_query = gdata.base.service.BaseQuery(feed='/base/feeds/snippets')
my_query['max-results'] = '25'
my_query.bq = 'digital camera [item type: products]'
result = self.gd_client.Query(my_query.ToUri())
self.assert_(isinstance(result, atom.Feed))
service = gdata.base.service.GBaseService(username, password)
query = gdata.base.service.BaseQuery()
query.feed = '/base/feeds/snippets'
query.bq = 'digital camera'
feed = service.Query(query.ToUri())
def testQueryWithConverter(self):
my_query = gdata.base.service.BaseQuery(feed='/base/feeds/snippets')
my_query['max-results'] = '1'
my_query.bq = 'digital camera [item type: products]'
result = self.gd_client.Query(my_query.ToUri(),
converter=gdata.base.GBaseSnippetFeedFromString)
self.assert_(isinstance(result, gdata.base.GBaseSnippetFeed))
def testCorrectReturnTypes(self):
q = gdata.base.service.BaseQuery()
q.feed = '/base/feeds/snippets'
q.bq = 'digital camera'
result = self.gd_client.QuerySnippetsFeed(q.ToUri())
self.assert_(isinstance(result, gdata.base.GBaseSnippetFeed))
q.feed = '/base/feeds/attributes'
result = self.gd_client.QueryAttributesFeed(q.ToUri())
self.assert_(isinstance(result, gdata.base.GBaseAttributesFeed))
q = gdata.base.service.BaseQuery()
q.feed = '/base/feeds/itemtypes/en_US'
result = self.gd_client.QueryItemTypesFeed(q.ToUri())
self.assert_(isinstance(result, gdata.base.GBaseItemTypesFeed))
q = gdata.base.service.BaseQuery()
q.feed = '/base/feeds/locales'
result = self.gd_client.QueryLocalesFeed(q.ToUri())
self.assert_(isinstance(result, gdata.base.GBaseLocalesFeed))
def testInsertItemUpdateItemAndDeleteItem(self):
try:
self.gd_client.ProgrammaticLogin()
self.assert_(self.gd_client.GetClientLoginToken() is not None)
self.assert_(self.gd_client.captcha_token is None)
self.assert_(self.gd_client.captcha_url is None)
except gdata.service.CaptchaRequired:
self.fail('Required Captcha')
proposed_item = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY)
result = self.gd_client.InsertItem(proposed_item)
item_id = result.id.text
self.assertEquals(result.id.text != None, True)
updated_item = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY)
updated_item.label[0].text = 'Test Item'
result = self.gd_client.UpdateItem(item_id, updated_item)
# Try to update an incorrect item_id.
try:
result = self.gd_client.UpdateItem(item_id + '2', updated_item)
self.fail()
except gdata.service.RequestError:
pass
result = self.gd_client.DeleteItem(item_id)
self.assert_(result)
# Delete and already deleted item.
try:
result = self.gd_client.DeleteItem(item_id)
self.fail()
except gdata.service.RequestError:
pass
def testInsertItemUpdateItemAndDeleteItemWithConverter(self):
try:
self.gd_client.ProgrammaticLogin()
self.assert_(self.gd_client.GetClientLoginToken() is not None)
self.assert_(self.gd_client.captcha_token is None)
self.assert_(self.gd_client.captcha_url is None)
except gdata.service.CaptchaRequired:
self.fail('Required Captcha')
proposed_item = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY)
result = self.gd_client.InsertItem(proposed_item,
converter=atom.EntryFromString)
self.assertEquals(isinstance(result, atom.Entry), True)
self.assertEquals(isinstance(result, gdata.base.GBaseItem), False)
item_id = result.id.text
self.assertEquals(result.id.text != None, True)
updated_item = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY)
updated_item.label[0].text = 'Test Item'
result = self.gd_client.UpdateItem(item_id, updated_item,
converter=atom.EntryFromString)
self.assertEquals(isinstance(result, atom.Entry), True)
self.assertEquals(isinstance(result, gdata.base.GBaseItem), False)
result = self.gd_client.DeleteItem(item_id)
self.assertEquals(result, True)
def testMakeBatchRequests(self):
try:
self.gd_client.ProgrammaticLogin()
self.assert_(self.gd_client.GetClientLoginToken() is not None)
self.assert_(self.gd_client.captcha_token is None)
self.assert_(self.gd_client.captcha_url is None)
except gdata.service.CaptchaRequired:
self.fail('Required Captcha')
request_feed = gdata.base.GBaseItemFeed(atom_id=atom.Id(
text='test batch'))
entry1 = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY)
entry1.title.text = 'first batch request item'
entry2 = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY)
entry2.title.text = 'second batch request item'
request_feed.AddInsert(entry1)
request_feed.AddInsert(entry2)
result_feed = self.gd_client.ExecuteBatch(request_feed)
self.assertEquals(result_feed.entry[0].batch_status.code, '201')
self.assertEquals(result_feed.entry[0].batch_status.reason, 'Created')
self.assertEquals(result_feed.entry[0].title.text, 'first batch request item')
self.assertEquals(result_feed.entry[0].item_type.text, 'products')
self.assertEquals(result_feed.entry[1].batch_status.code, '201')
self.assertEquals(result_feed.entry[1].batch_status.reason, 'Created')
self.assertEquals(result_feed.entry[1].title.text, 'second batch request item')
# Now delete the newly created items.
request_feed = gdata.base.GBaseItemFeed(atom_id=atom.Id(
text='test deletions'))
request_feed.AddDelete(entry=result_feed.entry[0])
request_feed.AddDelete(entry=result_feed.entry[1])
self.assertEquals(request_feed.entry[0].batch_operation.type,
gdata.BATCH_DELETE)
self.assertEquals(request_feed.entry[1].batch_operation.type,
gdata.BATCH_DELETE)
result_feed = self.gd_client.ExecuteBatch(request_feed)
self.assertEquals(result_feed.entry[0].batch_status.code, '200')
self.assertEquals(result_feed.entry[0].batch_status.reason, 'Success')
self.assertEquals(result_feed.entry[0].title.text, 'first batch request item')
self.assertEquals(result_feed.entry[1].batch_status.code, '200')
self.assertEquals(result_feed.entry[1].batch_status.reason, 'Success')
self.assertEquals(result_feed.entry[1].title.text, 'second batch request item')
if __name__ == '__main__':
print ('Google Base Tests\nNOTE: Please run these tests only with a test '
'account. The tests may delete or update your data.')
username = raw_input('Please enter your username: ')
password = getpass.getpass()
unittest.main()
| apache-2.0 |
tal-nino/shinken | test/test_nullinheritance.py | 18 | 1350 | #!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken 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.
#
# Shinken 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 Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from shinken_test import *
class TestNullInheritance(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_nullinheritance.cfg')
# We search to see if null as value really delete the inheritance
# of a property
def test_null_inheritance(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
self.assertEqual('', svc.icon_image)
if __name__ == '__main__':
unittest.main()
| agpl-3.0 |
daltonmaag/robofab | Lib/robofab/interface/all/dialogs_legacy.py | 8 | 18412 |
"""
Dialogs.
Cross-platform and cross-application compatible. Some of them anyway.
(Not all dialogs work on PCs outside of FontLab. Some dialogs are for FontLab only. Sorry.)
Mac and FontLab implementation written by the RoboFab development team.
PC implementation by Eigi Eigendorf and is (C)2002 Eigi Eigendorf.
"""
import os
import sys
from robofab import RoboFabError
from warnings import warn
MAC = False
PC = False
haveMacfs = False
if sys.platform in ('mac', 'darwin'):
MAC = True
elif os.name == 'nt':
PC = True
else:
warn("dialogs.py only supports Mac and PC platforms.")
pyVersion = sys.version_info[:3]
inFontLab = False
try:
from FL import *
inFontLab = True
except ImportError: pass
try:
import W
hasW = True
except ImportError:
hasW = False
try:
import dialogKit
hasDialogKit = True
except ImportError:
hasDialogKit = False
try:
import EasyDialogs
hasEasyDialogs = True
except:
hasEasyDialogs = False
if MAC:
if pyVersion < (2, 3, 0):
import macfs
haveMacfs = True
elif PC and not inFontLab:
from win32com.shell import shell
import win32ui
import win32con
def _raisePlatformError(dialog):
"""error raiser"""
if MAC:
p = 'Macintosh'
elif PC:
p = 'PC'
else:
p = sys.platform
raise RoboFabError("%s is not currently available on the %s platform"%(dialog, p))
class _FontLabDialogOneList:
"""A one list dialog for FontLab. This class should not be called directly. Use the OneList function."""
def __init__(self, list, message, title='RoboFab'):
self.message = message
self.selected = None
self.list = list
self.d = Dialog(self)
self.d.size = Point(250, 250)
self.d.title = title
self.d.Center()
self.d.AddControl(LISTCONTROL, Rect(12, 30, 238, 190), "list", STYLE_LIST, self.message)
self.list_index = 0
def Run(self):
return self.d.Run()
def on_cancel(self, code):
self.selected = None
def on_ok(self, code):
self.d.GetValue('list')
# Since FLS v5.2, the GetValue() method of the Dialog() class returns
# a 'wrong' index value from the specified LISTCONTROL.
# If the selected index is n, it will return n-1. For example, when
# the index is 1, it returns 0; when it's 2, it returns 1, and so on.
# If the selection is empty, FLS v5.2 returns -2, while the old v5.0
# returned None.
# See also:
# - http://forum.fontlab.com/index.php?topic=8807.0
# - http://forum.fontlab.com/index.php?topic=9003.0
#
# Edited based on feedback from Adam Twardoch
if fl.buildnumber > 4600 and sys.platform == 'win32':
if self.list_index == -2:
self.selected = None
else:
self.selected = self.list_index + 1
else:
self.selected = self.list_index
class _FontLabDialogSearchList:
"""A dialog for searching through a list. It contains a text field and a results list FontLab. This class should not be called directly. Use the SearchList function."""
def __init__(self, aList, message, title="RoboFab"):
self.d = Dialog(self)
self.d.size = Point(250, 290)
self.d.title = title
self.d.Center()
self.message = message
self._fullContent = aList
self.possibleHits = list(aList)
self.possibleHits.sort()
self.possibleHits_index = 0
self.entryField = ""
self.selected = None
self.d.AddControl(STATICCONTROL, Rect(10, 10, 240, 30), "message", STYLE_LABEL, message)
self.d.AddControl(EDITCONTROL, Rect(10, 30, 240, aAUTO), "entryField", STYLE_EDIT, "")
self.d.AddControl(LISTCONTROL, Rect(12, 60, 238, 230), "possibleHits", STYLE_LIST, "")
def run(self):
self.d.Run()
def on_entryField(self, code):
self.d.GetValue("entryField")
entry = self.entryField
count = len(entry)
possibleHits = [
i for i in self._fullContent
if len(i) >= count
and i[:count] == entry
]
possibleHits.sort()
self.possibleHits = possibleHits
self.possibleHits_index = 0
self.d.PutValue("possibleHits")
def on_ok(self, code):
self.d.GetValue("possibleHits")
sel = self.possibleHits_index
if sel == -1:
self.selected = None
else:
self.selected = self.possibleHits[sel]
def on_cancel(self, code):
self.selected = None
class _FontLabDialogTwoFields:
"""A two field dialog for FontLab. This class should not be called directly. Use the TwoFields function."""
def __init__(self, title_1, value_1, title_2, value_2, title='RoboFab'):
self.d = Dialog(self)
self.d.size = Point(200, 125)
self.d.title = title
self.d.Center()
self.d.AddControl(EDITCONTROL, Rect(120, 10, aIDENT2, aAUTO), "v1edit", STYLE_EDIT, title_1)
self.d.AddControl(EDITCONTROL, Rect(120, 40, aIDENT2, aAUTO), "v2edit", STYLE_EDIT, title_2)
self.v1edit = value_1
self.v2edit = value_2
def Run(self):
return self.d.Run()
def on_cancel(self, code):
self.v1edit = None
self.v2edit = None
def on_ok(self, code):
self.d.GetValue("v1edit")
self.d.GetValue("v2edit")
self.v1 = self.v1edit
self.v2 = self.v2edit
class _FontLabDialogTwoChecks:
"""A two check box dialog for FontLab. This class should not be called directly. Use the TwoChecks function."""
def __init__(self, title_1, title_2, value1=1, value2=1, title='RoboFab'):
self.d = Dialog(self)
self.d.size = Point(200, 105)
self.d.title = title
self.d.Center()
self.d.AddControl(CHECKBOXCONTROL, Rect(10, 10, aIDENT2, aAUTO), "check1", STYLE_CHECKBOX, title_1)
self.d.AddControl(CHECKBOXCONTROL, Rect(10, 30, aIDENT2, aAUTO), "check2", STYLE_CHECKBOX, title_2)
self.check1 = value1
self.check2 = value2
def Run(self):
return self.d.Run()
def on_cancel(self, code):
self.check1 = None
self.check2 = None
def on_ok(self, code):
self.d.GetValue("check1")
self.d.GetValue("check2")
class _FontLabDialogAskString:
"""A one simple string prompt dialog for FontLab. This class should not be called directly. Use the GetString function."""
def __init__(self, message, value, title='RoboFab'):
self.d = Dialog(self)
self.d.size = Point(350, 130)
self.d.title = title
self.d.Center()
self.d.AddControl(STATICCONTROL, Rect(aIDENT, aIDENT, aIDENT, aAUTO), "label", STYLE_LABEL, message)
self.d.AddControl(EDITCONTROL, Rect(aIDENT, 40, aIDENT, aAUTO), "value", STYLE_EDIT, '')
self.value=value
def Run(self):
return self.d.Run()
def on_cancel(self, code):
self.value = None
def on_ok(self, code):
self.d.GetValue("value")
class _FontLabDialogMessage:
"""A simple message dialog for FontLab. This class should not be called directly. Use the SimpleMessage function."""
def __init__(self, message, title='RoboFab'):
self.d = Dialog(self)
self.d.size = Point(350, 130)
self.d.title = title
self.d.Center()
self.d.AddControl(STATICCONTROL, Rect(aIDENT, aIDENT, aIDENT, 80), "label", STYLE_LABEL, message)
def Run(self):
return self.d.Run()
class _FontLabDialogGetYesNoCancel:
"""A yes no cancel message dialog for FontLab. This class should not be called directly. Use the YesNoCancel function."""
def __init__(self, message, title='RoboFab'):
self.d = Dialog(self)
self.d.size = Point(350, 130)
self.d.title = title
self.d.Center()
self.d.ok = 'Yes'
self.d.AddControl(STATICCONTROL, Rect(aIDENT, aIDENT, aIDENT, 80), "label", STYLE_LABEL, message)
self.d.AddControl(BUTTONCONTROL, Rect(100, 95, 172, 115), "button", STYLE_BUTTON, "No")
self.value = 0
def Run(self):
return self.d.Run()
def on_ok(self, code):
self.value = 1
def on_cancel(self, code):
self.value = -1
def on_button(self, code):
self.value = 0
self.d.End()
class _MacOneListW:
"""A one list dialog for Macintosh. This class should not be called directly. Use the OneList function."""
def __init__(self, list, message='Make a selection'):
import W
self.list = list
self.selected = None
self.w = W.ModalDialog((200, 240))
self.w.message = W.TextBox((10, 10, -10, 30), message)
self.w.list = W.List((10, 35, -10, -50), list)
self.w.l = W.HorizontalLine((10, -40, -10, 1), 1)
self.w.cancel = W.Button((10, -30, 87, -10), 'Cancel', self.cancel)
self.w.ok = W.Button((102, -30, 88, -10), 'OK', self.ok)
self.w.setdefaultbutton(self.w.ok)
self.w.bind('cmd.', self.w.cancel.push)
self.w.open()
def ok(self):
if len(self.w.list.getselection()) == 1:
self.selected = self.w.list.getselection()[0]
self.w.close()
def cancel(self):
self.selected = None
self.w.close()
class _MacTwoChecksW:
""" Version using W """
def __init__(self, title_1, title_2, value1=1, value2=1, title='RoboFab'):
import W
self.check1 = value1
self.check2 = value2
self.w = W.ModalDialog((200, 100))
self.w.check1 = W.CheckBox((10, 10, -10, 16), title_1, value=value1)
self.w.check2 = W.CheckBox((10, 35, -10, 16), title_2, value=value2)
self.w.l = W.HorizontalLine((10, 60, -10, 1), 1)
self.w.cancel = W.Button((10, 70, 85, 20), 'Cancel', self.cancel)
self.w.ok = W.Button((105, 70, 85, 20), 'OK', self.ok)
self.w.setdefaultbutton(self.w.ok)
self.w.bind('cmd.', self.w.cancel.push)
self.w.open()
def ok(self):
self.check1 = self.w.check1.get()
self.check2 = self.w.check2.get()
self.w.close()
def cancel(self):
self.check1 = None
self.check2 = None
self.w.close()
class ProgressBar:
def __init__(self, title='RoboFab...', ticks=0, label=''):
"""
A progress bar.
Availability: FontLab, Mac
"""
self._tickValue = 1
if inFontLab:
fl.BeginProgress(title, ticks)
elif MAC and hasEasyDialogs:
import EasyDialogs
self._bar = EasyDialogs.ProgressBar(title, maxval=ticks, label=label)
else:
_raisePlatformError('Progress')
def getCurrentTick(self):
return self._tickValue
def tick(self, tickValue=None):
"""
Tick the progress bar.
Availability: FontLab, Mac
"""
if not tickValue:
tickValue = self._tickValue
if inFontLab:
fl.TickProgress(tickValue)
elif MAC:
self._bar.set(tickValue)
else:
pass
self._tickValue = tickValue + 1
def label(self, label):
"""
Set the label on the progress bar.
Availability: Mac
"""
if inFontLab:
pass
elif MAC:
self._bar.label(label)
else:
pass
def close(self):
"""
Close the progressbar.
Availability: FontLab, Mac
"""
if inFontLab:
fl.EndProgress()
elif MAC:
del self._bar
else:
pass
def SelectFont(message="Select a font:", title='RoboFab'):
"""
Returns font instance if there is one, otherwise it returns None.
Availability: FontLab
"""
from robofab.world import RFont
if inFontLab:
list = []
for i in range(fl.count):
list.append(fl[i].full_name)
name = OneList(list, message, title)
if name is None:
return None
else:
return RFont(fl[list.index(name)])
else:
_raisePlatformError('SelectFont')
def SelectGlyph(font, message="Select a glyph:", title='RoboFab'):
"""
Returns glyph instance if there is one, otherwise it returns None.
Availability: FontLab
"""
from fontTools.misc.textTools import caselessSort
if inFontLab:
tl = font.keys()
list = caselessSort(tl)
glyphname = OneList(list, message, title)
if glyphname is None:
return None
else:
return font[glyphname]
else:
_raisePlatformError('SelectGlyph')
def FindGlyph(font, message="Search for a glyph:", title='RoboFab'):
"""
Returns glyph instance if there is one, otherwise it returns None.
Availability: FontLab
"""
if inFontLab:
glyphname = SearchList(font.keys(), message, title)
if glyphname is None:
return None
else:
return font[glyphname]
else:
_raisePlatformError('SelectGlyph')
def OneList(list, message="Select an item:", title='RoboFab'):
"""
Returns selected item, otherwise it returns None.
Availability: FontLab, Macintosh
"""
if inFontLab:
ol = _FontLabDialogOneList(list, message)
ol.Run()
selected = ol.selected
if selected is None:
return None
else:
try:
return list[selected]
except:
return None
elif MAC:
if hasW:
d = _MacOneListW(list, message)
sel = d.selected
if sel is None:
return None
else:
return list[sel]
else:
_raisePlatformError('OneList')
elif PC:
_raisePlatformError('OneList')
def SearchList(list, message="Select an item:", title='RoboFab'):
"""
Returns selected item, otherwise it returns None.
Availability: FontLab
"""
if inFontLab:
sl = _FontLabDialogSearchList(list, message, title)
sl.run()
selected = sl.selected
if selected is None:
return None
else:
return selected
else:
_raisePlatformError('SearchList')
def TwoFields(title_1="One:", value_1="0", title_2="Two:", value_2="0", title='RoboFab'):
"""
Returns (value 1, value 2).
Availability: FontLab
"""
if inFontLab:
tf = _FontLabDialogTwoFields(title_1, value_1, title_2, value_2, title)
tf.Run()
try:
v1 = tf.v1
v2 = tf.v2
return (v1, v2)
except:
return None
else:
_raisePlatformError('TwoFields')
def TwoChecks(title_1="One", title_2="Two", value1=1, value2=1, title='RoboFab'):
"""
Returns check value:
1 if check box 1 is checked
2 if check box 2 is checked
3 if both are checked
0 if neither are checked
None if cancel is clicked.
Availability: FontLab, Macintosh
"""
tc = None
if inFontLab:
tc = _FontLabDialogTwoChecks(title_1, title_2, value1, value2, title)
tc.Run()
elif MAC:
if hasW:
tc = _MacTwoChecksW(title_1, title_2, value1, value2, title)
else:
_raisePlatformError('TwoChecks')
else:
_raisePlatformError('TwoChecks')
c1 = tc.check1
c2 = tc.check2
if c1 == 1 and c2 == 0:
return 1
elif c1 == 0 and c2 == 1:
return 2
elif c1 == 1 and c2 == 1:
return 3
elif c1 == 0 and c2 == 0:
return 0
else:
return None
def Message(message, title='RoboFab'):
"""
A simple message dialog.
Availability: FontLab, Macintosh
"""
if inFontLab:
_FontLabDialogMessage(message, title).Run()
elif MAC:
import EasyDialogs
EasyDialogs.Message(message)
else:
_raisePlatformError('Message')
def AskString(message, value='', title='RoboFab'):
"""
Returns entered string.
Availability: FontLab, Macintosh
"""
if inFontLab:
askString = _FontLabDialogAskString(message, value, title)
askString.Run()
v = askString.value
if v is None:
return None
else:
return v
elif MAC:
import EasyDialogs
askString = EasyDialogs.AskString(message)
if askString is None:
return None
if len(askString) == 0:
return None
else:
return askString
else:
_raisePlatformError('GetString')
def AskYesNoCancel(message, title='RoboFab', default=0):
"""
Returns 1 for 'Yes', 0 for 'No' and -1 for 'Cancel'.
Availability: FontLab, Macintosh
("default" argument only available on Macintosh)
"""
if inFontLab:
gync = _FontLabDialogGetYesNoCancel(message, title)
gync.Run()
v = gync.value
return v
elif MAC:
import EasyDialogs
gync = EasyDialogs.AskYesNoCancel(message, default=default)
return gync
else:
_raisePlatformError('GetYesNoCancel')
def GetFile(message=None):
"""
Select file dialog. Returns path if one is selected. Otherwise it returns None.
Availability: FontLab, Macintosh, PC
"""
path = None
if MAC:
if haveMacfs:
fss, ok = macfs.PromptGetFile(message)
if ok:
path = fss.as_pathname()
else:
from robofab.interface.mac.getFileOrFolder import GetFile
path = GetFile(message)
elif PC:
if inFontLab:
if not message:
message = ''
path = fl.GetFileName(1, message, '', '')
else:
openFlags = win32con.OFN_FILEMUSTEXIST|win32con.OFN_EXPLORER
mode_open = 1
myDialog = win32ui.CreateFileDialog(mode_open,None,None,openFlags)
myDialog.SetOFNTitle(message)
is_OK = myDialog.DoModal()
if is_OK == 1:
path = myDialog.GetPathName()
else:
_raisePlatformError('GetFile')
return path
def GetFolder(message=None):
"""
Select folder dialog. Returns path if one is selected. Otherwise it returns None.
Availability: FontLab, Macintosh, PC
"""
path = None
if MAC:
if haveMacfs:
fss, ok = macfs.GetDirectory(message)
if ok:
path = fss.as_pathname()
else:
from robofab.interface.mac.getFileOrFolder import GetFileOrFolder
# This _also_ allows the user to select _files_, but given the
# package/folder dichotomy, I think we have no other choice.
path = GetFileOrFolder(message)
elif PC:
if inFontLab:
if not message:
message = ''
path = fl.GetPathName('', message)
else:
myTuple = shell.SHBrowseForFolder(0, None, message, 64)
try:
path = shell.SHGetPathFromIDList(myTuple[0])
except:
pass
else:
_raisePlatformError('GetFile')
return path
GetDirectory = GetFolder
def PutFile(message=None, fileName=None):
"""
Save file dialog. Returns path if one is entered. Otherwise it returns None.
Availability: FontLab, Macintosh, PC
"""
path = None
if MAC:
if haveMacfs:
fss, ok = macfs.StandardPutFile(message, fileName)
if ok:
path = fss.as_pathname()
else:
import EasyDialogs
path = EasyDialogs.AskFileForSave(message, savedFileName=fileName)
elif PC:
if inFontLab:
if not message:
message = ''
if not fileName:
fileName = ''
path = fl.GetFileName(0, message, fileName, '')
else:
openFlags = win32con.OFN_OVERWRITEPROMPT|win32con.OFN_EXPLORER
mode_save = 0
myDialog = win32ui.CreateFileDialog(mode_save, None, fileName, openFlags)
myDialog.SetOFNTitle(message)
is_OK = myDialog.DoModal()
if is_OK == 1:
path = myDialog.GetPathName()
else:
_raisePlatformError('GetFile')
return path
if __name__=='__main__':
import traceback
print "dialogs hasW", hasW
print "dialogs hasDialogKit", hasDialogKit
print "dialogs MAC", MAC
print "dialogs PC", PC
print "dialogs inFontLab", inFontLab
print "dialogs hasEasyDialogs", hasEasyDialogs
def tryDialog(dialogClass, args=None):
print
print "tryDialog:", dialogClass, "with args:", args
try:
if args is not None:
apply(dialogClass, args)
else:
apply(dialogClass)
except:
traceback.print_exc(limit=0)
tryDialog(TwoChecks, ('hello', 'world', 1, 0, 'ugh'))
tryDialog(TwoFields)
tryDialog(TwoChecks, ('hello', 'world', 1, 0, 'ugh'))
tryDialog(OneList, (['a', 'b', 'c'], 'hello world'))
tryDialog(Message, ('hello world',))
tryDialog(AskString, ('hello world',))
tryDialog(AskYesNoCancel, ('hello world',))
try:
b = ProgressBar('hello', 50, 'world')
for i in range(50):
if i == 25:
b.label('ugh.')
b.tick(i)
b.close()
except:
traceback.print_exc(limit=0)
| bsd-3-clause |
buildbot/buildbot | worker/buildbot_worker/test/unit/test_scripts_start.py | 17 | 2464 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import absolute_import
from __future__ import print_function
import mock
from twisted.trial import unittest
from buildbot_worker.scripts import start
from buildbot_worker.test.util import misc
class TestStartCommand(unittest.TestCase, misc.IsWorkerDirMixin):
"""
Test buildbot_worker.scripts.startup.startCommand()
"""
def test_start_command_bad_basedir(self):
"""
test calling startCommand() with invalid basedir path
"""
# patch isWorkerDir() to fail
self.setupUpIsWorkerDir(False)
# call startCommand() and check that correct exit code is returned
config = {"basedir": "dummy"}
self.assertEqual(start.startCommand(config), 1, "unexpected exit code")
# check that isWorkerDir was called with correct argument
self.isWorkerDir.assert_called_once_with("dummy")
def test_start_command_good(self):
"""
test successful startCommand() call
"""
# patch basedir check to always succeed
self.setupUpIsWorkerDir(True)
# patch startWorker() to do nothing
mocked_startWorker = mock.Mock(return_value=0)
self.patch(start, "startWorker", mocked_startWorker)
config = {"basedir": "dummy", "nodaemon": False, "quiet": False}
self.assertEqual(start.startCommand(config), 0, "unexpected exit code")
# check that isWorkerDir() and startWorker() were called
# with correct argument
self.isWorkerDir.assert_called_once_with("dummy")
mocked_startWorker.assert_called_once_with(config["basedir"],
config["quiet"],
config["nodaemon"])
| gpl-2.0 |
RobertWWong/WebDev | djangoApp/ENV/lib/python3.5/site-packages/django/contrib/gis/gdal/envelope.py | 105 | 7005 | """
The GDAL/OGR library uses an Envelope structure to hold the bounding
box information for a geometry. The envelope (bounding box) contains
two pairs of coordinates, one for the lower left coordinate and one
for the upper right coordinate:
+----------o Upper right; (max_x, max_y)
| |
| |
| |
Lower left (min_x, min_y) o----------+
"""
from ctypes import Structure, c_double
from django.contrib.gis.gdal.error import GDALException
# The OGR definition of an Envelope is a C structure containing four doubles.
# See the 'ogr_core.h' source file for more information:
# http://www.gdal.org/ogr__core_8h_source.html
class OGREnvelope(Structure):
"Represents the OGREnvelope C Structure."
_fields_ = [("MinX", c_double),
("MaxX", c_double),
("MinY", c_double),
("MaxY", c_double),
]
class Envelope(object):
"""
The Envelope object is a C structure that contains the minimum and
maximum X, Y coordinates for a rectangle bounding box. The naming
of the variables is compatible with the OGR Envelope structure.
"""
def __init__(self, *args):
"""
The initialization function may take an OGREnvelope structure, 4-element
tuple or list, or 4 individual arguments.
"""
if len(args) == 1:
if isinstance(args[0], OGREnvelope):
# OGREnvelope (a ctypes Structure) was passed in.
self._envelope = args[0]
elif isinstance(args[0], (tuple, list)):
# A tuple was passed in.
if len(args[0]) != 4:
raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
else:
self._from_sequence(args[0])
else:
raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
elif len(args) == 4:
# Individual parameters passed in.
# Thanks to ww for the help
self._from_sequence([float(a) for a in args])
else:
raise GDALException('Incorrect number (%d) of arguments.' % len(args))
# Checking the x,y coordinates
if self.min_x > self.max_x:
raise GDALException('Envelope minimum X > maximum X.')
if self.min_y > self.max_y:
raise GDALException('Envelope minimum Y > maximum Y.')
def __eq__(self, other):
"""
Returns True if the envelopes are equivalent; can compare against
other Envelopes and 4-tuples.
"""
if isinstance(other, Envelope):
return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \
(self.max_x == other.max_x) and (self.max_y == other.max_y)
elif isinstance(other, tuple) and len(other) == 4:
return (self.min_x == other[0]) and (self.min_y == other[1]) and \
(self.max_x == other[2]) and (self.max_y == other[3])
else:
raise GDALException('Equivalence testing only works with other Envelopes.')
def __str__(self):
"Returns a string representation of the tuple."
return str(self.tuple)
def _from_sequence(self, seq):
"Initializes the C OGR Envelope structure from the given sequence."
self._envelope = OGREnvelope()
self._envelope.MinX = seq[0]
self._envelope.MinY = seq[1]
self._envelope.MaxX = seq[2]
self._envelope.MaxY = seq[3]
def expand_to_include(self, *args):
"""
Modifies the envelope to expand to include the boundaries of
the passed-in 2-tuple (a point), 4-tuple (an extent) or
envelope.
"""
# We provide a number of different signatures for this method,
# and the logic here is all about converting them into a
# 4-tuple single parameter which does the actual work of
# expanding the envelope.
if len(args) == 1:
if isinstance(args[0], Envelope):
return self.expand_to_include(args[0].tuple)
elif hasattr(args[0], 'x') and hasattr(args[0], 'y'):
return self.expand_to_include(args[0].x, args[0].y, args[0].x, args[0].y)
elif isinstance(args[0], (tuple, list)):
# A tuple was passed in.
if len(args[0]) == 2:
return self.expand_to_include((args[0][0], args[0][1], args[0][0], args[0][1]))
elif len(args[0]) == 4:
(minx, miny, maxx, maxy) = args[0]
if minx < self._envelope.MinX:
self._envelope.MinX = minx
if miny < self._envelope.MinY:
self._envelope.MinY = miny
if maxx > self._envelope.MaxX:
self._envelope.MaxX = maxx
if maxy > self._envelope.MaxY:
self._envelope.MaxY = maxy
else:
raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
else:
raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
elif len(args) == 2:
# An x and an y parameter were passed in
return self.expand_to_include((args[0], args[1], args[0], args[1]))
elif len(args) == 4:
# Individual parameters passed in.
return self.expand_to_include(args)
else:
raise GDALException('Incorrect number (%d) of arguments.' % len(args[0]))
@property
def min_x(self):
"Returns the value of the minimum X coordinate."
return self._envelope.MinX
@property
def min_y(self):
"Returns the value of the minimum Y coordinate."
return self._envelope.MinY
@property
def max_x(self):
"Returns the value of the maximum X coordinate."
return self._envelope.MaxX
@property
def max_y(self):
"Returns the value of the maximum Y coordinate."
return self._envelope.MaxY
@property
def ur(self):
"Returns the upper-right coordinate."
return (self.max_x, self.max_y)
@property
def ll(self):
"Returns the lower-left coordinate."
return (self.min_x, self.min_y)
@property
def tuple(self):
"Returns a tuple representing the envelope."
return (self.min_x, self.min_y, self.max_x, self.max_y)
@property
def wkt(self):
"Returns WKT representing a Polygon for this envelope."
# TODO: Fix significant figures.
return 'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))' % \
(self.min_x, self.min_y, self.min_x, self.max_y,
self.max_x, self.max_y, self.max_x, self.min_y,
self.min_x, self.min_y)
| mit |
xxd3vin/spp-sdk | opt/Python27/Lib/test/test_netrc.py | 6 | 1125 |
import netrc, os, unittest, sys
from test import test_support
TEST_NETRC = """
machine foo login log1 password pass1 account acct1
macdef macro1
line1
line2
macdef macro2
line3
line4
default login log2 password pass2
"""
temp_filename = test_support.TESTFN
class NetrcTestCase(unittest.TestCase):
def setUp (self):
mode = 'w'
if sys.platform not in ['cygwin']:
mode += 't'
fp = open(temp_filename, mode)
fp.write(TEST_NETRC)
fp.close()
self.netrc = netrc.netrc(temp_filename)
def tearDown (self):
del self.netrc
os.unlink(temp_filename)
def test_case_1(self):
self.assertTrue(self.netrc.macros == {'macro1':['line1\n', 'line2\n'],
'macro2':['line3\n', 'line4\n']}
)
self.assertTrue(self.netrc.hosts['foo'] == ('log1', 'acct1', 'pass1'))
self.assertTrue(self.netrc.hosts['default'] == ('log2', None, 'pass2'))
def test_main():
test_support.run_unittest(NetrcTestCase)
if __name__ == "__main__":
test_main()
| mit |
zrax/moul-scripts | Python/system/encodings/cp437.py | 593 | 34820 | """ Python Character Mapping Codec cp437 generated from 'VENDORS/MICSFT/PC/CP437.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp437',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS
0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE
0x0098: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00a2, # CENT SIGN
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00a5, # YEN SIGN
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE
0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE
0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR
0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Decoding Table
decoding_table = (
u'\x00' # 0x0000 -> NULL
u'\x01' # 0x0001 -> START OF HEADING
u'\x02' # 0x0002 -> START OF TEXT
u'\x03' # 0x0003 -> END OF TEXT
u'\x04' # 0x0004 -> END OF TRANSMISSION
u'\x05' # 0x0005 -> ENQUIRY
u'\x06' # 0x0006 -> ACKNOWLEDGE
u'\x07' # 0x0007 -> BELL
u'\x08' # 0x0008 -> BACKSPACE
u'\t' # 0x0009 -> HORIZONTAL TABULATION
u'\n' # 0x000a -> LINE FEED
u'\x0b' # 0x000b -> VERTICAL TABULATION
u'\x0c' # 0x000c -> FORM FEED
u'\r' # 0x000d -> CARRIAGE RETURN
u'\x0e' # 0x000e -> SHIFT OUT
u'\x0f' # 0x000f -> SHIFT IN
u'\x10' # 0x0010 -> DATA LINK ESCAPE
u'\x11' # 0x0011 -> DEVICE CONTROL ONE
u'\x12' # 0x0012 -> DEVICE CONTROL TWO
u'\x13' # 0x0013 -> DEVICE CONTROL THREE
u'\x14' # 0x0014 -> DEVICE CONTROL FOUR
u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x0016 -> SYNCHRONOUS IDLE
u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x0018 -> CANCEL
u'\x19' # 0x0019 -> END OF MEDIUM
u'\x1a' # 0x001a -> SUBSTITUTE
u'\x1b' # 0x001b -> ESCAPE
u'\x1c' # 0x001c -> FILE SEPARATOR
u'\x1d' # 0x001d -> GROUP SEPARATOR
u'\x1e' # 0x001e -> RECORD SEPARATOR
u'\x1f' # 0x001f -> UNIT SEPARATOR
u' ' # 0x0020 -> SPACE
u'!' # 0x0021 -> EXCLAMATION MARK
u'"' # 0x0022 -> QUOTATION MARK
u'#' # 0x0023 -> NUMBER SIGN
u'$' # 0x0024 -> DOLLAR SIGN
u'%' # 0x0025 -> PERCENT SIGN
u'&' # 0x0026 -> AMPERSAND
u"'" # 0x0027 -> APOSTROPHE
u'(' # 0x0028 -> LEFT PARENTHESIS
u')' # 0x0029 -> RIGHT PARENTHESIS
u'*' # 0x002a -> ASTERISK
u'+' # 0x002b -> PLUS SIGN
u',' # 0x002c -> COMMA
u'-' # 0x002d -> HYPHEN-MINUS
u'.' # 0x002e -> FULL STOP
u'/' # 0x002f -> SOLIDUS
u'0' # 0x0030 -> DIGIT ZERO
u'1' # 0x0031 -> DIGIT ONE
u'2' # 0x0032 -> DIGIT TWO
u'3' # 0x0033 -> DIGIT THREE
u'4' # 0x0034 -> DIGIT FOUR
u'5' # 0x0035 -> DIGIT FIVE
u'6' # 0x0036 -> DIGIT SIX
u'7' # 0x0037 -> DIGIT SEVEN
u'8' # 0x0038 -> DIGIT EIGHT
u'9' # 0x0039 -> DIGIT NINE
u':' # 0x003a -> COLON
u';' # 0x003b -> SEMICOLON
u'<' # 0x003c -> LESS-THAN SIGN
u'=' # 0x003d -> EQUALS SIGN
u'>' # 0x003e -> GREATER-THAN SIGN
u'?' # 0x003f -> QUESTION MARK
u'@' # 0x0040 -> COMMERCIAL AT
u'A' # 0x0041 -> LATIN CAPITAL LETTER A
u'B' # 0x0042 -> LATIN CAPITAL LETTER B
u'C' # 0x0043 -> LATIN CAPITAL LETTER C
u'D' # 0x0044 -> LATIN CAPITAL LETTER D
u'E' # 0x0045 -> LATIN CAPITAL LETTER E
u'F' # 0x0046 -> LATIN CAPITAL LETTER F
u'G' # 0x0047 -> LATIN CAPITAL LETTER G
u'H' # 0x0048 -> LATIN CAPITAL LETTER H
u'I' # 0x0049 -> LATIN CAPITAL LETTER I
u'J' # 0x004a -> LATIN CAPITAL LETTER J
u'K' # 0x004b -> LATIN CAPITAL LETTER K
u'L' # 0x004c -> LATIN CAPITAL LETTER L
u'M' # 0x004d -> LATIN CAPITAL LETTER M
u'N' # 0x004e -> LATIN CAPITAL LETTER N
u'O' # 0x004f -> LATIN CAPITAL LETTER O
u'P' # 0x0050 -> LATIN CAPITAL LETTER P
u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
u'R' # 0x0052 -> LATIN CAPITAL LETTER R
u'S' # 0x0053 -> LATIN CAPITAL LETTER S
u'T' # 0x0054 -> LATIN CAPITAL LETTER T
u'U' # 0x0055 -> LATIN CAPITAL LETTER U
u'V' # 0x0056 -> LATIN CAPITAL LETTER V
u'W' # 0x0057 -> LATIN CAPITAL LETTER W
u'X' # 0x0058 -> LATIN CAPITAL LETTER X
u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
u'Z' # 0x005a -> LATIN CAPITAL LETTER Z
u'[' # 0x005b -> LEFT SQUARE BRACKET
u'\\' # 0x005c -> REVERSE SOLIDUS
u']' # 0x005d -> RIGHT SQUARE BRACKET
u'^' # 0x005e -> CIRCUMFLEX ACCENT
u'_' # 0x005f -> LOW LINE
u'`' # 0x0060 -> GRAVE ACCENT
u'a' # 0x0061 -> LATIN SMALL LETTER A
u'b' # 0x0062 -> LATIN SMALL LETTER B
u'c' # 0x0063 -> LATIN SMALL LETTER C
u'd' # 0x0064 -> LATIN SMALL LETTER D
u'e' # 0x0065 -> LATIN SMALL LETTER E
u'f' # 0x0066 -> LATIN SMALL LETTER F
u'g' # 0x0067 -> LATIN SMALL LETTER G
u'h' # 0x0068 -> LATIN SMALL LETTER H
u'i' # 0x0069 -> LATIN SMALL LETTER I
u'j' # 0x006a -> LATIN SMALL LETTER J
u'k' # 0x006b -> LATIN SMALL LETTER K
u'l' # 0x006c -> LATIN SMALL LETTER L
u'm' # 0x006d -> LATIN SMALL LETTER M
u'n' # 0x006e -> LATIN SMALL LETTER N
u'o' # 0x006f -> LATIN SMALL LETTER O
u'p' # 0x0070 -> LATIN SMALL LETTER P
u'q' # 0x0071 -> LATIN SMALL LETTER Q
u'r' # 0x0072 -> LATIN SMALL LETTER R
u's' # 0x0073 -> LATIN SMALL LETTER S
u't' # 0x0074 -> LATIN SMALL LETTER T
u'u' # 0x0075 -> LATIN SMALL LETTER U
u'v' # 0x0076 -> LATIN SMALL LETTER V
u'w' # 0x0077 -> LATIN SMALL LETTER W
u'x' # 0x0078 -> LATIN SMALL LETTER X
u'y' # 0x0079 -> LATIN SMALL LETTER Y
u'z' # 0x007a -> LATIN SMALL LETTER Z
u'{' # 0x007b -> LEFT CURLY BRACKET
u'|' # 0x007c -> VERTICAL LINE
u'}' # 0x007d -> RIGHT CURLY BRACKET
u'~' # 0x007e -> TILDE
u'\x7f' # 0x007f -> DELETE
u'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE
u'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE
u'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA
u'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE
u'\xef' # 0x008b -> LATIN SMALL LETTER I WITH DIAERESIS
u'\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\xec' # 0x008d -> LATIN SMALL LETTER I WITH GRAVE
u'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE
u'\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE
u'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xf2' # 0x0095 -> LATIN SMALL LETTER O WITH GRAVE
u'\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\xf9' # 0x0097 -> LATIN SMALL LETTER U WITH GRAVE
u'\xff' # 0x0098 -> LATIN SMALL LETTER Y WITH DIAERESIS
u'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xa2' # 0x009b -> CENT SIGN
u'\xa3' # 0x009c -> POUND SIGN
u'\xa5' # 0x009d -> YEN SIGN
u'\u20a7' # 0x009e -> PESETA SIGN
u'\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK
u'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE
u'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE
u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE
u'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE
u'\xf1' # 0x00a4 -> LATIN SMALL LETTER N WITH TILDE
u'\xd1' # 0x00a5 -> LATIN CAPITAL LETTER N WITH TILDE
u'\xaa' # 0x00a6 -> FEMININE ORDINAL INDICATOR
u'\xba' # 0x00a7 -> MASCULINE ORDINAL INDICATOR
u'\xbf' # 0x00a8 -> INVERTED QUESTION MARK
u'\u2310' # 0x00a9 -> REVERSED NOT SIGN
u'\xac' # 0x00aa -> NOT SIGN
u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF
u'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER
u'\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK
u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u2591' # 0x00b0 -> LIGHT SHADE
u'\u2592' # 0x00b1 -> MEDIUM SHADE
u'\u2593' # 0x00b2 -> DARK SHADE
u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL
u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT
u'\u2561' # 0x00b5 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
u'\u2562' # 0x00b6 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
u'\u2556' # 0x00b7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
u'\u2555' # 0x00b8 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT
u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL
u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT
u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT
u'\u255c' # 0x00bd -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
u'\u255b' # 0x00be -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT
u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT
u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL
u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT
u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL
u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
u'\u255e' # 0x00c6 -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
u'\u255f' # 0x00c7 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT
u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT
u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL
u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL
u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
u'\u2567' # 0x00cf -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
u'\u2568' # 0x00d0 -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
u'\u2564' # 0x00d1 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
u'\u2565' # 0x00d2 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
u'\u2559' # 0x00d3 -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
u'\u2558' # 0x00d4 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
u'\u2552' # 0x00d5 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
u'\u2553' # 0x00d6 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
u'\u256b' # 0x00d7 -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
u'\u256a' # 0x00d8 -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT
u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT
u'\u2588' # 0x00db -> FULL BLOCK
u'\u2584' # 0x00dc -> LOWER HALF BLOCK
u'\u258c' # 0x00dd -> LEFT HALF BLOCK
u'\u2590' # 0x00de -> RIGHT HALF BLOCK
u'\u2580' # 0x00df -> UPPER HALF BLOCK
u'\u03b1' # 0x00e0 -> GREEK SMALL LETTER ALPHA
u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S
u'\u0393' # 0x00e2 -> GREEK CAPITAL LETTER GAMMA
u'\u03c0' # 0x00e3 -> GREEK SMALL LETTER PI
u'\u03a3' # 0x00e4 -> GREEK CAPITAL LETTER SIGMA
u'\u03c3' # 0x00e5 -> GREEK SMALL LETTER SIGMA
u'\xb5' # 0x00e6 -> MICRO SIGN
u'\u03c4' # 0x00e7 -> GREEK SMALL LETTER TAU
u'\u03a6' # 0x00e8 -> GREEK CAPITAL LETTER PHI
u'\u0398' # 0x00e9 -> GREEK CAPITAL LETTER THETA
u'\u03a9' # 0x00ea -> GREEK CAPITAL LETTER OMEGA
u'\u03b4' # 0x00eb -> GREEK SMALL LETTER DELTA
u'\u221e' # 0x00ec -> INFINITY
u'\u03c6' # 0x00ed -> GREEK SMALL LETTER PHI
u'\u03b5' # 0x00ee -> GREEK SMALL LETTER EPSILON
u'\u2229' # 0x00ef -> INTERSECTION
u'\u2261' # 0x00f0 -> IDENTICAL TO
u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN
u'\u2265' # 0x00f2 -> GREATER-THAN OR EQUAL TO
u'\u2264' # 0x00f3 -> LESS-THAN OR EQUAL TO
u'\u2320' # 0x00f4 -> TOP HALF INTEGRAL
u'\u2321' # 0x00f5 -> BOTTOM HALF INTEGRAL
u'\xf7' # 0x00f6 -> DIVISION SIGN
u'\u2248' # 0x00f7 -> ALMOST EQUAL TO
u'\xb0' # 0x00f8 -> DEGREE SIGN
u'\u2219' # 0x00f9 -> BULLET OPERATOR
u'\xb7' # 0x00fa -> MIDDLE DOT
u'\u221a' # 0x00fb -> SQUARE ROOT
u'\u207f' # 0x00fc -> SUPERSCRIPT LATIN SMALL LETTER N
u'\xb2' # 0x00fd -> SUPERSCRIPT TWO
u'\u25a0' # 0x00fe -> BLACK SQUARE
u'\xa0' # 0x00ff -> NO-BREAK SPACE
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # NULL
0x0001: 0x0001, # START OF HEADING
0x0002: 0x0002, # START OF TEXT
0x0003: 0x0003, # END OF TEXT
0x0004: 0x0004, # END OF TRANSMISSION
0x0005: 0x0005, # ENQUIRY
0x0006: 0x0006, # ACKNOWLEDGE
0x0007: 0x0007, # BELL
0x0008: 0x0008, # BACKSPACE
0x0009: 0x0009, # HORIZONTAL TABULATION
0x000a: 0x000a, # LINE FEED
0x000b: 0x000b, # VERTICAL TABULATION
0x000c: 0x000c, # FORM FEED
0x000d: 0x000d, # CARRIAGE RETURN
0x000e: 0x000e, # SHIFT OUT
0x000f: 0x000f, # SHIFT IN
0x0010: 0x0010, # DATA LINK ESCAPE
0x0011: 0x0011, # DEVICE CONTROL ONE
0x0012: 0x0012, # DEVICE CONTROL TWO
0x0013: 0x0013, # DEVICE CONTROL THREE
0x0014: 0x0014, # DEVICE CONTROL FOUR
0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE
0x0016: 0x0016, # SYNCHRONOUS IDLE
0x0017: 0x0017, # END OF TRANSMISSION BLOCK
0x0018: 0x0018, # CANCEL
0x0019: 0x0019, # END OF MEDIUM
0x001a: 0x001a, # SUBSTITUTE
0x001b: 0x001b, # ESCAPE
0x001c: 0x001c, # FILE SEPARATOR
0x001d: 0x001d, # GROUP SEPARATOR
0x001e: 0x001e, # RECORD SEPARATOR
0x001f: 0x001f, # UNIT SEPARATOR
0x0020: 0x0020, # SPACE
0x0021: 0x0021, # EXCLAMATION MARK
0x0022: 0x0022, # QUOTATION MARK
0x0023: 0x0023, # NUMBER SIGN
0x0024: 0x0024, # DOLLAR SIGN
0x0025: 0x0025, # PERCENT SIGN
0x0026: 0x0026, # AMPERSAND
0x0027: 0x0027, # APOSTROPHE
0x0028: 0x0028, # LEFT PARENTHESIS
0x0029: 0x0029, # RIGHT PARENTHESIS
0x002a: 0x002a, # ASTERISK
0x002b: 0x002b, # PLUS SIGN
0x002c: 0x002c, # COMMA
0x002d: 0x002d, # HYPHEN-MINUS
0x002e: 0x002e, # FULL STOP
0x002f: 0x002f, # SOLIDUS
0x0030: 0x0030, # DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE
0x0032: 0x0032, # DIGIT TWO
0x0033: 0x0033, # DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE
0x003a: 0x003a, # COLON
0x003b: 0x003b, # SEMICOLON
0x003c: 0x003c, # LESS-THAN SIGN
0x003d: 0x003d, # EQUALS SIGN
0x003e: 0x003e, # GREATER-THAN SIGN
0x003f: 0x003f, # QUESTION MARK
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET
0x005c: 0x005c, # REVERSE SOLIDUS
0x005d: 0x005d, # RIGHT SQUARE BRACKET
0x005e: 0x005e, # CIRCUMFLEX ACCENT
0x005f: 0x005f, # LOW LINE
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET
0x007c: 0x007c, # VERTICAL LINE
0x007d: 0x007d, # RIGHT CURLY BRACKET
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # DELETE
0x00a0: 0x00ff, # NO-BREAK SPACE
0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK
0x00a2: 0x009b, # CENT SIGN
0x00a3: 0x009c, # POUND SIGN
0x00a5: 0x009d, # YEN SIGN
0x00aa: 0x00a6, # FEMININE ORDINAL INDICATOR
0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00ac: 0x00aa, # NOT SIGN
0x00b0: 0x00f8, # DEGREE SIGN
0x00b1: 0x00f1, # PLUS-MINUS SIGN
0x00b2: 0x00fd, # SUPERSCRIPT TWO
0x00b5: 0x00e6, # MICRO SIGN
0x00b7: 0x00fa, # MIDDLE DOT
0x00ba: 0x00a7, # MASCULINE ORDINAL INDICATOR
0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER
0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF
0x00bf: 0x00a8, # INVERTED QUESTION MARK
0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE
0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA
0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE
0x00d1: 0x00a5, # LATIN CAPITAL LETTER N WITH TILDE
0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S
0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE
0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE
0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS
0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE
0x00e6: 0x0091, # LATIN SMALL LIGATURE AE
0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA
0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE
0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE
0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS
0x00ec: 0x008d, # LATIN SMALL LETTER I WITH GRAVE
0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE
0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x00ef: 0x008b, # LATIN SMALL LETTER I WITH DIAERESIS
0x00f1: 0x00a4, # LATIN SMALL LETTER N WITH TILDE
0x00f2: 0x0095, # LATIN SMALL LETTER O WITH GRAVE
0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE
0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS
0x00f7: 0x00f6, # DIVISION SIGN
0x00f9: 0x0097, # LATIN SMALL LETTER U WITH GRAVE
0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE
0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS
0x00ff: 0x0098, # LATIN SMALL LETTER Y WITH DIAERESIS
0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK
0x0393: 0x00e2, # GREEK CAPITAL LETTER GAMMA
0x0398: 0x00e9, # GREEK CAPITAL LETTER THETA
0x03a3: 0x00e4, # GREEK CAPITAL LETTER SIGMA
0x03a6: 0x00e8, # GREEK CAPITAL LETTER PHI
0x03a9: 0x00ea, # GREEK CAPITAL LETTER OMEGA
0x03b1: 0x00e0, # GREEK SMALL LETTER ALPHA
0x03b4: 0x00eb, # GREEK SMALL LETTER DELTA
0x03b5: 0x00ee, # GREEK SMALL LETTER EPSILON
0x03c0: 0x00e3, # GREEK SMALL LETTER PI
0x03c3: 0x00e5, # GREEK SMALL LETTER SIGMA
0x03c4: 0x00e7, # GREEK SMALL LETTER TAU
0x03c6: 0x00ed, # GREEK SMALL LETTER PHI
0x207f: 0x00fc, # SUPERSCRIPT LATIN SMALL LETTER N
0x20a7: 0x009e, # PESETA SIGN
0x2219: 0x00f9, # BULLET OPERATOR
0x221a: 0x00fb, # SQUARE ROOT
0x221e: 0x00ec, # INFINITY
0x2229: 0x00ef, # INTERSECTION
0x2248: 0x00f7, # ALMOST EQUAL TO
0x2261: 0x00f0, # IDENTICAL TO
0x2264: 0x00f3, # LESS-THAN OR EQUAL TO
0x2265: 0x00f2, # GREATER-THAN OR EQUAL TO
0x2310: 0x00a9, # REVERSED NOT SIGN
0x2320: 0x00f4, # TOP HALF INTEGRAL
0x2321: 0x00f5, # BOTTOM HALF INTEGRAL
0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL
0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL
0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT
0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT
0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL
0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL
0x2552: 0x00d5, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553: 0x00d6, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2555: 0x00b8, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2556: 0x00b7, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x2558: 0x00d4, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2559: 0x00d3, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x255b: 0x00be, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x255c: 0x00bd, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT
0x255e: 0x00c6, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255f: 0x00c7, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2561: 0x00b5, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562: 0x00b6, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2564: 0x00d1, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565: 0x00d2, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2567: 0x00cf, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568: 0x00d0, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x256a: 0x00d8, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x256b: 0x00d7, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2580: 0x00df, # UPPER HALF BLOCK
0x2584: 0x00dc, # LOWER HALF BLOCK
0x2588: 0x00db, # FULL BLOCK
0x258c: 0x00dd, # LEFT HALF BLOCK
0x2590: 0x00de, # RIGHT HALF BLOCK
0x2591: 0x00b0, # LIGHT SHADE
0x2592: 0x00b1, # MEDIUM SHADE
0x2593: 0x00b2, # DARK SHADE
0x25a0: 0x00fe, # BLACK SQUARE
}
| gpl-3.0 |
RedHatInsights/insights-core | insights/parsers/tests/test_chkconfig.py | 1 | 3835 | import pytest
from ...tests import context_wrap
from ..chkconfig import ChkConfig
from insights.parsers import SkipException
SERVICES = """
auditd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
crond 0:off 1:off 2:on 3:on 4:on 5:on 6:off
iptables 0:off 1:off 2:on 3:on 4:on 5:on 6:off
kdump 0:off 1:off 2:off 3:on 4:on 5:on 6:off
restorecond 0:off 1:off 2:off 3:off 4:off 5:off 6:off
xinetd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
rexec: off
rlogin: off
rsh: on
tcpmux-server: off
telnet: on
""".strip()
RHEL_73_SERVICES = """
Note: This output shows SysV services only and does not include native
systemd services. SysV configuration data might be overridden by native
systemd configuration.
If you want to list systemd services use 'systemctl list-unit-files'.
To see services enabled on particular target use
'systemctl list-dependencies [target]'.
netconsole 0:off 1:off 2:off 3:off 4:off 5:off 6:off
network 0:off 1:off 2:on 3:on 4:on 5:on 6:off
rhnsd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
xinetd based services:
chargen-dgram: off
chargen-stream: off
daytime-dgram: off
daytime-stream: off
discard-dgram: off
discard-stream: off
echo-dgram: off
echo-stream: off
rsync: on
tcpmux-server: off
time-dgram: off
time-stream: off
"""
SERVICES_NG = """
Note: This output shows SysV services only and does not include native
systemd services. SysV configuration data might be overridden by native
systemd configuration.
If you want to list systemd services use 'systemctl list-unit-files'.
To see services enabled on particular target use
'systemctl list-dependencies [target]'.
"""
def test_chkconfig():
context = context_wrap(SERVICES)
chkconfig = ChkConfig(context)
assert len(chkconfig.services) == 11
assert len(chkconfig.parsed_lines) == 11
assert chkconfig.is_on('crond')
assert chkconfig.is_on('kdump')
assert chkconfig.is_on('telnet')
assert not chkconfig.is_on('restorecond')
assert not chkconfig.is_on('rlogin')
def test_levels_on():
chkconfig = ChkConfig(context_wrap(SERVICES))
assert chkconfig.levels_on('crond') == set(['2', '3', '4', '5'])
assert chkconfig.levels_on('telnet') == set(['2', '3', '4', '5'])
assert chkconfig.levels_on('rlogin') == set([])
with pytest.raises(KeyError):
assert chkconfig.levels_on('bad_name')
def test_levels_off():
chkconfig = ChkConfig(context_wrap(SERVICES))
assert chkconfig.levels_off('crond') == set(['0', '1', '6'])
assert chkconfig.levels_off('telnet') == set(['0', '1', '6'])
assert chkconfig.levels_off('rlogin') == set(['0', '1', '2', '3',
'4', '5', '6'])
with pytest.raises(KeyError):
assert chkconfig.levels_off('bad_name')
def test_rhel_73():
chkconfig = ChkConfig(context_wrap(RHEL_73_SERVICES))
assert sorted(chkconfig.level_states.keys()) == sorted([
'netconsole', 'network', 'rhnsd', 'chargen-dgram', 'chargen-stream',
'daytime-dgram', 'daytime-stream', 'discard-dgram', 'discard-stream',
'echo-dgram', 'echo-stream', 'rsync', 'tcpmux-server', 'time-dgram',
'time-stream',
])
assert chkconfig.levels_off('netconsole') == set(['0', '1', '2', '3', '4', '5', '6'])
assert chkconfig.levels_on('network') == set(['2', '3', '4', '5'])
assert chkconfig.levels_on('rsync') == set(['0', '1', '2', '3', '4', '5', '6'])
def test_chkconfig_ng():
with pytest.raises(SkipException):
ChkConfig(context_wrap(SERVICES_NG))
| apache-2.0 |
coffeestats/coffeestats-django | coffeestats/coffeestats/urls.py | 1 | 2864 | from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import reverse_lazy
from django.views.i18n import JavaScriptCatalog
admin.autodiscover()
urlpatterns = [
url(r'^', include('caffeine.urls')),
url(r'^api/v1/', include(
('caffeine_api_v1.urls', 'caffeine_api_v1'),
namespace='apiv1')),
# new API
url(r'^api/v2/', include('caffeine_api_v2.urls')),
# oauth2
url(r'^oauth2/', include(
('caffeine_oauth2.urls', 'caffeine_oauth2'),
namespace='oauth2_provider')),
# authentication
url(r'^auth/login/$', auth_views.LoginView.as_view(
template_name='django_registration/login.html'), name='auth_login'),
url(r'^auth/logout/$', auth_views.LogoutView.as_view(
template_name='django_registration/logout.html', next_page='/'),
name='auth_logout'),
url(r'^auth/password/change/$', auth_views.PasswordChangeView.as_view(),
name='auth_password_change'),
url(r'^auth/password/change/done/$',
auth_views.PasswordChangeDoneView.as_view(),
name='auth_password_change_done'),
url(r'^auth/password/reset/$', auth_views.PasswordResetView.as_view(
template_name='django_registration/password_reset_form.html',
email_template_name='django_registration/password_reset_email.txt',
subject_template_name='django_registration/password_reset_subject.txt',
success_url=reverse_lazy('auth_password_reset_done')),
name='auth_password_reset'),
url(r'^password/reset/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
auth_views.PasswordResetConfirmView.as_view(
template_name='django_registration/password_reset_confirm.html',
success_url=reverse_lazy('auth_password_reset_complete')),
name='auth_password_reset_confirm'),
url(r'^password/reset/complete/$',
auth_views.PasswordResetCompleteView.as_view(
template_name='django_registration/password_reset_complete.html'),
name='auth_password_reset_complete'),
url(r'^password/reset/done/$', auth_views.PasswordResetDoneView.as_view(
template_name='django_registration/password_reset_done.html'),
name='auth_password_reset_done'),
# javascript i18n
url(r'^jsi18n/(?P<packages>\S+?)/$', JavaScriptCatalog.as_view(),
name='jsi18n_catalog'),
# admin site
url(r'^admin/', admin.site.urls),
]
if settings.DEBUG: # pragma: no cover
import debug_toolbar
from django.contrib.staticfiles.views import serve as serve_static
from django.views.decorators.cache import never_cache
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
url(r'^static/(?P<path>.*)$', never_cache(serve_static)),
]
| mit |
ITinDublin/ITinDublin.github.io | .plugins/better_figures_and_images/better_figures_and_images.py | 7 | 2904 | """
Better Figures & Images
------------------------
This plugin:
- Adds a style="width: ???px; height: auto;" to each image in the content
- Also adds the width of the contained image to any parent div.figures.
- If RESPONSIVE_IMAGES == True, also adds style="max-width: 100%;"
- Corrects alt text: if alt == image filename, set alt = ''
TODO: Need to add a test.py for this plugin.
"""
from __future__ import unicode_literals
from os import path, access, R_OK
from pelican import signals
from bs4 import BeautifulSoup
from PIL import Image
import logging
logger = logging.getLogger(__name__)
def content_object_init(instance):
if instance._content is not None:
content = instance._content
soup = BeautifulSoup(content, "lxml")
if 'img' in content:
for img in soup('img'):
logger.debug('Better Fig. PATH: %s', instance.settings['PATH'])
logger.debug('Better Fig. img.src: %s', img['src'])
img_path, img_filename = path.split(img['src'])
logger.debug('Better Fig. img_path: %s', img_path)
logger.debug('Better Fig. img_fname: %s', img_filename)
# Strip off {filename}, |filename| or /static
if img_path.startswith(('{filename}', '|filename|')):
img_path = img_path[10:]
elif img_path.startswith('/static'):
img_path = img_path[7:]
else:
logger.warning('Better Fig. Error: img_path should start with either {filename}, |filename| or /static')
# Build the source image filename
src = instance.settings['PATH'] + img_path + '/' + img_filename
logger.debug('Better Fig. src: %s', src)
if not (path.isfile(src) and access(src, R_OK)):
logger.error('Better Fig. Error: image not found: %s', src)
# Open the source image and query dimensions; build style string
im = Image.open(src)
extra_style = 'width: {}px; height: auto;'.format(im.size[0])
if 'RESPONSIVE_IMAGES' in instance.settings and instance.settings['RESPONSIVE_IMAGES']:
extra_style += ' max-width: 100%;'
if img.get('style'):
img['style'] += extra_style
else:
img['style'] = extra_style
if img['alt'] == img['src']:
img['alt'] = ''
fig = img.find_parent('div', 'figure')
if fig:
if fig.get('style'):
fig['style'] += extra_style
else:
fig['style'] = extra_style
instance._content = soup.decode()
def register():
signals.content_object_init.connect(content_object_init)
| mit |
kofron/bigcouch | couchjs/scons/scons-local-2.0.1/SCons/exitfuncs.py | 61 | 2402 | """SCons.exitfuncs
Register functions which are executed when SCons exits for any reason.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/exitfuncs.py 5134 2010/08/16 23:02:40 bdeegan"
_exithandlers = []
def _run_exitfuncs():
"""run any registered exit functions
_exithandlers is traversed in reverse order so functions are executed
last in, first out.
"""
while _exithandlers:
func, targs, kargs = _exithandlers.pop()
func(*targs, **kargs)
def register(func, *targs, **kargs):
"""register a function to be executed upon normal program termination
func - function to be called at exit
targs - optional arguments to pass to func
kargs - optional keyword arguments to pass to func
"""
_exithandlers.append((func, targs, kargs))
import sys
try:
x = sys.exitfunc
# if x isn't our own exit func executive, assume it's another
# registered exit function - append it to our list...
if x != _run_exitfuncs:
register(x)
except AttributeError:
pass
# make our exit function get run by python when it exits:
sys.exitfunc = _run_exitfuncs
del sys
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| apache-2.0 |
mastizada/kuma | vendor/packages/Babel/babel/util.py | 10 | 9722 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://babel.edgewall.org/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.
"""Various utility classes and functions."""
import codecs
from datetime import timedelta, tzinfo
import os
import re
try:
set
except NameError:
from sets import Set as set
import textwrap
import time
from itertools import izip, imap
missing = object()
__all__ = ['distinct', 'pathmatch', 'relpath', 'wraptext', 'odict', 'UTC',
'LOCALTZ']
__docformat__ = 'restructuredtext en'
def distinct(iterable):
"""Yield all items in an iterable collection that are distinct.
Unlike when using sets for a similar effect, the original ordering of the
items in the collection is preserved by this function.
>>> print list(distinct([1, 2, 1, 3, 4, 4]))
[1, 2, 3, 4]
>>> print list(distinct('foobar'))
['f', 'o', 'b', 'a', 'r']
:param iterable: the iterable collection providing the data
:return: the distinct items in the collection
:rtype: ``iterator``
"""
seen = set()
for item in iter(iterable):
if item not in seen:
yield item
seen.add(item)
# Regexp to match python magic encoding line
PYTHON_MAGIC_COMMENT_re = re.compile(
r'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)', re.VERBOSE)
def parse_encoding(fp):
"""Deduce the encoding of a source file from magic comment.
It does this in the same way as the `Python interpreter`__
.. __: http://docs.python.org/ref/encodings.html
The ``fp`` argument should be a seekable file object.
(From Jeff Dairiki)
"""
pos = fp.tell()
fp.seek(0)
try:
line1 = fp.readline()
has_bom = line1.startswith(codecs.BOM_UTF8)
if has_bom:
line1 = line1[len(codecs.BOM_UTF8):]
m = PYTHON_MAGIC_COMMENT_re.match(line1)
if not m:
try:
import parser
parser.suite(line1)
except (ImportError, SyntaxError):
# Either it's a real syntax error, in which case the source is
# not valid python source, or line2 is a continuation of line1,
# in which case we don't want to scan line2 for a magic
# comment.
pass
else:
line2 = fp.readline()
m = PYTHON_MAGIC_COMMENT_re.match(line2)
if has_bom:
if m:
raise SyntaxError(
"python refuses to compile code with both a UTF8 "
"byte-order-mark and a magic encoding comment")
return 'utf_8'
elif m:
return m.group(1)
else:
return None
finally:
fp.seek(pos)
def pathmatch(pattern, filename):
"""Extended pathname pattern matching.
This function is similar to what is provided by the ``fnmatch`` module in
the Python standard library, but:
* can match complete (relative or absolute) path names, and not just file
names, and
* also supports a convenience pattern ("**") to match files at any
directory level.
Examples:
>>> pathmatch('**.py', 'bar.py')
True
>>> pathmatch('**.py', 'foo/bar/baz.py')
True
>>> pathmatch('**.py', 'templates/index.html')
False
>>> pathmatch('**/templates/*.html', 'templates/index.html')
True
>>> pathmatch('**/templates/*.html', 'templates/foo/bar.html')
False
:param pattern: the glob pattern
:param filename: the path name of the file to match against
:return: `True` if the path name matches the pattern, `False` otherwise
:rtype: `bool`
"""
symbols = {
'?': '[^/]',
'?/': '[^/]/',
'*': '[^/]+',
'*/': '[^/]+/',
'**/': '(?:.+/)*?',
'**': '(?:.+/)*?[^/]+',
}
buf = []
for idx, part in enumerate(re.split('([?*]+/?)', pattern)):
if idx % 2:
buf.append(symbols[part])
elif part:
buf.append(re.escape(part))
match = re.match(''.join(buf) + '$', filename.replace(os.sep, '/'))
return match is not None
class TextWrapper(textwrap.TextWrapper):
wordsep_re = re.compile(
r'(\s+|' # any whitespace
r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))' # em-dash
)
def wraptext(text, width=70, initial_indent='', subsequent_indent=''):
"""Simple wrapper around the ``textwrap.wrap`` function in the standard
library. This version does not wrap lines on hyphens in words.
:param text: the text to wrap
:param width: the maximum line width
:param initial_indent: string that will be prepended to the first line of
wrapped output
:param subsequent_indent: string that will be prepended to all lines save
the first of wrapped output
:return: a list of lines
:rtype: `list`
"""
wrapper = TextWrapper(width=width, initial_indent=initial_indent,
subsequent_indent=subsequent_indent,
break_long_words=False)
return wrapper.wrap(text)
class odict(dict):
"""Ordered dict implementation.
:see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
"""
def __init__(self, data=None):
dict.__init__(self, data or {})
self._keys = dict.keys(self)
def __delitem__(self, key):
dict.__delitem__(self, key)
self._keys.remove(key)
def __setitem__(self, key, item):
dict.__setitem__(self, key, item)
if key not in self._keys:
self._keys.append(key)
def __iter__(self):
return iter(self._keys)
iterkeys = __iter__
def clear(self):
dict.clear(self)
self._keys = []
def copy(self):
d = odict()
d.update(self)
return d
def items(self):
return zip(self._keys, self.values())
def iteritems(self):
return izip(self._keys, self.itervalues())
def keys(self):
return self._keys[:]
def pop(self, key, default=missing):
if default is missing:
return dict.pop(self, key)
elif key not in self:
return default
self._keys.remove(key)
return dict.pop(self, key, default)
def popitem(self, key):
self._keys.remove(key)
return dict.popitem(key)
def setdefault(self, key, failobj = None):
dict.setdefault(self, key, failobj)
if key not in self._keys:
self._keys.append(key)
def update(self, dict):
for (key, val) in dict.items():
self[key] = val
def values(self):
return map(self.get, self._keys)
def itervalues(self):
return imap(self.get, self._keys)
try:
relpath = os.path.relpath
except AttributeError:
def relpath(path, start='.'):
"""Compute the relative path to one path from another.
>>> relpath('foo/bar.txt', '').replace(os.sep, '/')
'foo/bar.txt'
>>> relpath('foo/bar.txt', 'foo').replace(os.sep, '/')
'bar.txt'
>>> relpath('foo/bar.txt', 'baz').replace(os.sep, '/')
'../foo/bar.txt'
:return: the relative path
:rtype: `basestring`
"""
start_list = os.path.abspath(start).split(os.sep)
path_list = os.path.abspath(path).split(os.sep)
# Work out how much of the filepath is shared by start and path.
i = len(os.path.commonprefix([start_list, path_list]))
rel_list = [os.path.pardir] * (len(start_list) - i) + path_list[i:]
return os.path.join(*rel_list)
ZERO = timedelta(0)
class FixedOffsetTimezone(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name=None):
self._offset = timedelta(minutes=offset)
if name is None:
name = 'Etc/GMT+%d' % offset
self.zone = name
def __str__(self):
return self.zone
def __repr__(self):
return '<FixedOffset "%s" %s>' % (self.zone, self._offset)
def utcoffset(self, dt):
return self._offset
def tzname(self, dt):
return self.zone
def dst(self, dt):
return ZERO
try:
from pytz import UTC
except ImportError:
UTC = FixedOffsetTimezone(0, 'UTC')
"""`tzinfo` object for UTC (Universal Time).
:type: `tzinfo`
"""
STDOFFSET = timedelta(seconds = -time.timezone)
if time.daylight:
DSTOFFSET = timedelta(seconds = -time.altzone)
else:
DSTOFFSET = STDOFFSET
DSTDIFF = DSTOFFSET - STDOFFSET
class LocalTimezone(tzinfo):
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET
def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO
def tzname(self, dt):
return time.tzname[self._isdst(dt)]
def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.weekday(), 0, -1)
stamp = time.mktime(tt)
tt = time.localtime(stamp)
return tt.tm_isdst > 0
LOCALTZ = LocalTimezone()
"""`tzinfo` object for local time-zone.
:type: `tzinfo`
"""
| mpl-2.0 |
Kongsea/tensorflow | tensorflow/python/kernel_tests/confusion_matrix_test.py | 23 | 18955 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# ==============================================================================
"""Tests for confusion_matrix_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import confusion_matrix
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import test
class ConfusionMatrixTest(test.TestCase):
@test_util.run_in_graph_and_eager_modes()
def testExample(self):
"""This is a test of the example provided in pydoc."""
with self.test_session():
self.assertAllEqual([
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]
], self.evaluate(confusion_matrix.confusion_matrix(
labels=[1, 2, 4], predictions=[2, 2, 4])))
def _testConfMatrix(self, labels, predictions, truth, weights=None,
num_classes=None):
with self.test_session():
dtype = predictions.dtype
ans = confusion_matrix.confusion_matrix(
labels, predictions, dtype=dtype, weights=weights,
num_classes=num_classes).eval()
self.assertAllClose(truth, ans, atol=1e-10)
self.assertEqual(ans.dtype, dtype)
def _testBasic(self, dtype):
labels = np.arange(5, dtype=dtype)
predictions = np.arange(5, dtype=dtype)
truth = np.asarray(
[[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]],
dtype=dtype)
self._testConfMatrix(labels=labels, predictions=predictions, truth=truth)
def testInt32Basic(self):
self._testBasic(dtype=np.int32)
def testInt64Basic(self):
self._testBasic(dtype=np.int64)
def _testConfMatrixOnTensors(self, tf_dtype, np_dtype):
with self.test_session() as sess:
m_neg = array_ops.placeholder(dtype=dtypes.float32)
m_pos = array_ops.placeholder(dtype=dtypes.float32)
s = array_ops.placeholder(dtype=dtypes.float32)
neg = random_ops.random_normal(
[20], mean=m_neg, stddev=s, dtype=dtypes.float32)
pos = random_ops.random_normal(
[20], mean=m_pos, stddev=s, dtype=dtypes.float32)
data = array_ops.concat([neg, pos], 0)
data = math_ops.cast(math_ops.round(data), tf_dtype)
data = math_ops.minimum(math_ops.maximum(data, 0), 1)
lab = array_ops.concat(
[
array_ops.zeros(
[20], dtype=tf_dtype), array_ops.ones(
[20], dtype=tf_dtype)
],
0)
cm = confusion_matrix.confusion_matrix(
lab, data, dtype=tf_dtype, num_classes=2)
d, l, cm_out = sess.run([data, lab, cm], {m_neg: 0.0, m_pos: 1.0, s: 1.0})
truth = np.zeros([2, 2], dtype=np_dtype)
try:
range_builder = xrange
except NameError: # In Python 3.
range_builder = range
for i in range_builder(len(d)):
truth[l[i], d[i]] += 1
self.assertEqual(cm_out.dtype, np_dtype)
self.assertAllClose(cm_out, truth, atol=1e-10)
def testOnTensors_int32(self):
self._testConfMatrixOnTensors(dtypes.int32, np.int32)
def testOnTensors_int64(self):
self._testConfMatrixOnTensors(dtypes.int64, np.int64)
def _testDifferentLabelsInPredictionAndTarget(self, dtype):
labels = np.asarray([4, 5, 6], dtype=dtype)
predictions = np.asarray([1, 2, 3], dtype=dtype)
truth = np.asarray(
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0]],
dtype=dtype)
self._testConfMatrix(labels=labels, predictions=predictions, truth=truth)
def testInt32DifferentLabels(self, dtype=np.int32):
self._testDifferentLabelsInPredictionAndTarget(dtype)
def testInt64DifferentLabels(self, dtype=np.int64):
self._testDifferentLabelsInPredictionAndTarget(dtype)
def _testMultipleLabels(self, dtype):
labels = np.asarray([1, 1, 2, 3, 5, 1, 3, 6, 3, 1], dtype=dtype)
predictions = np.asarray([1, 1, 2, 3, 5, 6, 1, 2, 3, 4], dtype=dtype)
truth = np.asarray(
[[0, 0, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 0, 0],
[0, 1, 0, 2, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 0]],
dtype=dtype)
self._testConfMatrix(labels=labels, predictions=predictions, truth=truth)
def testInt32MultipleLabels(self, dtype=np.int32):
self._testMultipleLabels(dtype)
def testInt64MultipleLabels(self, dtype=np.int64):
self._testMultipleLabels(dtype)
def testWeighted(self):
labels = np.arange(5, dtype=np.int32)
predictions = np.arange(5, dtype=np.int32)
weights = constant_op.constant(np.arange(5, dtype=np.int32))
truth = np.asarray(
[[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 2, 0, 0],
[0, 0, 0, 3, 0],
[0, 0, 0, 0, 4]],
dtype=np.int32)
self._testConfMatrix(
labels=labels, predictions=predictions, weights=weights, truth=truth)
def testLabelsTooLarge(self):
labels = np.asarray([1, 1, 0, 3, 5], dtype=np.int32)
predictions = np.asarray([2, 1, 0, 2, 2], dtype=np.int32)
with self.assertRaisesOpError("`labels`.*x < y"):
self._testConfMatrix(
labels=labels, predictions=predictions, num_classes=3, truth=None)
def testLabelsNegative(self):
labels = np.asarray([1, 1, 0, -1, -1], dtype=np.int32)
predictions = np.asarray([2, 1, 0, 2, 2], dtype=np.int32)
with self.assertRaisesOpError("`labels`.*negative values"):
self._testConfMatrix(
labels=labels, predictions=predictions, num_classes=3, truth=None)
def testPredictionsTooLarge(self):
labels = np.asarray([1, 1, 0, 2, 2], dtype=np.int32)
predictions = np.asarray([2, 1, 0, 3, 5], dtype=np.int32)
with self.assertRaisesOpError("`predictions`.*x < y"):
self._testConfMatrix(
labels=labels, predictions=predictions, num_classes=3, truth=None)
def testPredictionsNegative(self):
labels = np.asarray([1, 1, 0, 2, 2], dtype=np.int32)
predictions = np.asarray([2, 1, 0, -1, -1], dtype=np.int32)
with self.assertRaisesOpError("`predictions`.*negative values"):
self._testConfMatrix(
labels=labels, predictions=predictions, num_classes=3, truth=None)
def testInvalidRank_predictionsTooBig(self):
labels = np.asarray([1, 2, 3])
predictions = np.asarray([[1, 2, 3]])
self.assertRaisesRegexp(ValueError, "an not squeeze dim",
confusion_matrix.confusion_matrix, predictions,
labels)
def testInvalidRank_predictionsTooSmall(self):
labels = np.asarray([[1, 2, 3]])
predictions = np.asarray([1, 2, 3])
self.assertRaisesRegexp(ValueError, "an not squeeze dim",
confusion_matrix.confusion_matrix, predictions,
labels)
def testInputDifferentSize(self):
labels = np.asarray([1, 2])
predictions = np.asarray([1, 2, 3])
self.assertRaisesRegexp(ValueError, "must be equal",
confusion_matrix.confusion_matrix, predictions,
labels)
def testOutputIsInt32(self):
labels = np.arange(2)
predictions = np.arange(2)
with self.test_session():
cm = confusion_matrix.confusion_matrix(
labels, predictions, dtype=dtypes.int32)
tf_cm = cm.eval()
self.assertEqual(tf_cm.dtype, np.int32)
def testOutputIsInt64(self):
labels = np.arange(2)
predictions = np.arange(2)
with self.test_session():
cm = confusion_matrix.confusion_matrix(
labels, predictions, dtype=dtypes.int64)
tf_cm = cm.eval()
self.assertEqual(tf_cm.dtype, np.int64)
class RemoveSqueezableDimensionsTest(test.TestCase):
def testBothScalarShape(self):
label_values = 1.0
prediction_values = 0.0
static_labels, static_predictions = (
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values))
labels_placeholder = array_ops.placeholder(dtype=dtypes.float32)
predictions_placeholder = array_ops.placeholder(dtype=dtypes.float32)
dynamic_labels, dynamic_predictions = (
confusion_matrix.remove_squeezable_dimensions(
labels_placeholder, predictions_placeholder))
with self.test_session():
self.assertAllEqual(label_values, static_labels.eval())
self.assertAllEqual(prediction_values, static_predictions.eval())
feed_dict = {
labels_placeholder: label_values,
predictions_placeholder: prediction_values
}
self.assertAllEqual(
label_values, dynamic_labels.eval(feed_dict=feed_dict))
self.assertAllEqual(
prediction_values, dynamic_predictions.eval(feed_dict=feed_dict))
def testSameShape(self):
label_values = np.ones(shape=(2, 3, 1))
prediction_values = np.zeros_like(label_values)
static_labels, static_predictions = (
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values))
labels_placeholder = array_ops.placeholder(dtype=dtypes.int32)
predictions_placeholder = array_ops.placeholder(dtype=dtypes.int32)
dynamic_labels, dynamic_predictions = (
confusion_matrix.remove_squeezable_dimensions(
labels_placeholder, predictions_placeholder))
with self.test_session():
self.assertAllEqual(label_values, static_labels.eval())
self.assertAllEqual(prediction_values, static_predictions.eval())
feed_dict = {
labels_placeholder: label_values,
predictions_placeholder: prediction_values
}
self.assertAllEqual(
label_values, dynamic_labels.eval(feed_dict=feed_dict))
self.assertAllEqual(
prediction_values, dynamic_predictions.eval(feed_dict=feed_dict))
def testSameShapeExpectedRankDiff0(self):
label_values = np.ones(shape=(2, 3, 1))
prediction_values = np.zeros_like(label_values)
static_labels, static_predictions = (
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values, expected_rank_diff=0))
labels_placeholder = array_ops.placeholder(dtype=dtypes.int32)
predictions_placeholder = array_ops.placeholder(dtype=dtypes.int32)
dynamic_labels, dynamic_predictions = (
confusion_matrix.remove_squeezable_dimensions(
labels_placeholder, predictions_placeholder, expected_rank_diff=0))
with self.test_session():
self.assertAllEqual(label_values, static_labels.eval())
self.assertAllEqual(prediction_values, static_predictions.eval())
feed_dict = {
labels_placeholder: label_values,
predictions_placeholder: prediction_values
}
self.assertAllEqual(
label_values, dynamic_labels.eval(feed_dict=feed_dict))
self.assertAllEqual(
prediction_values, dynamic_predictions.eval(feed_dict=feed_dict))
def testSqueezableLabels(self):
label_values = np.ones(shape=(2, 3, 1))
prediction_values = np.zeros(shape=(2, 3))
static_labels, static_predictions = (
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values))
labels_placeholder = array_ops.placeholder(dtype=dtypes.int32)
predictions_placeholder = array_ops.placeholder(dtype=dtypes.int32)
dynamic_labels, dynamic_predictions = (
confusion_matrix.remove_squeezable_dimensions(
labels_placeholder, predictions_placeholder))
expected_label_values = np.reshape(label_values, newshape=(2, 3))
with self.test_session():
self.assertAllEqual(expected_label_values, static_labels.eval())
self.assertAllEqual(prediction_values, static_predictions.eval())
feed_dict = {
labels_placeholder: label_values,
predictions_placeholder: prediction_values
}
self.assertAllEqual(
expected_label_values, dynamic_labels.eval(feed_dict=feed_dict))
self.assertAllEqual(
prediction_values, dynamic_predictions.eval(feed_dict=feed_dict))
def testSqueezableLabelsExpectedRankDiffPlus1(self):
label_values = np.ones(shape=(2, 3, 1))
prediction_values = np.zeros(shape=(2, 3, 5))
static_labels, static_predictions = (
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values, expected_rank_diff=1))
labels_placeholder = array_ops.placeholder(dtype=dtypes.int32)
predictions_placeholder = array_ops.placeholder(dtype=dtypes.int32)
dynamic_labels, dynamic_predictions = (
confusion_matrix.remove_squeezable_dimensions(
labels_placeholder, predictions_placeholder, expected_rank_diff=1))
expected_label_values = np.reshape(label_values, newshape=(2, 3))
with self.test_session():
self.assertAllEqual(expected_label_values, static_labels.eval())
self.assertAllEqual(prediction_values, static_predictions.eval())
feed_dict = {
labels_placeholder: label_values,
predictions_placeholder: prediction_values
}
self.assertAllEqual(
expected_label_values, dynamic_labels.eval(feed_dict=feed_dict))
self.assertAllEqual(
prediction_values, dynamic_predictions.eval(feed_dict=feed_dict))
def testSqueezablePredictions(self):
label_values = np.ones(shape=(2, 3))
prediction_values = np.zeros(shape=(2, 3, 1))
static_labels, static_predictions = (
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values))
labels_placeholder = array_ops.placeholder(dtype=dtypes.int32)
predictions_placeholder = array_ops.placeholder(dtype=dtypes.int32)
dynamic_labels, dynamic_predictions = (
confusion_matrix.remove_squeezable_dimensions(
labels_placeholder, predictions_placeholder))
expected_prediction_values = np.reshape(prediction_values, newshape=(2, 3))
with self.test_session():
self.assertAllEqual(label_values, static_labels.eval())
self.assertAllEqual(expected_prediction_values, static_predictions.eval())
feed_dict = {
labels_placeholder: label_values,
predictions_placeholder: prediction_values
}
self.assertAllEqual(
label_values, dynamic_labels.eval(feed_dict=feed_dict))
self.assertAllEqual(
expected_prediction_values,
dynamic_predictions.eval(feed_dict=feed_dict))
def testSqueezablePredictionsExpectedRankDiffMinus1(self):
label_values = np.ones(shape=(2, 3, 5))
prediction_values = np.zeros(shape=(2, 3, 1))
static_labels, static_predictions = (
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values, expected_rank_diff=-1))
labels_placeholder = array_ops.placeholder(dtype=dtypes.int32)
predictions_placeholder = array_ops.placeholder(dtype=dtypes.int32)
dynamic_labels, dynamic_predictions = (
confusion_matrix.remove_squeezable_dimensions(
labels_placeholder, predictions_placeholder, expected_rank_diff=-1))
expected_prediction_values = np.reshape(prediction_values, newshape=(2, 3))
with self.test_session():
self.assertAllEqual(label_values, static_labels.eval())
self.assertAllEqual(expected_prediction_values, static_predictions.eval())
feed_dict = {
labels_placeholder: label_values,
predictions_placeholder: prediction_values
}
self.assertAllEqual(
label_values, dynamic_labels.eval(feed_dict=feed_dict))
self.assertAllEqual(
expected_prediction_values,
dynamic_predictions.eval(feed_dict=feed_dict))
def testUnsqueezableLabels(self):
label_values = np.ones(shape=(2, 3, 2))
prediction_values = np.zeros(shape=(2, 3))
with self.assertRaisesRegexp(ValueError, r"Can not squeeze dim\[2\]"):
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values)
labels_placeholder = array_ops.placeholder(dtype=dtypes.int32)
predictions_placeholder = array_ops.placeholder(dtype=dtypes.int32)
dynamic_labels, dynamic_predictions = (
confusion_matrix.remove_squeezable_dimensions(
labels_placeholder, predictions_placeholder))
with self.test_session():
feed_dict = {
labels_placeholder: label_values,
predictions_placeholder: prediction_values
}
with self.assertRaisesRegexp(
errors_impl.InvalidArgumentError,
"Tried to explicitly squeeze dimension 2"):
dynamic_labels.eval(feed_dict=feed_dict)
self.assertAllEqual(
prediction_values, dynamic_predictions.eval(feed_dict=feed_dict))
def testUnsqueezablePredictions(self):
label_values = np.ones(shape=(2, 3))
prediction_values = np.zeros(shape=(2, 3, 2))
with self.assertRaisesRegexp(ValueError, r"Can not squeeze dim\[2\]"):
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values)
labels_placeholder = array_ops.placeholder(dtype=dtypes.int32)
predictions_placeholder = array_ops.placeholder(dtype=dtypes.int32)
dynamic_labels, dynamic_predictions = (
confusion_matrix.remove_squeezable_dimensions(
labels_placeholder, predictions_placeholder))
with self.test_session():
feed_dict = {
labels_placeholder: label_values,
predictions_placeholder: prediction_values
}
self.assertAllEqual(
label_values, dynamic_labels.eval(feed_dict=feed_dict))
with self.assertRaisesRegexp(
errors_impl.InvalidArgumentError,
"Tried to explicitly squeeze dimension 2"):
dynamic_predictions.eval(feed_dict=feed_dict)
if __name__ == "__main__":
test.main()
| apache-2.0 |
Godiyos/python-for-android | python3-alpha/python3-src/Lib/sre_parse.py | 48 | 27922 | #
# Secret Labs' Regular Expression Engine
#
# convert re-style regular expression to sre pattern
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# See the sre.py file for information on usage and redistribution.
#
"""Internal support module for sre"""
# XXX: show string offset and offending character for all errors
import sys
from sre_constants import *
SPECIAL_CHARS = ".\\[{()*+?^$|"
REPEAT_CHARS = "*+?{"
DIGITS = set("0123456789")
OCTDIGITS = set("01234567")
HEXDIGITS = set("0123456789abcdefABCDEF")
WHITESPACE = set(" \t\n\r\v\f")
ESCAPES = {
r"\a": (LITERAL, ord("\a")),
r"\b": (LITERAL, ord("\b")),
r"\f": (LITERAL, ord("\f")),
r"\n": (LITERAL, ord("\n")),
r"\r": (LITERAL, ord("\r")),
r"\t": (LITERAL, ord("\t")),
r"\v": (LITERAL, ord("\v")),
r"\\": (LITERAL, ord("\\"))
}
CATEGORIES = {
r"\A": (AT, AT_BEGINNING_STRING), # start of string
r"\b": (AT, AT_BOUNDARY),
r"\B": (AT, AT_NON_BOUNDARY),
r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
r"\Z": (AT, AT_END_STRING), # end of string
}
FLAGS = {
# standard flags
"i": SRE_FLAG_IGNORECASE,
"L": SRE_FLAG_LOCALE,
"m": SRE_FLAG_MULTILINE,
"s": SRE_FLAG_DOTALL,
"x": SRE_FLAG_VERBOSE,
# extensions
"a": SRE_FLAG_ASCII,
"t": SRE_FLAG_TEMPLATE,
"u": SRE_FLAG_UNICODE,
}
class Pattern:
# master pattern object. keeps track of global attributes
def __init__(self):
self.flags = 0
self.open = []
self.groups = 1
self.groupdict = {}
def opengroup(self, name=None):
gid = self.groups
self.groups = gid + 1
if name is not None:
ogid = self.groupdict.get(name, None)
if ogid is not None:
raise error("redefinition of group name %s as group %d; "
"was group %d" % (repr(name), gid, ogid))
self.groupdict[name] = gid
self.open.append(gid)
return gid
def closegroup(self, gid):
self.open.remove(gid)
def checkgroup(self, gid):
return gid < self.groups and gid not in self.open
class SubPattern:
# a subpattern, in intermediate form
def __init__(self, pattern, data=None):
self.pattern = pattern
if data is None:
data = []
self.data = data
self.width = None
def dump(self, level=0):
nl = 1
seqtypes = (tuple, list)
for op, av in self.data:
print(level*" " + op, end=' '); nl = 0
if op == "in":
# member sublanguage
print(); nl = 1
for op, a in av:
print((level+1)*" " + op, a)
elif op == "branch":
print(); nl = 1
i = 0
for a in av[1]:
if i > 0:
print(level*" " + "or")
a.dump(level+1); nl = 1
i = i + 1
elif isinstance(av, seqtypes):
for a in av:
if isinstance(a, SubPattern):
if not nl: print()
a.dump(level+1); nl = 1
else:
print(a, end=' ') ; nl = 0
else:
print(av, end=' ') ; nl = 0
if not nl: print()
def __repr__(self):
return repr(self.data)
def __len__(self):
return len(self.data)
def __delitem__(self, index):
del self.data[index]
def __getitem__(self, index):
if isinstance(index, slice):
return SubPattern(self.pattern, self.data[index])
return self.data[index]
def __setitem__(self, index, code):
self.data[index] = code
def insert(self, index, code):
self.data.insert(index, code)
def append(self, code):
self.data.append(code)
def getwidth(self):
# determine the width (min, max) for this subpattern
if self.width:
return self.width
lo = hi = 0
UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
for op, av in self.data:
if op is BRANCH:
i = sys.maxsize
j = 0
for av in av[1]:
l, h = av.getwidth()
i = min(i, l)
j = max(j, h)
lo = lo + i
hi = hi + j
elif op is CALL:
i, j = av.getwidth()
lo = lo + i
hi = hi + j
elif op is SUBPATTERN:
i, j = av[1].getwidth()
lo = lo + i
hi = hi + j
elif op in REPEATCODES:
i, j = av[2].getwidth()
lo = lo + int(i) * av[0]
hi = hi + int(j) * av[1]
elif op in UNITCODES:
lo = lo + 1
hi = hi + 1
elif op == SUCCESS:
break
self.width = int(min(lo, sys.maxsize)), int(min(hi, sys.maxsize))
return self.width
class Tokenizer:
def __init__(self, string):
self.string = string
self.index = 0
self.__next()
def __next(self):
if self.index >= len(self.string):
self.next = None
return
char = self.string[self.index:self.index+1]
# Special case for the str8, since indexing returns a integer
# XXX This is only needed for test_bug_926075 in test_re.py
if char and isinstance(char, bytes):
char = chr(char[0])
if char == "\\":
try:
c = self.string[self.index + 1]
except IndexError:
raise error("bogus escape (end of line)")
if isinstance(self.string, bytes):
c = chr(c)
char = char + c
self.index = self.index + len(char)
self.next = char
def match(self, char, skip=1):
if char == self.next:
if skip:
self.__next()
return 1
return 0
def get(self):
this = self.next
self.__next()
return this
def tell(self):
return self.index, self.next
def seek(self, index):
self.index, self.next = index
def isident(char):
return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
def isdigit(char):
return "0" <= char <= "9"
def isname(name):
# check that group name is a valid string
if not isident(name[0]):
return False
for char in name[1:]:
if not isident(char) and not isdigit(char):
return False
return True
def _class_escape(source, escape):
# handle escape code inside character class
code = ESCAPES.get(escape)
if code:
return code
code = CATEGORIES.get(escape)
if code:
return code
try:
c = escape[1:2]
if c == "x":
# hexadecimal escape (exactly two digits)
while source.next in HEXDIGITS and len(escape) < 4:
escape = escape + source.get()
escape = escape[2:]
if len(escape) != 2:
raise error("bogus escape: %s" % repr("\\" + escape))
return LITERAL, int(escape, 16) & 0xff
elif c in OCTDIGITS:
# octal escape (up to three digits)
while source.next in OCTDIGITS and len(escape) < 4:
escape = escape + source.get()
escape = escape[1:]
return LITERAL, int(escape, 8) & 0xff
elif c in DIGITS:
raise error("bogus escape: %s" % repr(escape))
if len(escape) == 2:
return LITERAL, ord(escape[1])
except ValueError:
pass
raise error("bogus escape: %s" % repr(escape))
def _escape(source, escape, state):
# handle escape code in expression
code = CATEGORIES.get(escape)
if code:
return code
code = ESCAPES.get(escape)
if code:
return code
try:
c = escape[1:2]
if c == "x":
# hexadecimal escape
while source.next in HEXDIGITS and len(escape) < 4:
escape = escape + source.get()
if len(escape) != 4:
raise ValueError
return LITERAL, int(escape[2:], 16) & 0xff
elif c == "0":
# octal escape
while source.next in OCTDIGITS and len(escape) < 4:
escape = escape + source.get()
return LITERAL, int(escape[1:], 8) & 0xff
elif c in DIGITS:
# octal escape *or* decimal group reference (sigh)
if source.next in DIGITS:
escape = escape + source.get()
if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
source.next in OCTDIGITS):
# got three octal digits; this is an octal escape
escape = escape + source.get()
return LITERAL, int(escape[1:], 8) & 0xff
# not an octal escape, so this is a group reference
group = int(escape[1:])
if group < state.groups:
if not state.checkgroup(group):
raise error("cannot refer to open group")
return GROUPREF, group
raise ValueError
if len(escape) == 2:
return LITERAL, ord(escape[1])
except ValueError:
pass
raise error("bogus escape: %s" % repr(escape))
def _parse_sub(source, state, nested=1):
# parse an alternation: a|b|c
items = []
itemsappend = items.append
sourcematch = source.match
while 1:
itemsappend(_parse(source, state))
if sourcematch("|"):
continue
if not nested:
break
if not source.next or sourcematch(")", 0):
break
else:
raise error("pattern not properly closed")
if len(items) == 1:
return items[0]
subpattern = SubPattern(state)
subpatternappend = subpattern.append
# check if all items share a common prefix
while 1:
prefix = None
for item in items:
if not item:
break
if prefix is None:
prefix = item[0]
elif item[0] != prefix:
break
else:
# all subitems start with a common "prefix".
# move it out of the branch
for item in items:
del item[0]
subpatternappend(prefix)
continue # check next one
break
# check if the branch can be replaced by a character set
for item in items:
if len(item) != 1 or item[0][0] != LITERAL:
break
else:
# we can store this as a character set instead of a
# branch (the compiler may optimize this even more)
set = []
setappend = set.append
for item in items:
setappend(item[0])
subpatternappend((IN, set))
return subpattern
subpattern.append((BRANCH, (None, items)))
return subpattern
def _parse_sub_cond(source, state, condgroup):
item_yes = _parse(source, state)
if source.match("|"):
item_no = _parse(source, state)
if source.match("|"):
raise error("conditional backref with more than two branches")
else:
item_no = None
if source.next and not source.match(")", 0):
raise error("pattern not properly closed")
subpattern = SubPattern(state)
subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
return subpattern
_PATTERNENDERS = set("|)")
_ASSERTCHARS = set("=!<")
_LOOKBEHINDASSERTCHARS = set("=!")
_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
def _parse(source, state):
# parse a simple pattern
subpattern = SubPattern(state)
# precompute constants into local variables
subpatternappend = subpattern.append
sourceget = source.get
sourcematch = source.match
_len = len
PATTERNENDERS = _PATTERNENDERS
ASSERTCHARS = _ASSERTCHARS
LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
REPEATCODES = _REPEATCODES
while 1:
if source.next in PATTERNENDERS:
break # end of subpattern
this = sourceget()
if this is None:
break # end of pattern
if state.flags & SRE_FLAG_VERBOSE:
# skip whitespace and comments
if this in WHITESPACE:
continue
if this == "#":
while 1:
this = sourceget()
if this in (None, "\n"):
break
continue
if this and this[0] not in SPECIAL_CHARS:
subpatternappend((LITERAL, ord(this)))
elif this == "[":
# character set
set = []
setappend = set.append
## if sourcematch(":"):
## pass # handle character classes
if sourcematch("^"):
setappend((NEGATE, None))
# check remaining characters
start = set[:]
while 1:
this = sourceget()
if this == "]" and set != start:
break
elif this and this[0] == "\\":
code1 = _class_escape(source, this)
elif this:
code1 = LITERAL, ord(this)
else:
raise error("unexpected end of regular expression")
if sourcematch("-"):
# potential range
this = sourceget()
if this == "]":
if code1[0] is IN:
code1 = code1[1][0]
setappend(code1)
setappend((LITERAL, ord("-")))
break
elif this:
if this[0] == "\\":
code2 = _class_escape(source, this)
else:
code2 = LITERAL, ord(this)
if code1[0] != LITERAL or code2[0] != LITERAL:
raise error("bad character range")
lo = code1[1]
hi = code2[1]
if hi < lo:
raise error("bad character range")
setappend((RANGE, (lo, hi)))
else:
raise error("unexpected end of regular expression")
else:
if code1[0] is IN:
code1 = code1[1][0]
setappend(code1)
# XXX: <fl> should move set optimization to compiler!
if _len(set)==1 and set[0][0] is LITERAL:
subpatternappend(set[0]) # optimization
elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
subpatternappend((NOT_LITERAL, set[1][1])) # optimization
else:
# XXX: <fl> should add charmap optimization here
subpatternappend((IN, set))
elif this and this[0] in REPEAT_CHARS:
# repeat previous item
if this == "?":
min, max = 0, 1
elif this == "*":
min, max = 0, MAXREPEAT
elif this == "+":
min, max = 1, MAXREPEAT
elif this == "{":
if source.next == "}":
subpatternappend((LITERAL, ord(this)))
continue
here = source.tell()
min, max = 0, MAXREPEAT
lo = hi = ""
while source.next in DIGITS:
lo = lo + source.get()
if sourcematch(","):
while source.next in DIGITS:
hi = hi + sourceget()
else:
hi = lo
if not sourcematch("}"):
subpatternappend((LITERAL, ord(this)))
source.seek(here)
continue
if lo:
min = int(lo)
if hi:
max = int(hi)
if max < min:
raise error("bad repeat interval")
else:
raise error("not supported")
# figure out which item to repeat
if subpattern:
item = subpattern[-1:]
else:
item = None
if not item or (_len(item) == 1 and item[0][0] == AT):
raise error("nothing to repeat")
if item[0][0] in REPEATCODES:
raise error("multiple repeat")
if sourcematch("?"):
subpattern[-1] = (MIN_REPEAT, (min, max, item))
else:
subpattern[-1] = (MAX_REPEAT, (min, max, item))
elif this == ".":
subpatternappend((ANY, None))
elif this == "(":
group = 1
name = None
condgroup = None
if sourcematch("?"):
group = 0
# options
if sourcematch("P"):
# python extensions
if sourcematch("<"):
# named group: skip forward to end of name
name = ""
while 1:
char = sourceget()
if char is None:
raise error("unterminated name")
if char == ">":
break
name = name + char
group = 1
if not isname(name):
raise error("bad character in group name")
elif sourcematch("="):
# named backreference
name = ""
while 1:
char = sourceget()
if char is None:
raise error("unterminated name")
if char == ")":
break
name = name + char
if not isname(name):
raise error("bad character in group name")
gid = state.groupdict.get(name)
if gid is None:
raise error("unknown group name")
subpatternappend((GROUPREF, gid))
continue
else:
char = sourceget()
if char is None:
raise error("unexpected end of pattern")
raise error("unknown specifier: ?P%s" % char)
elif sourcematch(":"):
# non-capturing group
group = 2
elif sourcematch("#"):
# comment
while 1:
if source.next is None or source.next == ")":
break
sourceget()
if not sourcematch(")"):
raise error("unbalanced parenthesis")
continue
elif source.next in ASSERTCHARS:
# lookahead assertions
char = sourceget()
dir = 1
if char == "<":
if source.next not in LOOKBEHINDASSERTCHARS:
raise error("syntax error")
dir = -1 # lookbehind
char = sourceget()
p = _parse_sub(source, state)
if not sourcematch(")"):
raise error("unbalanced parenthesis")
if char == "=":
subpatternappend((ASSERT, (dir, p)))
else:
subpatternappend((ASSERT_NOT, (dir, p)))
continue
elif sourcematch("("):
# conditional backreference group
condname = ""
while 1:
char = sourceget()
if char is None:
raise error("unterminated name")
if char == ")":
break
condname = condname + char
group = 2
if isname(condname):
condgroup = state.groupdict.get(condname)
if condgroup is None:
raise error("unknown group name")
else:
try:
condgroup = int(condname)
except ValueError:
raise error("bad character in group name")
else:
# flags
if not source.next in FLAGS:
raise error("unexpected end of pattern")
while source.next in FLAGS:
state.flags = state.flags | FLAGS[sourceget()]
if group:
# parse group contents
if group == 2:
# anonymous group
group = None
else:
group = state.opengroup(name)
if condgroup:
p = _parse_sub_cond(source, state, condgroup)
else:
p = _parse_sub(source, state)
if not sourcematch(")"):
raise error("unbalanced parenthesis")
if group is not None:
state.closegroup(group)
subpatternappend((SUBPATTERN, (group, p)))
else:
while 1:
char = sourceget()
if char is None:
raise error("unexpected end of pattern")
if char == ")":
break
raise error("unknown extension")
elif this == "^":
subpatternappend((AT, AT_BEGINNING))
elif this == "$":
subpattern.append((AT, AT_END))
elif this and this[0] == "\\":
code = _escape(source, this, state)
subpatternappend(code)
else:
raise error("parser error")
return subpattern
def fix_flags(src, flags):
# Check and fix flags according to the type of pattern (str or bytes)
if isinstance(src, str):
if not flags & SRE_FLAG_ASCII:
flags |= SRE_FLAG_UNICODE
elif flags & SRE_FLAG_UNICODE:
raise ValueError("ASCII and UNICODE flags are incompatible")
else:
if flags & SRE_FLAG_UNICODE:
raise ValueError("can't use UNICODE flag with a bytes pattern")
return flags
def parse(str, flags=0, pattern=None):
# parse 're' pattern into list of (opcode, argument) tuples
source = Tokenizer(str)
if pattern is None:
pattern = Pattern()
pattern.flags = flags
pattern.str = str
p = _parse_sub(source, pattern, 0)
p.pattern.flags = fix_flags(str, p.pattern.flags)
tail = source.get()
if tail == ")":
raise error("unbalanced parenthesis")
elif tail:
raise error("bogus characters at end of regular expression")
if flags & SRE_FLAG_DEBUG:
p.dump()
if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
# the VERBOSE flag was switched on inside the pattern. to be
# on the safe side, we'll parse the whole thing again...
return parse(str, p.pattern.flags)
return p
def parse_template(source, pattern):
# parse 're' replacement string into list of literals and
# group references
s = Tokenizer(source)
sget = s.get
p = []
a = p.append
def literal(literal, p=p, pappend=a):
if p and p[-1][0] is LITERAL:
p[-1] = LITERAL, p[-1][1] + literal
else:
pappend((LITERAL, literal))
sep = source[:0]
if isinstance(sep, str):
makechar = chr
else:
makechar = chr
while 1:
this = sget()
if this is None:
break # end of replacement string
if this and this[0] == "\\":
# group
c = this[1:2]
if c == "g":
name = ""
if s.match("<"):
while 1:
char = sget()
if char is None:
raise error("unterminated group name")
if char == ">":
break
name = name + char
if not name:
raise error("bad group name")
try:
index = int(name)
if index < 0:
raise error("negative group number")
except ValueError:
if not isname(name):
raise error("bad character in group name")
try:
index = pattern.groupindex[name]
except KeyError:
raise IndexError("unknown group name")
a((MARK, index))
elif c == "0":
if s.next in OCTDIGITS:
this = this + sget()
if s.next in OCTDIGITS:
this = this + sget()
literal(makechar(int(this[1:], 8) & 0xff))
elif c in DIGITS:
isoctal = False
if s.next in DIGITS:
this = this + sget()
if (c in OCTDIGITS and this[2] in OCTDIGITS and
s.next in OCTDIGITS):
this = this + sget()
isoctal = True
literal(makechar(int(this[1:], 8) & 0xff))
if not isoctal:
a((MARK, int(this[1:])))
else:
try:
this = makechar(ESCAPES[this][1])
except KeyError:
pass
literal(this)
else:
literal(this)
# convert template to groups and literals lists
i = 0
groups = []
groupsappend = groups.append
literals = [None] * len(p)
if isinstance(source, str):
encode = lambda x: x
else:
# The tokenizer implicitly decodes bytes objects as latin-1, we must
# therefore re-encode the final representation.
encode = lambda x: x.encode('latin1')
for c, s in p:
if c is MARK:
groupsappend((i, s))
# literal[i] is already None
else:
literals[i] = encode(s)
i = i + 1
return groups, literals
def expand_template(template, match):
g = match.group
sep = match.string[:0]
groups, literals = template
literals = literals[:]
try:
for index, group in groups:
literals[index] = s = g(group)
if s is None:
raise error("unmatched group")
except IndexError:
raise error("invalid group reference")
return sep.join(literals)
| apache-2.0 |
dispiste/gvSIG-rexternal | org.gvsig.rexternal.app.mainplugin/scripting/scripts/test/test1.py | 1 | 1109 |
from gvsig import *
import os
import rlib
reload(rlib)
def console(msg,otype=0):
print msg,
def main(*args):
R = rlib.getREngine(console)
layer = os.path.join(str(script.getResource("data")), "contorno.shp")
R.setwd(R.getLayerPath(script.getResource("data")))
R.source( R.getLayerPath(script.getResource("data/test.r")) )
R.call("load_libraries")
R.call("doalmostnothing",
R.getLayerPath(layer),
R.getLayerName(layer),
R.getTemp("r-output.tif")
)
R.end()
"""
<rprocess>
<name>Proceso R de prueba</name>
<group>Vectorial</group>
<inputs>
<input>
<type>VectorLayer</type>
<name>LAYER</name>
<label>Capa vetorial de prueba</label>
<shapetype>LINE</shapetype>
</input>
<input>
<type>NumericalValue</type>
<name>X</name>
<label>Valor de X inicial</label>
<valuetype>DOUBLE</valuetype>
</input>
</inputs>
<outputs>
<output>
<type>VectorLayer</type>
<name>X</name>
<label>no se que poner aqui</label>
<shapetype>LINE</shapetype>
</output>
</outputs>
</rprocess>
"""
| gpl-3.0 |
ldoktor/virt-test | tests/linux_s3.py | 6 | 1294 | import logging, time
from autotest.client.shared import error
def run_linux_s3(test, params, env):
"""
Suspend a guest Linux OS to memory.
@param test: kvm test object.
@param params: Dictionary with test parameters.
@param env: Dictionary with the test environment.
"""
vm = env.get_vm(params["main_vm"])
vm.verify_alive()
timeout = int(params.get("login_timeout", 360))
session = vm.wait_for_login(timeout=timeout)
logging.info("Checking that VM supports S3")
session.cmd("grep -q mem /sys/power/state")
logging.info("Waiting for a while for X to start")
time.sleep(10)
src_tty = session.cmd_output("fgconsole").strip()
logging.info("Current virtual terminal is %s", src_tty)
if src_tty not in map(str, range(1, 10)):
raise error.TestFail("Got a strange current vt (%s)" % src_tty)
dst_tty = "1"
if src_tty == "1":
dst_tty = "2"
logging.info("Putting VM into S3")
command = "chvt %s && echo mem > /sys/power/state && chvt %s" % (dst_tty,
src_tty)
suspend_timeout = 120 + int(params.get("smp")) * 60
session.cmd(command, timeout=suspend_timeout)
logging.info("VM resumed after S3")
session.close()
| gpl-2.0 |
ceph/samba | third_party/waf/wafadmin/Tools/tex.py | 32 | 7225 | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006 (ita)
"TeX/LaTeX/PDFLaTeX support"
import os, re
import Utils, TaskGen, Task, Runner, Build
from TaskGen import feature, before
from Logs import error, warn, debug
re_tex = re.compile(r'\\(?P<type>include|input|import|bringin|lstinputlisting){(?P<file>[^{}]*)}', re.M)
def scan(self):
node = self.inputs[0]
env = self.env
nodes = []
names = []
if not node: return (nodes, names)
code = Utils.readf(node.abspath(env))
curdirnode = self.curdirnode
abs = curdirnode.abspath()
for match in re_tex.finditer(code):
path = match.group('file')
if path:
for k in ['', '.tex', '.ltx']:
# add another loop for the tex include paths?
debug('tex: trying %s%s' % (path, k))
try:
os.stat(abs+os.sep+path+k)
except OSError:
continue
found = path+k
node = curdirnode.find_resource(found)
if node:
nodes.append(node)
else:
debug('tex: could not find %s' % path)
names.append(path)
debug("tex: found the following : %s and names %s" % (nodes, names))
return (nodes, names)
latex_fun, _ = Task.compile_fun('latex', '${LATEX} ${LATEXFLAGS} ${SRCFILE}', shell=False)
pdflatex_fun, _ = Task.compile_fun('pdflatex', '${PDFLATEX} ${PDFLATEXFLAGS} ${SRCFILE}', shell=False)
bibtex_fun, _ = Task.compile_fun('bibtex', '${BIBTEX} ${BIBTEXFLAGS} ${SRCFILE}', shell=False)
makeindex_fun, _ = Task.compile_fun('bibtex', '${MAKEINDEX} ${MAKEINDEXFLAGS} ${SRCFILE}', shell=False)
g_bibtex_re = re.compile('bibdata', re.M)
def tex_build(task, command='LATEX'):
env = task.env
bld = task.generator.bld
if not env['PROMPT_LATEX']:
env.append_value('LATEXFLAGS', '-interaction=batchmode')
env.append_value('PDFLATEXFLAGS', '-interaction=batchmode')
fun = latex_fun
if command == 'PDFLATEX':
fun = pdflatex_fun
node = task.inputs[0]
reldir = node.bld_dir(env)
#lst = []
#for c in Utils.split_path(reldir):
# if c: lst.append('..')
#srcfile = os.path.join(*(lst + [node.srcpath(env)]))
#sr2 = os.path.join(*(lst + [node.parent.srcpath(env)]))
srcfile = node.abspath(env)
sr2 = node.parent.abspath() + os.pathsep + node.parent.abspath(env) + os.pathsep
aux_node = node.change_ext('.aux')
idx_node = node.change_ext('.idx')
nm = aux_node.name
docuname = nm[ : len(nm) - 4 ] # 4 is the size of ".aux"
# important, set the cwd for everybody
task.cwd = task.inputs[0].parent.abspath(task.env)
warn('first pass on %s' % command)
task.env.env = {'TEXINPUTS': sr2}
task.env.SRCFILE = srcfile
ret = fun(task)
if ret:
return ret
# look in the .aux file if there is a bibfile to process
try:
ct = Utils.readf(aux_node.abspath(env))
except (OSError, IOError):
error('error bibtex scan')
else:
fo = g_bibtex_re.findall(ct)
# there is a .aux file to process
if fo:
warn('calling bibtex')
task.env.env = {'BIBINPUTS': sr2, 'BSTINPUTS': sr2}
task.env.SRCFILE = docuname
ret = bibtex_fun(task)
if ret:
error('error when calling bibtex %s' % docuname)
return ret
# look on the filesystem if there is a .idx file to process
try:
idx_path = idx_node.abspath(env)
os.stat(idx_path)
except OSError:
error('error file.idx scan')
else:
warn('calling makeindex')
task.env.SRCFILE = idx_node.name
task.env.env = {}
ret = makeindex_fun(task)
if ret:
error('error when calling makeindex %s' % idx_path)
return ret
hash = ''
i = 0
while i < 10:
# prevent against infinite loops - one never knows
i += 1
# watch the contents of file.aux
prev_hash = hash
try:
hash = Utils.h_file(aux_node.abspath(env))
except KeyError:
error('could not read aux.h -> %s' % aux_node.abspath(env))
pass
# debug
#print "hash is, ", hash, " ", old_hash
# stop if file.aux does not change anymore
if hash and hash == prev_hash:
break
# run the command
warn('calling %s' % command)
task.env.env = {'TEXINPUTS': sr2 + os.pathsep}
task.env.SRCFILE = srcfile
ret = fun(task)
if ret:
error('error when calling %s %s' % (command, latex_fun))
return ret
return None # ok
latex_vardeps = ['LATEX', 'LATEXFLAGS']
def latex_build(task):
return tex_build(task, 'LATEX')
pdflatex_vardeps = ['PDFLATEX', 'PDFLATEXFLAGS']
def pdflatex_build(task):
return tex_build(task, 'PDFLATEX')
class tex_taskgen(TaskGen.task_gen):
def __init__(self, *k, **kw):
TaskGen.task_gen.__init__(self, *k, **kw)
@feature('tex')
@before('apply_core')
def apply_tex(self):
if not getattr(self, 'type', None) in ['latex', 'pdflatex']:
self.type = 'pdflatex'
tree = self.bld
outs = Utils.to_list(getattr(self, 'outs', []))
# prompt for incomplete files (else the batchmode is used)
self.env['PROMPT_LATEX'] = getattr(self, 'prompt', 1)
deps_lst = []
if getattr(self, 'deps', None):
deps = self.to_list(self.deps)
for filename in deps:
n = self.path.find_resource(filename)
if not n in deps_lst: deps_lst.append(n)
self.source = self.to_list(self.source)
for filename in self.source:
base, ext = os.path.splitext(filename)
node = self.path.find_resource(filename)
if not node: raise Utils.WafError('cannot find %s' % filename)
if self.type == 'latex':
task = self.create_task('latex', node, node.change_ext('.dvi'))
elif self.type == 'pdflatex':
task = self.create_task('pdflatex', node, node.change_ext('.pdf'))
task.env = self.env
task.curdirnode = self.path
# add the manual dependencies
if deps_lst:
variant = node.variant(self.env)
try:
lst = tree.node_deps[task.unique_id()]
for n in deps_lst:
if not n in lst:
lst.append(n)
except KeyError:
tree.node_deps[task.unique_id()] = deps_lst
if self.type == 'latex':
if 'ps' in outs:
tsk = self.create_task('dvips', task.outputs, node.change_ext('.ps'))
tsk.env.env = {'TEXINPUTS' : node.parent.abspath() + os.pathsep + self.path.abspath() + os.pathsep + self.path.abspath(self.env)}
if 'pdf' in outs:
tsk = self.create_task('dvipdf', task.outputs, node.change_ext('.pdf'))
tsk.env.env = {'TEXINPUTS' : node.parent.abspath() + os.pathsep + self.path.abspath() + os.pathsep + self.path.abspath(self.env)}
elif self.type == 'pdflatex':
if 'ps' in outs:
self.create_task('pdf2ps', task.outputs, node.change_ext('.ps'))
self.source = []
def detect(conf):
v = conf.env
for p in 'tex latex pdflatex bibtex dvips dvipdf ps2pdf makeindex pdf2ps'.split():
conf.find_program(p, var=p.upper())
v[p.upper()+'FLAGS'] = ''
v['DVIPSFLAGS'] = '-Ppdf'
b = Task.simple_task_type
b('tex', '${TEX} ${TEXFLAGS} ${SRC}', color='BLUE', shell=False) # not used anywhere
b('bibtex', '${BIBTEX} ${BIBTEXFLAGS} ${SRC}', color='BLUE', shell=False) # not used anywhere
b('dvips', '${DVIPS} ${DVIPSFLAGS} ${SRC} -o ${TGT}', color='BLUE', after="latex pdflatex tex bibtex", shell=False)
b('dvipdf', '${DVIPDF} ${DVIPDFFLAGS} ${SRC} ${TGT}', color='BLUE', after="latex pdflatex tex bibtex", shell=False)
b('pdf2ps', '${PDF2PS} ${PDF2PSFLAGS} ${SRC} ${TGT}', color='BLUE', after="dvipdf pdflatex", shell=False)
b = Task.task_type_from_func
cls = b('latex', latex_build, vars=latex_vardeps)
cls.scan = scan
cls = b('pdflatex', pdflatex_build, vars=pdflatex_vardeps)
cls.scan = scan
| gpl-3.0 |
Drvanon/Game | venv/lib/python3.3/site-packages/sqlalchemy/dialects/drizzle/mysqldb.py | 154 | 1270 | """
.. dialect:: drizzle+mysqldb
:name: MySQL-Python
:dbapi: mysqldb
:connectstring: drizzle+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
:url: http://sourceforge.net/projects/mysql-python
"""
from sqlalchemy.dialects.drizzle.base import (
DrizzleDialect,
DrizzleExecutionContext,
DrizzleCompiler,
DrizzleIdentifierPreparer)
from sqlalchemy.connectors.mysqldb import (
MySQLDBExecutionContext,
MySQLDBCompiler,
MySQLDBIdentifierPreparer,
MySQLDBConnector)
class DrizzleExecutionContext_mysqldb(MySQLDBExecutionContext,
DrizzleExecutionContext):
pass
class DrizzleCompiler_mysqldb(MySQLDBCompiler, DrizzleCompiler):
pass
class DrizzleIdentifierPreparer_mysqldb(MySQLDBIdentifierPreparer,
DrizzleIdentifierPreparer):
pass
class DrizzleDialect_mysqldb(MySQLDBConnector, DrizzleDialect):
execution_ctx_cls = DrizzleExecutionContext_mysqldb
statement_compiler = DrizzleCompiler_mysqldb
preparer = DrizzleIdentifierPreparer_mysqldb
def _detect_charset(self, connection):
"""Sniff out the character set in use for connection results."""
return 'utf8'
dialect = DrizzleDialect_mysqldb
| apache-2.0 |
jiangzhuo/kbengine | kbe/res/scripts/common/Lib/test/test_heapq.py | 111 | 14475 | """Unittests for heapq."""
import sys
import random
import unittest
from test import support
from unittest import TestCase, skipUnless
py_heapq = support.import_fresh_module('heapq', blocked=['_heapq'])
c_heapq = support.import_fresh_module('heapq', fresh=['_heapq'])
# _heapq.nlargest/nsmallest are saved in heapq._nlargest/_smallest when
# _heapq is imported, so check them there
func_names = ['heapify', 'heappop', 'heappush', 'heappushpop',
'heapreplace', '_nlargest', '_nsmallest']
class TestModules(TestCase):
def test_py_functions(self):
for fname in func_names:
self.assertEqual(getattr(py_heapq, fname).__module__, 'heapq')
@skipUnless(c_heapq, 'requires _heapq')
def test_c_functions(self):
for fname in func_names:
self.assertEqual(getattr(c_heapq, fname).__module__, '_heapq')
class TestHeap:
def test_push_pop(self):
# 1) Push 256 random numbers and pop them off, verifying all's OK.
heap = []
data = []
self.check_invariant(heap)
for i in range(256):
item = random.random()
data.append(item)
self.module.heappush(heap, item)
self.check_invariant(heap)
results = []
while heap:
item = self.module.heappop(heap)
self.check_invariant(heap)
results.append(item)
data_sorted = data[:]
data_sorted.sort()
self.assertEqual(data_sorted, results)
# 2) Check that the invariant holds for a sorted array
self.check_invariant(results)
self.assertRaises(TypeError, self.module.heappush, [])
try:
self.assertRaises(TypeError, self.module.heappush, None, None)
self.assertRaises(TypeError, self.module.heappop, None)
except AttributeError:
pass
def check_invariant(self, heap):
# Check the heap invariant.
for pos, item in enumerate(heap):
if pos: # pos 0 has no parent
parentpos = (pos-1) >> 1
self.assertTrue(heap[parentpos] <= item)
def test_heapify(self):
for size in range(30):
heap = [random.random() for dummy in range(size)]
self.module.heapify(heap)
self.check_invariant(heap)
self.assertRaises(TypeError, self.module.heapify, None)
def test_naive_nbest(self):
data = [random.randrange(2000) for i in range(1000)]
heap = []
for item in data:
self.module.heappush(heap, item)
if len(heap) > 10:
self.module.heappop(heap)
heap.sort()
self.assertEqual(heap, sorted(data)[-10:])
def heapiter(self, heap):
# An iterator returning a heap's elements, smallest-first.
try:
while 1:
yield self.module.heappop(heap)
except IndexError:
pass
def test_nbest(self):
# Less-naive "N-best" algorithm, much faster (if len(data) is big
# enough <wink>) than sorting all of data. However, if we had a max
# heap instead of a min heap, it could go faster still via
# heapify'ing all of data (linear time), then doing 10 heappops
# (10 log-time steps).
data = [random.randrange(2000) for i in range(1000)]
heap = data[:10]
self.module.heapify(heap)
for item in data[10:]:
if item > heap[0]: # this gets rarer the longer we run
self.module.heapreplace(heap, item)
self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
self.assertRaises(TypeError, self.module.heapreplace, None)
self.assertRaises(TypeError, self.module.heapreplace, None, None)
self.assertRaises(IndexError, self.module.heapreplace, [], None)
def test_nbest_with_pushpop(self):
data = [random.randrange(2000) for i in range(1000)]
heap = data[:10]
self.module.heapify(heap)
for item in data[10:]:
self.module.heappushpop(heap, item)
self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
self.assertEqual(self.module.heappushpop([], 'x'), 'x')
def test_heappushpop(self):
h = []
x = self.module.heappushpop(h, 10)
self.assertEqual((h, x), ([], 10))
h = [10]
x = self.module.heappushpop(h, 10.0)
self.assertEqual((h, x), ([10], 10.0))
self.assertEqual(type(h[0]), int)
self.assertEqual(type(x), float)
h = [10];
x = self.module.heappushpop(h, 9)
self.assertEqual((h, x), ([10], 9))
h = [10];
x = self.module.heappushpop(h, 11)
self.assertEqual((h, x), ([11], 10))
def test_heapsort(self):
# Exercise everything with repeated heapsort checks
for trial in range(100):
size = random.randrange(50)
data = [random.randrange(25) for i in range(size)]
if trial & 1: # Half of the time, use heapify
heap = data[:]
self.module.heapify(heap)
else: # The rest of the time, use heappush
heap = []
for item in data:
self.module.heappush(heap, item)
heap_sorted = [self.module.heappop(heap) for i in range(size)]
self.assertEqual(heap_sorted, sorted(data))
def test_merge(self):
inputs = []
for i in range(random.randrange(5)):
row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
inputs.append(row)
self.assertEqual(sorted(chain(*inputs)), list(self.module.merge(*inputs)))
self.assertEqual(list(self.module.merge()), [])
def test_merge_does_not_suppress_index_error(self):
# Issue 19018: Heapq.merge suppresses IndexError from user generator
def iterable():
s = list(range(10))
for i in range(20):
yield s[i] # IndexError when i > 10
with self.assertRaises(IndexError):
list(self.module.merge(iterable(), iterable()))
def test_merge_stability(self):
class Int(int):
pass
inputs = [[], [], [], []]
for i in range(20000):
stream = random.randrange(4)
x = random.randrange(500)
obj = Int(x)
obj.pair = (x, stream)
inputs[stream].append(obj)
for stream in inputs:
stream.sort()
result = [i.pair for i in self.module.merge(*inputs)]
self.assertEqual(result, sorted(result))
def test_nsmallest(self):
data = [(random.randrange(2000), i) for i in range(1000)]
for f in (None, lambda x: x[0] * 547 % 2000):
for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
self.assertEqual(list(self.module.nsmallest(n, data)),
sorted(data)[:n])
self.assertEqual(list(self.module.nsmallest(n, data, key=f)),
sorted(data, key=f)[:n])
def test_nlargest(self):
data = [(random.randrange(2000), i) for i in range(1000)]
for f in (None, lambda x: x[0] * 547 % 2000):
for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
self.assertEqual(list(self.module.nlargest(n, data)),
sorted(data, reverse=True)[:n])
self.assertEqual(list(self.module.nlargest(n, data, key=f)),
sorted(data, key=f, reverse=True)[:n])
def test_comparison_operator(self):
# Issue 3051: Make sure heapq works with both __lt__
# For python 3.0, __le__ alone is not enough
def hsort(data, comp):
data = [comp(x) for x in data]
self.module.heapify(data)
return [self.module.heappop(data).x for i in range(len(data))]
class LT:
def __init__(self, x):
self.x = x
def __lt__(self, other):
return self.x > other.x
class LE:
def __init__(self, x):
self.x = x
def __le__(self, other):
return self.x >= other.x
data = [random.random() for i in range(100)]
target = sorted(data, reverse=True)
self.assertEqual(hsort(data, LT), target)
self.assertRaises(TypeError, data, LE)
class TestHeapPython(TestHeap, TestCase):
module = py_heapq
@skipUnless(c_heapq, 'requires _heapq')
class TestHeapC(TestHeap, TestCase):
module = c_heapq
#==============================================================================
class LenOnly:
"Dummy sequence class defining __len__ but not __getitem__."
def __len__(self):
return 10
class GetOnly:
"Dummy sequence class defining __getitem__ but not __len__."
def __getitem__(self, ndx):
return 10
class CmpErr:
"Dummy element that always raises an error during comparison"
def __eq__(self, other):
raise ZeroDivisionError
__ne__ = __lt__ = __le__ = __gt__ = __ge__ = __eq__
def R(seqn):
'Regular generator'
for i in seqn:
yield i
class G:
'Sequence using __getitem__'
def __init__(self, seqn):
self.seqn = seqn
def __getitem__(self, i):
return self.seqn[i]
class I:
'Sequence using iterator protocol'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class Ig:
'Sequence using iterator protocol defined with a generator'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
for val in self.seqn:
yield val
class X:
'Missing __getitem__ and __iter__'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __next__(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class N:
'Iterator missing __next__()'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
class E:
'Test propagation of exceptions'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
3 // 0
class S:
'Test immediate stop'
def __init__(self, seqn):
pass
def __iter__(self):
return self
def __next__(self):
raise StopIteration
from itertools import chain
def L(seqn):
'Test multiple tiers of iterators'
return chain(map(lambda x:x, R(Ig(G(seqn)))))
class SideEffectLT:
def __init__(self, value, heap):
self.value = value
self.heap = heap
def __lt__(self, other):
self.heap[:] = []
return self.value < other.value
class TestErrorHandling:
def test_non_sequence(self):
for f in (self.module.heapify, self.module.heappop):
self.assertRaises((TypeError, AttributeError), f, 10)
for f in (self.module.heappush, self.module.heapreplace,
self.module.nlargest, self.module.nsmallest):
self.assertRaises((TypeError, AttributeError), f, 10, 10)
def test_len_only(self):
for f in (self.module.heapify, self.module.heappop):
self.assertRaises((TypeError, AttributeError), f, LenOnly())
for f in (self.module.heappush, self.module.heapreplace):
self.assertRaises((TypeError, AttributeError), f, LenOnly(), 10)
for f in (self.module.nlargest, self.module.nsmallest):
self.assertRaises(TypeError, f, 2, LenOnly())
def test_get_only(self):
for f in (self.module.heapify, self.module.heappop):
self.assertRaises(TypeError, f, GetOnly())
for f in (self.module.heappush, self.module.heapreplace):
self.assertRaises(TypeError, f, GetOnly(), 10)
for f in (self.module.nlargest, self.module.nsmallest):
self.assertRaises(TypeError, f, 2, GetOnly())
def test_get_only(self):
seq = [CmpErr(), CmpErr(), CmpErr()]
for f in (self.module.heapify, self.module.heappop):
self.assertRaises(ZeroDivisionError, f, seq)
for f in (self.module.heappush, self.module.heapreplace):
self.assertRaises(ZeroDivisionError, f, seq, 10)
for f in (self.module.nlargest, self.module.nsmallest):
self.assertRaises(ZeroDivisionError, f, 2, seq)
def test_arg_parsing(self):
for f in (self.module.heapify, self.module.heappop,
self.module.heappush, self.module.heapreplace,
self.module.nlargest, self.module.nsmallest):
self.assertRaises((TypeError, AttributeError), f, 10)
def test_iterable_args(self):
for f in (self.module.nlargest, self.module.nsmallest):
for s in ("123", "", range(1000), (1, 1.2), range(2000,2200,5)):
for g in (G, I, Ig, L, R):
self.assertEqual(list(f(2, g(s))), list(f(2,s)))
self.assertEqual(list(f(2, S(s))), [])
self.assertRaises(TypeError, f, 2, X(s))
self.assertRaises(TypeError, f, 2, N(s))
self.assertRaises(ZeroDivisionError, f, 2, E(s))
# Issue #17278: the heap may change size while it's being walked.
def test_heappush_mutating_heap(self):
heap = []
heap.extend(SideEffectLT(i, heap) for i in range(200))
# Python version raises IndexError, C version RuntimeError
with self.assertRaises((IndexError, RuntimeError)):
self.module.heappush(heap, SideEffectLT(5, heap))
def test_heappop_mutating_heap(self):
heap = []
heap.extend(SideEffectLT(i, heap) for i in range(200))
# Python version raises IndexError, C version RuntimeError
with self.assertRaises((IndexError, RuntimeError)):
self.module.heappop(heap)
class TestErrorHandlingPython(TestErrorHandling, TestCase):
module = py_heapq
@skipUnless(c_heapq, 'requires _heapq')
class TestErrorHandlingC(TestErrorHandling, TestCase):
module = c_heapq
if __name__ == "__main__":
unittest.main()
| lgpl-3.0 |
mancoast/CPythonPyc_test | cpython/323_test_extcall.py | 54 | 7022 |
"""Doctest for method/function calls.
We're going the use these types for extra testing
>>> from collections import UserList
>>> from collections import UserDict
We're defining four helper functions
>>> def e(a,b):
... print(a, b)
>>> def f(*a, **k):
... print(a, support.sortdict(k))
>>> def g(x, *y, **z):
... print(x, y, support.sortdict(z))
>>> def h(j=1, a=2, h=3):
... print(j, a, h)
Argument list examples
>>> f()
() {}
>>> f(1)
(1,) {}
>>> f(1, 2)
(1, 2) {}
>>> f(1, 2, 3)
(1, 2, 3) {}
>>> f(1, 2, 3, *(4, 5))
(1, 2, 3, 4, 5) {}
>>> f(1, 2, 3, *[4, 5])
(1, 2, 3, 4, 5) {}
>>> f(1, 2, 3, *UserList([4, 5]))
(1, 2, 3, 4, 5) {}
Here we add keyword arguments
>>> f(1, 2, 3, **{'a':4, 'b':5})
(1, 2, 3) {'a': 4, 'b': 5}
>>> f(1, 2, 3, *[4, 5], **{'a':6, 'b':7})
(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
>>> f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b': 9})
(1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
>>> f(1, 2, 3, **UserDict(a=4, b=5))
(1, 2, 3) {'a': 4, 'b': 5}
>>> f(1, 2, 3, *(4, 5), **UserDict(a=6, b=7))
(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
>>> f(1, 2, 3, x=4, y=5, *(6, 7), **UserDict(a=8, b=9))
(1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
Examples with invalid arguments (TypeErrors). We're also testing the function
names in the exception messages.
Verify clearing of SF bug #733667
>>> e(c=4)
Traceback (most recent call last):
...
TypeError: e() got an unexpected keyword argument 'c'
>>> g()
Traceback (most recent call last):
...
TypeError: g() takes at least 1 argument (0 given)
>>> g(*())
Traceback (most recent call last):
...
TypeError: g() takes at least 1 argument (0 given)
>>> g(*(), **{})
Traceback (most recent call last):
...
TypeError: g() takes at least 1 argument (0 given)
>>> g(1)
1 () {}
>>> g(1, 2)
1 (2,) {}
>>> g(1, 2, 3)
1 (2, 3) {}
>>> g(1, 2, 3, *(4, 5))
1 (2, 3, 4, 5) {}
>>> class Nothing: pass
...
>>> g(*Nothing())
Traceback (most recent call last):
...
TypeError: g() argument after * must be a sequence, not Nothing
>>> class Nothing:
... def __len__(self): return 5
...
>>> g(*Nothing())
Traceback (most recent call last):
...
TypeError: g() argument after * must be a sequence, not Nothing
>>> class Nothing():
... def __len__(self): return 5
... def __getitem__(self, i):
... if i<3: return i
... else: raise IndexError(i)
...
>>> g(*Nothing())
0 (1, 2) {}
>>> class Nothing:
... def __init__(self): self.c = 0
... def __iter__(self): return self
... def __next__(self):
... if self.c == 4:
... raise StopIteration
... c = self.c
... self.c += 1
... return c
...
>>> g(*Nothing())
0 (1, 2, 3) {}
Make sure that the function doesn't stomp the dictionary
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> d2 = d.copy()
>>> g(1, d=4, **d)
1 () {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> d == d2
True
What about willful misconduct?
>>> def saboteur(**kw):
... kw['x'] = 'm'
... return kw
>>> d = {}
>>> kw = saboteur(a=1, **d)
>>> d
{}
>>> g(1, 2, 3, **{'x': 4, 'y': 5})
Traceback (most recent call last):
...
TypeError: g() got multiple values for keyword argument 'x'
>>> f(**{1:2})
Traceback (most recent call last):
...
TypeError: f() keywords must be strings
>>> h(**{'e': 2})
Traceback (most recent call last):
...
TypeError: h() got an unexpected keyword argument 'e'
>>> h(*h)
Traceback (most recent call last):
...
TypeError: h() argument after * must be a sequence, not function
>>> dir(*h)
Traceback (most recent call last):
...
TypeError: dir() argument after * must be a sequence, not function
>>> None(*h)
Traceback (most recent call last):
...
TypeError: NoneType object argument after * must be a sequence, \
not function
>>> h(**h)
Traceback (most recent call last):
...
TypeError: h() argument after ** must be a mapping, not function
>>> dir(**h)
Traceback (most recent call last):
...
TypeError: dir() argument after ** must be a mapping, not function
>>> None(**h)
Traceback (most recent call last):
...
TypeError: NoneType object argument after ** must be a mapping, \
not function
>>> dir(b=1, **{'b': 1})
Traceback (most recent call last):
...
TypeError: dir() got multiple values for keyword argument 'b'
Another helper function
>>> def f2(*a, **b):
... return a, b
>>> d = {}
>>> for i in range(512):
... key = 'k%d' % i
... d[key] = i
>>> a, b = f2(1, *(2,3), **d)
>>> len(a), len(b), b == d
(3, 512, True)
>>> class Foo:
... def method(self, arg1, arg2):
... return arg1+arg2
>>> x = Foo()
>>> Foo.method(*(x, 1, 2))
3
>>> Foo.method(x, *(1, 2))
3
>>> Foo.method(*(1, 2, 3))
5
>>> Foo.method(1, *[2, 3])
5
A PyCFunction that takes only positional parameters should allow an
empty keyword dictionary to pass without a complaint, but raise a
TypeError if te dictionary is not empty
>>> try:
... silence = id(1, *{})
... True
... except:
... False
True
>>> id(1, **{'foo': 1})
Traceback (most recent call last):
...
TypeError: id() takes no keyword arguments
A corner case of keyword dictionary items being deleted during
the function call setup. See <http://bugs.python.org/issue2016>.
>>> class Name(str):
... def __eq__(self, other):
... try:
... del x[self]
... except KeyError:
... pass
... return str.__eq__(self, other)
... def __hash__(self):
... return str.__hash__(self)
>>> x = {Name("a"):1, Name("b"):2}
>>> def f(a, b):
... print(a,b)
>>> f(**x)
1 2
A obscure message:
>>> def f(a, b):
... pass
>>> f(b=1)
Traceback (most recent call last):
...
TypeError: f() takes exactly 2 arguments (1 given)
The number of arguments passed in includes keywords:
>>> def f(a):
... pass
>>> f(6, a=4, *(1, 2, 3))
Traceback (most recent call last):
...
TypeError: f() takes exactly 1 positional argument (5 given)
>>> def f(a, *, kw):
... pass
>>> f(6, 4, kw=4)
Traceback (most recent call last):
...
TypeError: f() takes exactly 1 positional argument (3 given)
"""
import sys
from test import support
def test_main():
support.run_doctest(sys.modules[__name__], True)
if __name__ == '__main__':
test_main()
| gpl-3.0 |
gx1997/chrome-loongson | third_party/mesa/MesaLib/src/gallium/tests/python/tests/surface_copy.py | 32 | 5561 | #!/usr/bin/env python
##########################################################################
#
# Copyright 2009 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sub license, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial portions
# of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
# IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
# ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
##########################################################################
import os
import random
from gallium import *
from base import *
def lods(*dims):
size = max(dims)
lods = 0
while size:
lods += 1
size >>= 1
return lods
class TextureTest(TestCase):
tags = (
'target',
'format',
'width',
'height',
'depth',
'last_level',
'face',
'level',
'zslice',
)
def test(self):
dev = self.dev
ctx = self.ctx
target = self.target
format = self.format
width = self.width
height = self.height
depth = self.depth
last_level = self.last_level
face = self.face
level = self.level
zslice = self.zslice
bind = PIPE_BIND_SAMPLER_VIEW
geom_flags = 0
sample_count = 0
if not dev.is_format_supported(format, target, sample_count, bind, geom_flags):
raise TestSkip
if not dev.is_format_supported(format, target, sample_count, bind, geom_flags):
raise TestSkip
# textures
dst_texture = dev.resource_create(
target = target,
format = format,
width = width,
height = height,
depth = depth,
last_level = last_level,
bind = bind,
)
dst_surface = dst_texture.get_surface(face = face, level = level, zslice = zslice)
src_texture = dev.resource_create(
target = target,
format = format,
width = dst_surface.width,
height = dst_surface.height,
depth = 1,
last_level = 0,
bind = PIPE_BIND_SAMPLER_VIEW,
)
src_surface = src_texture.get_surface()
w = dst_surface.width
h = dst_surface.height
stride = util_format_get_stride(format, w)
size = util_format_get_nblocksy(format, h) * stride
src_raw = os.urandom(size)
ctx.surface_write_raw(src_surface, 0, 0, w, h, src_raw, stride)
ctx.surface_copy(dst_surface, 0, 0,
src_surface, 0, 0, w, h)
dst_raw = ctx.surface_read_raw(dst_surface, 0, 0, w, h)
if dst_raw != src_raw:
raise TestFailure
def main():
dev = Device()
ctx = dev.context_create()
suite = TestSuite()
targets = [
PIPE_TEXTURE_2D,
PIPE_TEXTURE_CUBE,
PIPE_TEXTURE_3D,
]
sizes = [64, 32, 16, 8, 4, 2, 1]
#sizes = [1020, 508, 252, 62, 30, 14, 6, 3]
#sizes = [64]
#sizes = [63]
faces = [
PIPE_TEX_FACE_POS_X,
PIPE_TEX_FACE_NEG_X,
PIPE_TEX_FACE_POS_Y,
PIPE_TEX_FACE_NEG_Y,
PIPE_TEX_FACE_POS_Z,
PIPE_TEX_FACE_NEG_Z,
]
try:
n = int(sys.argv[1])
except:
n = 10000
for i in range(n):
format = random.choice(formats.keys())
if not util_format_is_depth_or_stencil(format):
is_depth_or_stencil = util_format_is_depth_or_stencil(format)
if is_depth_or_stencil:
target = PIPE_TEXTURE_2D
else:
target = random.choice(targets)
size = random.choice(sizes)
if target == PIPE_TEXTURE_3D:
depth = size
else:
depth = 1
if target == PIPE_TEXTURE_CUBE:
face = random.choice(faces)
else:
face = PIPE_TEX_FACE_POS_X
levels = lods(size)
last_level = random.randint(0, levels - 1)
level = random.randint(0, last_level)
zslice = random.randint(0, max(depth >> level, 1) - 1)
test = TextureTest(
dev = dev,
ctx = ctx,
target = target,
format = format,
width = size,
height = size,
depth = depth,
last_level = last_level,
face = face,
level = level,
zslice = zslice,
)
suite.add_test(test)
suite.run()
if __name__ == '__main__':
main()
| bsd-3-clause |
junhuac/MQUIC | depot_tools/external_bin/gsutil/gsutil_4.15/gsutil/third_party/python-gflags/gflags.py | 448 | 104236 | #!/usr/bin/env python
#
# Copyright (c) 2002, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ---
# Author: Chad Lester
# Design and style contributions by:
# Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann,
# Eric Veach, Laurence Gonsalves, Matthew Springer
# Code reorganized a bit by Craig Silverstein
"""This module is used to define and parse command line flags.
This module defines a *distributed* flag-definition policy: rather than
an application having to define all flags in or near main(), each python
module defines flags that are useful to it. When one python module
imports another, it gains access to the other's flags. (This is
implemented by having all modules share a common, global registry object
containing all the flag information.)
Flags are defined through the use of one of the DEFINE_xxx functions.
The specific function used determines how the flag is parsed, checked,
and optionally type-converted, when it's seen on the command line.
IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a
'FlagValues' object (typically the global FlagValues FLAGS, defined
here). The 'FlagValues' object can scan the command line arguments and
pass flag arguments to the corresponding 'Flag' objects for
value-checking and type conversion. The converted flag values are
available as attributes of the 'FlagValues' object.
Code can access the flag through a FlagValues object, for instance
gflags.FLAGS.myflag. Typically, the __main__ module passes the command
line arguments to gflags.FLAGS for parsing.
At bottom, this module calls getopt(), so getopt functionality is
supported, including short- and long-style flags, and the use of -- to
terminate flags.
Methods defined by the flag module will throw 'FlagsError' exceptions.
The exception argument will be a human-readable string.
FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags
take a name, default value, help-string, and optional 'short' name
(one-letter name). Some flags have other arguments, which are described
with the flag.
DEFINE_string: takes any input, and interprets it as a string.
DEFINE_bool or
DEFINE_boolean: typically does not take an argument: say --myflag to
set FLAGS.myflag to true, or --nomyflag to set
FLAGS.myflag to false. Alternately, you can say
--myflag=true or --myflag=t or --myflag=1 or
--myflag=false or --myflag=f or --myflag=0
DEFINE_float: takes an input and interprets it as a floating point
number. Takes optional args lower_bound and upper_bound;
if the number specified on the command line is out of
range, it will raise a FlagError.
DEFINE_integer: takes an input and interprets it as an integer. Takes
optional args lower_bound and upper_bound as for floats.
DEFINE_enum: takes a list of strings which represents legal values. If
the command-line value is not in this list, raise a flag
error. Otherwise, assign to FLAGS.flag as a string.
DEFINE_list: Takes a comma-separated list of strings on the commandline.
Stores them in a python list object.
DEFINE_spaceseplist: Takes a space-separated list of strings on the
commandline. Stores them in a python list object.
Example: --myspacesepflag "foo bar baz"
DEFINE_multistring: The same as DEFINE_string, except the flag can be
specified more than once on the commandline. The
result is a python list object (list of strings),
even if the flag is only on the command line once.
DEFINE_multi_int: The same as DEFINE_integer, except the flag can be
specified more than once on the commandline. The
result is a python list object (list of ints), even if
the flag is only on the command line once.
SPECIAL FLAGS: There are a few flags that have special meaning:
--help prints a list of all the flags in a human-readable fashion
--helpshort prints a list of all key flags (see below).
--helpxml prints a list of all flags, in XML format. DO NOT parse
the output of --help and --helpshort. Instead, parse
the output of --helpxml. For more info, see
"OUTPUT FOR --helpxml" below.
--flagfile=foo read flags from file foo.
--undefok=f1,f2 ignore unrecognized option errors for f1,f2.
For boolean flags, you should use --undefok=boolflag, and
--boolflag and --noboolflag will be accepted. Do not use
--undefok=noboolflag.
-- as in getopt(), terminates flag-processing
FLAGS VALIDATORS: If your program:
- requires flag X to be specified
- needs flag Y to match a regular expression
- or requires any more general constraint to be satisfied
then validators are for you!
Each validator represents a constraint over one flag, which is enforced
starting from the initial parsing of the flags and until the program
terminates.
Also, lower_bound and upper_bound for numerical flags are enforced using flag
validators.
Howto:
If you want to enforce a constraint over one flag, use
gflags.RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS)
After flag values are initially parsed, and after any change to the specified
flag, method checker(flag_value) will be executed. If constraint is not
satisfied, an IllegalFlagValue exception will be raised. See
RegisterValidator's docstring for a detailed explanation on how to construct
your own checker.
EXAMPLE USAGE:
FLAGS = gflags.FLAGS
gflags.DEFINE_integer('my_version', 0, 'Version number.')
gflags.DEFINE_string('filename', None, 'Input file name', short_name='f')
gflags.RegisterValidator('my_version',
lambda value: value % 2 == 0,
message='--my_version must be divisible by 2')
gflags.MarkFlagAsRequired('filename')
NOTE ON --flagfile:
Flags may be loaded from text files in addition to being specified on
the commandline.
Any flags you don't feel like typing, throw them in a file, one flag per
line, for instance:
--myflag=myvalue
--nomyboolean_flag
You then specify your file with the special flag '--flagfile=somefile'.
You CAN recursively nest flagfile= tokens OR use multiple files on the
command line. Lines beginning with a single hash '#' or a double slash
'//' are comments in your flagfile.
Any flagfile=<file> will be interpreted as having a relative path from
the current working directory rather than from the place the file was
included from:
myPythonScript.py --flagfile=config/somefile.cfg
If somefile.cfg includes further --flagfile= directives, these will be
referenced relative to the original CWD, not from the directory the
including flagfile was found in!
The caveat applies to people who are including a series of nested files
in a different dir than they are executing out of. Relative path names
are always from CWD, not from the directory of the parent include
flagfile. We do now support '~' expanded directory names.
Absolute path names ALWAYS work!
EXAMPLE USAGE:
FLAGS = gflags.FLAGS
# Flag names are globally defined! So in general, we need to be
# careful to pick names that are unlikely to be used by other libraries.
# If there is a conflict, we'll get an error at import time.
gflags.DEFINE_string('name', 'Mr. President', 'your name')
gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0)
gflags.DEFINE_boolean('debug', False, 'produces debugging output')
gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender')
def main(argv):
try:
argv = FLAGS(argv) # parse flags
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS)
sys.exit(1)
if FLAGS.debug: print 'non-flag arguments:', argv
print 'Happy Birthday', FLAGS.name
if FLAGS.age is not None:
print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender)
if __name__ == '__main__':
main(sys.argv)
KEY FLAGS:
As we already explained, each module gains access to all flags defined
by all the other modules it transitively imports. In the case of
non-trivial scripts, this means a lot of flags ... For documentation
purposes, it is good to identify the flags that are key (i.e., really
important) to a module. Clearly, the concept of "key flag" is a
subjective one. When trying to determine whether a flag is key to a
module or not, assume that you are trying to explain your module to a
potential user: which flags would you really like to mention first?
We'll describe shortly how to declare which flags are key to a module.
For the moment, assume we know the set of key flags for each module.
Then, if you use the app.py module, you can use the --helpshort flag to
print only the help for the flags that are key to the main module, in a
human-readable format.
NOTE: If you need to parse the flag help, do NOT use the output of
--help / --helpshort. That output is meant for human consumption, and
may be changed in the future. Instead, use --helpxml; flags that are
key for the main module are marked there with a <key>yes</key> element.
The set of key flags for a module M is composed of:
1. Flags defined by module M by calling a DEFINE_* function.
2. Flags that module M explictly declares as key by using the function
DECLARE_key_flag(<flag_name>)
3. Key flags of other modules that M specifies by using the function
ADOPT_module_key_flags(<other_module>)
This is a "bulk" declaration of key flags: each flag that is key for
<other_module> becomes key for the current module too.
Notice that if you do not use the functions described at points 2 and 3
above, then --helpshort prints information only about the flags defined
by the main module of our script. In many cases, this behavior is good
enough. But if you move part of the main module code (together with the
related flags) into a different module, then it is nice to use
DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort
lists all relevant flags (otherwise, your code refactoring may confuse
your users).
Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own
pluses and minuses: DECLARE_key_flag is more targeted and may lead a
more focused --helpshort documentation. ADOPT_module_key_flags is good
for cases when an entire module is considered key to the current script.
Also, it does not require updates to client scripts when a new flag is
added to the module.
EXAMPLE USAGE 2 (WITH KEY FLAGS):
Consider an application that contains the following three files (two
auxiliary modules and a main module)
File libfoo.py:
import gflags
gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start')
gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.')
... some code ...
File libbar.py:
import gflags
gflags.DEFINE_string('bar_gfs_path', '/gfs/path',
'Path to the GFS files for libbar.')
gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com',
'Email address for bug reports about module libbar.')
gflags.DEFINE_boolean('bar_risky_hack', False,
'Turn on an experimental and buggy optimization.')
... some code ...
File myscript.py:
import gflags
import libfoo
import libbar
gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.')
# Declare that all flags that are key for libfoo are
# key for this module too.
gflags.ADOPT_module_key_flags(libfoo)
# Declare that the flag --bar_gfs_path (defined in libbar) is key
# for this module.
gflags.DECLARE_key_flag('bar_gfs_path')
... some code ...
When myscript is invoked with the flag --helpshort, the resulted help
message lists information about all the key flags for myscript:
--num_iterations, --num_replicas, --rpc2, and --bar_gfs_path.
Of course, myscript uses all the flags declared by it (in this case,
just --num_replicas) or by any of the modules it transitively imports
(e.g., the modules libfoo, libbar). E.g., it can access the value of
FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key
flag for myscript.
OUTPUT FOR --helpxml:
The --helpxml flag generates output with the following structure:
<?xml version="1.0"?>
<AllFlags>
<program>PROGRAM_BASENAME</program>
<usage>MAIN_MODULE_DOCSTRING</usage>
(<flag>
[<key>yes</key>]
<file>DECLARING_MODULE</file>
<name>FLAG_NAME</name>
<meaning>FLAG_HELP_MESSAGE</meaning>
<default>DEFAULT_FLAG_VALUE</default>
<current>CURRENT_FLAG_VALUE</current>
<type>FLAG_TYPE</type>
[OPTIONAL_ELEMENTS]
</flag>)*
</AllFlags>
Notes:
1. The output is intentionally similar to the output generated by the
C++ command-line flag library. The few differences are due to the
Python flags that do not have a C++ equivalent (at least not yet),
e.g., DEFINE_list.
2. New XML elements may be added in the future.
3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can
pass for this flag on the command-line. E.g., for a flag defined
using DEFINE_list, this field may be foo,bar, not ['foo', 'bar'].
4. CURRENT_FLAG_VALUE is produced using str(). This means that the
string 'false' will be represented in the same way as the boolean
False. Using repr() would have removed this ambiguity and simplified
parsing, but would have broken the compatibility with the C++
command-line flags.
5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of
flags: lower_bound, upper_bound (for flags that specify bounds),
enum_value (for enum flags), list_separator (for flags that consist of
a list of values, separated by a special token).
6. We do not provide any example here: please use --helpxml instead.
This module requires at least python 2.2.1 to run.
"""
import cgi
import getopt
import os
import re
import string
import struct
import sys
# pylint: disable-msg=C6204
try:
import fcntl
except ImportError:
fcntl = None
try:
# Importing termios will fail on non-unix platforms.
import termios
except ImportError:
termios = None
import gflags_validators
# pylint: enable-msg=C6204
# Are we running under pychecker?
_RUNNING_PYCHECKER = 'pychecker.python' in sys.modules
def _GetCallingModuleObjectAndName():
"""Returns the module that's calling into this module.
We generally use this function to get the name of the module calling a
DEFINE_foo... function.
"""
# Walk down the stack to find the first globals dict that's not ours.
for depth in range(1, sys.getrecursionlimit()):
if not sys._getframe(depth).f_globals is globals():
globals_for_frame = sys._getframe(depth).f_globals
module, module_name = _GetModuleObjectAndName(globals_for_frame)
if module_name is not None:
return module, module_name
raise AssertionError("No module was found")
def _GetCallingModule():
"""Returns the name of the module that's calling into this module."""
return _GetCallingModuleObjectAndName()[1]
def _GetThisModuleObjectAndName():
"""Returns: (module object, module name) for this module."""
return _GetModuleObjectAndName(globals())
# module exceptions:
class FlagsError(Exception):
"""The base class for all flags errors."""
pass
class DuplicateFlag(FlagsError):
"""Raised if there is a flag naming conflict."""
pass
class CantOpenFlagFileError(FlagsError):
"""Raised if flagfile fails to open: doesn't exist, wrong permissions, etc."""
pass
class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag):
"""Special case of DuplicateFlag -- SWIG flag value can't be set to None.
This can be raised when a duplicate flag is created. Even if allow_override is
True, we still abort if the new value is None, because it's currently
impossible to pass None default value back to SWIG. See FlagValues.SetDefault
for details.
"""
pass
class DuplicateFlagError(DuplicateFlag):
"""A DuplicateFlag whose message cites the conflicting definitions.
A DuplicateFlagError conveys more information than a DuplicateFlag,
namely the modules where the conflicting definitions occur. This
class was created to avoid breaking external modules which depend on
the existing DuplicateFlags interface.
"""
def __init__(self, flagname, flag_values, other_flag_values=None):
"""Create a DuplicateFlagError.
Args:
flagname: Name of the flag being redefined.
flag_values: FlagValues object containing the first definition of
flagname.
other_flag_values: If this argument is not None, it should be the
FlagValues object where the second definition of flagname occurs.
If it is None, we assume that we're being called when attempting
to create the flag a second time, and we use the module calling
this one as the source of the second definition.
"""
self.flagname = flagname
first_module = flag_values.FindModuleDefiningFlag(
flagname, default='<unknown>')
if other_flag_values is None:
second_module = _GetCallingModule()
else:
second_module = other_flag_values.FindModuleDefiningFlag(
flagname, default='<unknown>')
msg = "The flag '%s' is defined twice. First from %s, Second from %s" % (
self.flagname, first_module, second_module)
DuplicateFlag.__init__(self, msg)
class IllegalFlagValue(FlagsError):
"""The flag command line argument is illegal."""
pass
class UnrecognizedFlag(FlagsError):
"""Raised if a flag is unrecognized."""
pass
# An UnrecognizedFlagError conveys more information than an UnrecognizedFlag.
# Since there are external modules that create DuplicateFlags, the interface to
# DuplicateFlag shouldn't change. The flagvalue will be assigned the full value
# of the flag and its argument, if any, allowing handling of unrecognized flags
# in an exception handler.
# If flagvalue is the empty string, then this exception is an due to a
# reference to a flag that was not already defined.
class UnrecognizedFlagError(UnrecognizedFlag):
def __init__(self, flagname, flagvalue=''):
self.flagname = flagname
self.flagvalue = flagvalue
UnrecognizedFlag.__init__(
self, "Unknown command line flag '%s'" % flagname)
# Global variable used by expvar
_exported_flags = {}
_help_width = 80 # width of help output
def GetHelpWidth():
"""Returns: an integer, the width of help lines that is used in TextWrap."""
if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None):
return _help_width
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = struct.unpack('hh', data)[1]
# Emacs mode returns 0.
# Here we assume that any value below 40 is unreasonable
if columns >= 40:
return columns
# Returning an int as default is fine, int(int) just return the int.
return int(os.getenv('COLUMNS', _help_width))
except (TypeError, IOError, struct.error):
return _help_width
def CutCommonSpacePrefix(text):
"""Removes a common space prefix from the lines of a multiline text.
If the first line does not start with a space, it is left as it is and
only in the remaining lines a common space prefix is being searched
for. That means the first line will stay untouched. This is especially
useful to turn doc strings into help texts. This is because some
people prefer to have the doc comment start already after the
apostrophe and then align the following lines while others have the
apostrophes on a separate line.
The function also drops trailing empty lines and ignores empty lines
following the initial content line while calculating the initial
common whitespace.
Args:
text: text to work on
Returns:
the resulting text
"""
text_lines = text.splitlines()
# Drop trailing empty lines
while text_lines and not text_lines[-1]:
text_lines = text_lines[:-1]
if text_lines:
# We got some content, is the first line starting with a space?
if text_lines[0] and text_lines[0][0].isspace():
text_first_line = []
else:
text_first_line = [text_lines.pop(0)]
# Calculate length of common leading whitespace (only over content lines)
common_prefix = os.path.commonprefix([line for line in text_lines if line])
space_prefix_len = len(common_prefix) - len(common_prefix.lstrip())
# If we have a common space prefix, drop it from all lines
if space_prefix_len:
for index in xrange(len(text_lines)):
if text_lines[index]:
text_lines[index] = text_lines[index][space_prefix_len:]
return '\n'.join(text_first_line + text_lines)
return ''
def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '):
"""Wraps a given text to a maximum line length and returns it.
We turn lines that only contain whitespace into empty lines. We keep
new lines and tabs (e.g., we do not treat tabs as spaces).
Args:
text: text to wrap
length: maximum length of a line, includes indentation
if this is None then use GetHelpWidth()
indent: indent for all but first line
firstline_indent: indent for first line; if None, fall back to indent
tabs: replacement for tabs
Returns:
wrapped text
Raises:
FlagsError: if indent not shorter than length
FlagsError: if firstline_indent not shorter than length
"""
# Get defaults where callee used None
if length is None:
length = GetHelpWidth()
if indent is None:
indent = ''
if len(indent) >= length:
raise FlagsError('Indent must be shorter than length')
# In line we will be holding the current line which is to be started
# with indent (or firstline_indent if available) and then appended
# with words.
if firstline_indent is None:
firstline_indent = ''
line = indent
else:
line = firstline_indent
if len(firstline_indent) >= length:
raise FlagsError('First line indent must be shorter than length')
# If the callee does not care about tabs we simply convert them to
# spaces If callee wanted tabs to be single space then we do that
# already here.
if not tabs or tabs == ' ':
text = text.replace('\t', ' ')
else:
tabs_are_whitespace = not tabs.strip()
line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE)
# Split the text into lines and the lines with the regex above. The
# resulting lines are collected in result[]. For each split we get the
# spaces, the tabs and the next non white space (e.g. next word).
result = []
for text_line in text.splitlines():
# Store result length so we can find out whether processing the next
# line gave any new content
old_result_len = len(result)
# Process next line with line_regex. For optimization we do an rstrip().
# - process tabs (changes either line or word, see below)
# - process word (first try to squeeze on line, then wrap or force wrap)
# Spaces found on the line are ignored, they get added while wrapping as
# needed.
for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()):
# If tabs weren't converted to spaces, handle them now
if current_tabs:
# If the last thing we added was a space anyway then drop
# it. But let's not get rid of the indentation.
if (((result and line != indent) or
(not result and line != firstline_indent)) and line[-1] == ' '):
line = line[:-1]
# Add the tabs, if that means adding whitespace, just add it at
# the line, the rstrip() code while shorten the line down if
# necessary
if tabs_are_whitespace:
line += tabs * len(current_tabs)
else:
# if not all tab replacement is whitespace we prepend it to the word
word = tabs * len(current_tabs) + word
# Handle the case where word cannot be squeezed onto current last line
if len(line) + len(word) > length and len(indent) + len(word) <= length:
result.append(line.rstrip())
line = indent + word
word = ''
# No space left on line or can we append a space?
if len(line) + 1 >= length:
result.append(line.rstrip())
line = indent
else:
line += ' '
# Add word and shorten it up to allowed line length. Restart next
# line with indent and repeat, or add a space if we're done (word
# finished) This deals with words that cannot fit on one line
# (e.g. indent + word longer than allowed line length).
while len(line) + len(word) >= length:
line += word
result.append(line[:length])
word = line[length:]
line = indent
# Default case, simply append the word and a space
if word:
line += word + ' '
# End of input line. If we have content we finish the line. If the
# current line is just the indent but we had content in during this
# original line then we need to add an empty line.
if (result and line != indent) or (not result and line != firstline_indent):
result.append(line.rstrip())
elif len(result) == old_result_len:
result.append('')
line = indent
return '\n'.join(result)
def DocToHelp(doc):
"""Takes a __doc__ string and reformats it as help."""
# Get rid of starting and ending white space. Using lstrip() or even
# strip() could drop more than maximum of first line and right space
# of last line.
doc = doc.strip()
# Get rid of all empty lines
whitespace_only_line = re.compile('^[ \t]+$', re.M)
doc = whitespace_only_line.sub('', doc)
# Cut out common space at line beginnings
doc = CutCommonSpacePrefix(doc)
# Just like this module's comment, comments tend to be aligned somehow.
# In other words they all start with the same amount of white space
# 1) keep double new lines
# 2) keep ws after new lines if not empty line
# 3) all other new lines shall be changed to a space
# Solution: Match new lines between non white space and replace with space.
doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M)
return doc
def _GetModuleObjectAndName(globals_dict):
"""Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
A pair consisting of (1) module object and (2) module name (a
string). Returns (None, None) if the module could not be
identified.
"""
# The use of .items() (instead of .iteritems()) is NOT a mistake: if
# a parallel thread imports a module while we iterate over
# .iteritems() (not nice, but possible), we get a RuntimeError ...
# Hence, we use the slightly slower but safer .items().
for name, module in sys.modules.items():
if getattr(module, '__dict__', None) is globals_dict:
if name == '__main__':
# Pick a more informative name for the main module.
name = sys.argv[0]
return (module, name)
return (None, None)
def _GetMainModule():
"""Returns: string, name of the module from which execution started."""
# First, try to use the same logic used by _GetCallingModuleObjectAndName(),
# i.e., call _GetModuleObjectAndName(). For that we first need to
# find the dictionary that the main module uses to store the
# globals.
#
# That's (normally) the same dictionary object that the deepest
# (oldest) stack frame is using for globals.
deepest_frame = sys._getframe(0)
while deepest_frame.f_back is not None:
deepest_frame = deepest_frame.f_back
globals_for_main_module = deepest_frame.f_globals
main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1]
# The above strategy fails in some cases (e.g., tools that compute
# code coverage by redefining, among other things, the main module).
# If so, just use sys.argv[0]. We can probably always do this, but
# it's safest to try to use the same logic as _GetCallingModuleObjectAndName()
if main_module_name is None:
main_module_name = sys.argv[0]
return main_module_name
class FlagValues:
"""Registry of 'Flag' objects.
A 'FlagValues' can then scan command line arguments, passing flag
arguments through to the 'Flag' objects that it owns. It also
provides easy access to the flag values. Typically only one
'FlagValues' object is needed by an application: gflags.FLAGS
This class is heavily overloaded:
'Flag' objects are registered via __setitem__:
FLAGS['longname'] = x # register a new flag
The .value attribute of the registered 'Flag' objects can be accessed
as attributes of this 'FlagValues' object, through __getattr__. Both
the long and short name of the original 'Flag' objects can be used to
access its value:
FLAGS.longname # parsed flag value
FLAGS.x # parsed flag value (short name)
Command line arguments are scanned and passed to the registered 'Flag'
objects through the __call__ method. Unparsed arguments, including
argv[0] (e.g. the program name) are returned.
argv = FLAGS(sys.argv) # scan command line arguments
The original registered Flag objects can be retrieved through the use
of the dictionary-like operator, __getitem__:
x = FLAGS['longname'] # access the registered Flag object
The str() operator of a 'FlagValues' object provides help for all of
the registered 'Flag' objects.
"""
def __init__(self):
# Since everything in this class is so heavily overloaded, the only
# way of defining and using fields is to access __dict__ directly.
# Dictionary: flag name (string) -> Flag object.
self.__dict__['__flags'] = {}
# Dictionary: module name (string) -> list of Flag objects that are defined
# by that module.
self.__dict__['__flags_by_module'] = {}
# Dictionary: module id (int) -> list of Flag objects that are defined by
# that module.
self.__dict__['__flags_by_module_id'] = {}
# Dictionary: module name (string) -> list of Flag objects that are
# key for that module.
self.__dict__['__key_flags_by_module'] = {}
# Set if we should use new style gnu_getopt rather than getopt when parsing
# the args. Only possible with Python 2.3+
self.UseGnuGetOpt(False)
def UseGnuGetOpt(self, use_gnu_getopt=True):
"""Use GNU-style scanning. Allows mixing of flag and non-flag arguments.
See http://docs.python.org/library/getopt.html#getopt.gnu_getopt
Args:
use_gnu_getopt: wether or not to use GNU style scanning.
"""
self.__dict__['__use_gnu_getopt'] = use_gnu_getopt
def IsGnuGetOpt(self):
return self.__dict__['__use_gnu_getopt']
def FlagDict(self):
return self.__dict__['__flags']
def FlagsByModuleDict(self):
"""Returns the dictionary of module_name -> list of defined flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects.
"""
return self.__dict__['__flags_by_module']
def FlagsByModuleIdDict(self):
"""Returns the dictionary of module_id -> list of defined flags.
Returns:
A dictionary. Its keys are module IDs (ints). Its values
are lists of Flag objects.
"""
return self.__dict__['__flags_by_module_id']
def KeyFlagsByModuleDict(self):
"""Returns the dictionary of module_name -> list of key flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects.
"""
return self.__dict__['__key_flags_by_module']
def _RegisterFlagByModule(self, module_name, flag):
"""Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module.
"""
flags_by_module = self.FlagsByModuleDict()
flags_by_module.setdefault(module_name, []).append(flag)
def _RegisterFlagByModuleId(self, module_id, flag):
"""Records the module that defines a specific flag.
Args:
module_id: An int, the ID of the Python module.
flag: A Flag object, a flag that is key to the module.
"""
flags_by_module_id = self.FlagsByModuleIdDict()
flags_by_module_id.setdefault(module_id, []).append(flag)
def _RegisterKeyFlagForModule(self, module_name, flag):
"""Specifies that a flag is a key flag for a module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module.
"""
key_flags_by_module = self.KeyFlagsByModuleDict()
# The list of key flags for the module named module_name.
key_flags = key_flags_by_module.setdefault(module_name, [])
# Add flag, but avoid duplicates.
if flag not in key_flags:
key_flags.append(flag)
def _GetFlagsDefinedByModule(self, module):
"""Returns the list of flags defined by a module.
Args:
module: A module object or a module name (a string).
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object.
"""
if not isinstance(module, str):
module = module.__name__
return list(self.FlagsByModuleDict().get(module, []))
def _GetKeyFlagsForModule(self, module):
"""Returns the list of key flags for a module.
Args:
module: A module object or a module name (a string)
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object.
"""
if not isinstance(module, str):
module = module.__name__
# Any flag is a key flag for the module that defined it. NOTE:
# key_flags is a fresh list: we can update it without affecting the
# internals of this FlagValues object.
key_flags = self._GetFlagsDefinedByModule(module)
# Take into account flags explicitly declared as key for a module.
for flag in self.KeyFlagsByModuleDict().get(module, []):
if flag not in key_flags:
key_flags.append(flag)
return key_flags
def FindModuleDefiningFlag(self, flagname, default=None):
"""Return the name of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module which registered the flag with this name.
If no such module exists (i.e. no flag with this name exists),
we return default.
"""
for module, flags in self.FlagsByModuleDict().iteritems():
for flag in flags:
if flag.name == flagname or flag.short_name == flagname:
return module
return default
def FindModuleIdDefiningFlag(self, flagname, default=None):
"""Return the ID of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The ID of the module which registered the flag with this name.
If no such module exists (i.e. no flag with this name exists),
we return default.
"""
for module_id, flags in self.FlagsByModuleIdDict().iteritems():
for flag in flags:
if flag.name == flagname or flag.short_name == flagname:
return module_id
return default
def AppendFlagValues(self, flag_values):
"""Appends flags registered in another FlagValues instance.
Args:
flag_values: registry to copy from
"""
for flag_name, flag in flag_values.FlagDict().iteritems():
# Each flags with shortname appears here twice (once under its
# normal name, and again with its short name). To prevent
# problems (DuplicateFlagError) with double flag registration, we
# perform a check to make sure that the entry we're looking at is
# for its normal name.
if flag_name == flag.name:
try:
self[flag_name] = flag
except DuplicateFlagError:
raise DuplicateFlagError(flag_name, self,
other_flag_values=flag_values)
def RemoveFlagValues(self, flag_values):
"""Remove flags that were previously appended from another FlagValues.
Args:
flag_values: registry containing flags to remove.
"""
for flag_name in flag_values.FlagDict():
self.__delattr__(flag_name)
def __setitem__(self, name, flag):
"""Registers a new flag variable."""
fl = self.FlagDict()
if not isinstance(flag, Flag):
raise IllegalFlagValue(flag)
if not isinstance(name, type("")):
raise FlagsError("Flag name must be a string")
if len(name) == 0:
raise FlagsError("Flag name cannot be empty")
# If running under pychecker, duplicate keys are likely to be
# defined. Disable check for duplicate keys when pycheck'ing.
if (name in fl and not flag.allow_override and
not fl[name].allow_override and not _RUNNING_PYCHECKER):
module, module_name = _GetCallingModuleObjectAndName()
if (self.FindModuleDefiningFlag(name) == module_name and
id(module) != self.FindModuleIdDefiningFlag(name)):
# If the flag has already been defined by a module with the same name,
# but a different ID, we can stop here because it indicates that the
# module is simply being imported a subsequent time.
return
raise DuplicateFlagError(name, self)
short_name = flag.short_name
if short_name is not None:
if (short_name in fl and not flag.allow_override and
not fl[short_name].allow_override and not _RUNNING_PYCHECKER):
raise DuplicateFlagError(short_name, self)
fl[short_name] = flag
fl[name] = flag
global _exported_flags
_exported_flags[name] = flag
def __getitem__(self, name):
"""Retrieves the Flag object for the flag --name."""
return self.FlagDict()[name]
def __getattr__(self, name):
"""Retrieves the 'value' attribute of the flag --name."""
fl = self.FlagDict()
if name not in fl:
raise AttributeError(name)
return fl[name].value
def __setattr__(self, name, value):
"""Sets the 'value' attribute of the flag --name."""
fl = self.FlagDict()
fl[name].value = value
self._AssertValidators(fl[name].validators)
return value
def _AssertAllValidators(self):
all_validators = set()
for flag in self.FlagDict().itervalues():
for validator in flag.validators:
all_validators.add(validator)
self._AssertValidators(all_validators)
def _AssertValidators(self, validators):
"""Assert if all validators in the list are satisfied.
Asserts validators in the order they were created.
Args:
validators: Iterable(gflags_validators.Validator), validators to be
verified
Raises:
AttributeError: if validators work with a non-existing flag.
IllegalFlagValue: if validation fails for at least one validator
"""
for validator in sorted(
validators, key=lambda validator: validator.insertion_index):
try:
validator.Verify(self)
except gflags_validators.Error, e:
message = validator.PrintFlagsWithValues(self)
raise IllegalFlagValue('%s: %s' % (message, str(e)))
def _FlagIsRegistered(self, flag_obj):
"""Checks whether a Flag object is registered under some name.
Note: this is non trivial: in addition to its normal name, a flag
may have a short name too. In self.FlagDict(), both the normal and
the short name are mapped to the same flag object. E.g., calling
only "del FLAGS.short_name" is not unregistering the corresponding
Flag object (it is still registered under the longer name).
Args:
flag_obj: A Flag object.
Returns:
A boolean: True iff flag_obj is registered under some name.
"""
flag_dict = self.FlagDict()
# Check whether flag_obj is registered under its long name.
name = flag_obj.name
if flag_dict.get(name, None) == flag_obj:
return True
# Check whether flag_obj is registered under its short name.
short_name = flag_obj.short_name
if (short_name is not None and
flag_dict.get(short_name, None) == flag_obj):
return True
# The flag cannot be registered under any other name, so we do not
# need to do a full search through the values of self.FlagDict().
return False
def __delattr__(self, flag_name):
"""Deletes a previously-defined flag from a flag object.
This method makes sure we can delete a flag by using
del flag_values_object.<flag_name>
E.g.,
gflags.DEFINE_integer('foo', 1, 'Integer flag.')
del gflags.FLAGS.foo
Args:
flag_name: A string, the name of the flag to be deleted.
Raises:
AttributeError: When there is no registered flag named flag_name.
"""
fl = self.FlagDict()
if flag_name not in fl:
raise AttributeError(flag_name)
flag_obj = fl[flag_name]
del fl[flag_name]
if not self._FlagIsRegistered(flag_obj):
# If the Flag object indicated by flag_name is no longer
# registered (please see the docstring of _FlagIsRegistered), then
# we delete the occurrences of the flag object in all our internal
# dictionaries.
self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj)
self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj)
self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj)
def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj):
"""Removes a flag object from a module -> list of flags dictionary.
Args:
flags_by_module_dict: A dictionary that maps module names to lists of
flags.
flag_obj: A flag object.
"""
for unused_module, flags_in_module in flags_by_module_dict.iteritems():
# while (as opposed to if) takes care of multiple occurrences of a
# flag in the list for the same module.
while flag_obj in flags_in_module:
flags_in_module.remove(flag_obj)
def SetDefault(self, name, value):
"""Changes the default value of the named flag object."""
fl = self.FlagDict()
if name not in fl:
raise AttributeError(name)
fl[name].SetDefault(value)
self._AssertValidators(fl[name].validators)
def __contains__(self, name):
"""Returns True if name is a value (flag) in the dict."""
return name in self.FlagDict()
has_key = __contains__ # a synonym for __contains__()
def __iter__(self):
return iter(self.FlagDict())
def __call__(self, argv):
"""Parses flags from argv; stores parsed flags into this FlagValues object.
All unparsed arguments are returned. Flags are parsed using the GNU
Program Argument Syntax Conventions, using getopt:
http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt
Args:
argv: argument list. Can be of any type that may be converted to a list.
Returns:
The list of arguments not parsed as options, including argv[0]
Raises:
FlagsError: on any parsing error
"""
# Support any sequence type that can be converted to a list
argv = list(argv)
shortopts = ""
longopts = []
fl = self.FlagDict()
# This pre parses the argv list for --flagfile=<> options.
argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False)
# Correct the argv to support the google style of passing boolean
# parameters. Boolean parameters may be passed by using --mybool,
# --nomybool, --mybool=(true|false|1|0). getopt does not support
# having options that may or may not have a parameter. We replace
# instances of the short form --mybool and --nomybool with their
# full forms: --mybool=(true|false).
original_argv = list(argv) # list() makes a copy
shortest_matches = None
for name, flag in fl.items():
if not flag.boolean:
continue
if shortest_matches is None:
# Determine the smallest allowable prefix for all flag names
shortest_matches = self.ShortestUniquePrefixes(fl)
no_name = 'no' + name
prefix = shortest_matches[name]
no_prefix = shortest_matches[no_name]
# Replace all occurrences of this boolean with extended forms
for arg_idx in range(1, len(argv)):
arg = argv[arg_idx]
if arg.find('=') >= 0: continue
if arg.startswith('--'+prefix) and ('--'+name).startswith(arg):
argv[arg_idx] = ('--%s=true' % name)
elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg):
argv[arg_idx] = ('--%s=false' % name)
# Loop over all of the flags, building up the lists of short options
# and long options that will be passed to getopt. Short options are
# specified as a string of letters, each letter followed by a colon
# if it takes an argument. Long options are stored in an array of
# strings. Each string ends with an '=' if it takes an argument.
for name, flag in fl.items():
longopts.append(name + "=")
if len(name) == 1: # one-letter option: allow short flag type also
shortopts += name
if not flag.boolean:
shortopts += ":"
longopts.append('undefok=')
undefok_flags = []
# In case --undefok is specified, loop to pick up unrecognized
# options one by one.
unrecognized_opts = []
args = argv[1:]
while True:
try:
if self.__dict__['__use_gnu_getopt']:
optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts)
else:
optlist, unparsed_args = getopt.getopt(args, shortopts, longopts)
break
except getopt.GetoptError, e:
if not e.opt or e.opt in fl:
# Not an unrecognized option, re-raise the exception as a FlagsError
raise FlagsError(e)
# Remove offender from args and try again
for arg_index in range(len(args)):
if ((args[arg_index] == '--' + e.opt) or
(args[arg_index] == '-' + e.opt) or
(args[arg_index].startswith('--' + e.opt + '='))):
unrecognized_opts.append((e.opt, args[arg_index]))
args = args[0:arg_index] + args[arg_index+1:]
break
else:
# We should have found the option, so we don't expect to get
# here. We could assert, but raising the original exception
# might work better.
raise FlagsError(e)
for name, arg in optlist:
if name == '--undefok':
flag_names = arg.split(',')
undefok_flags.extend(flag_names)
# For boolean flags, if --undefok=boolflag is specified, then we should
# also accept --noboolflag, in addition to --boolflag.
# Since we don't know the type of the undefok'd flag, this will affect
# non-boolean flags as well.
# NOTE: You shouldn't use --undefok=noboolflag, because then we will
# accept --nonoboolflag here. We are choosing not to do the conversion
# from noboolflag -> boolflag because of the ambiguity that flag names
# can start with 'no'.
undefok_flags.extend('no' + name for name in flag_names)
continue
if name.startswith('--'):
# long option
name = name[2:]
short_option = 0
else:
# short option
name = name[1:]
short_option = 1
if name in fl:
flag = fl[name]
if flag.boolean and short_option: arg = 1
flag.Parse(arg)
# If there were unrecognized options, raise an exception unless
# the options were named via --undefok.
for opt, value in unrecognized_opts:
if opt not in undefok_flags:
raise UnrecognizedFlagError(opt, value)
if unparsed_args:
if self.__dict__['__use_gnu_getopt']:
# if using gnu_getopt just return the program name + remainder of argv.
ret_val = argv[:1] + unparsed_args
else:
# unparsed_args becomes the first non-flag detected by getopt to
# the end of argv. Because argv may have been modified above,
# return original_argv for this region.
ret_val = argv[:1] + original_argv[-len(unparsed_args):]
else:
ret_val = argv[:1]
self._AssertAllValidators()
return ret_val
def Reset(self):
"""Resets the values to the point before FLAGS(argv) was called."""
for f in self.FlagDict().values():
f.Unparse()
def RegisteredFlags(self):
"""Returns: a list of the names and short names of all registered flags."""
return list(self.FlagDict())
def FlagValuesDict(self):
"""Returns: a dictionary that maps flag names to flag values."""
flag_values = {}
for flag_name in self.RegisteredFlags():
flag = self.FlagDict()[flag_name]
flag_values[flag_name] = flag.value
return flag_values
def __str__(self):
"""Generates a help string for all known flags."""
return self.GetHelp()
def GetHelp(self, prefix=''):
"""Generates a help string for all known flags."""
helplist = []
flags_by_module = self.FlagsByModuleDict()
if flags_by_module:
modules = sorted(flags_by_module)
# Print the help for the main module first, if possible.
main_module = _GetMainModule()
if main_module in modules:
modules.remove(main_module)
modules = [main_module] + modules
for module in modules:
self.__RenderOurModuleFlags(module, helplist)
self.__RenderModuleFlags('gflags',
_SPECIAL_FLAGS.FlagDict().values(),
helplist)
else:
# Just print one long list of flags.
self.__RenderFlagList(
self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(),
helplist, prefix)
return '\n'.join(helplist)
def __RenderModuleFlags(self, module, flags, output_lines, prefix=""):
"""Generates a help string for a given module."""
if not isinstance(module, str):
module = module.__name__
output_lines.append('\n%s%s:' % (prefix, module))
self.__RenderFlagList(flags, output_lines, prefix + " ")
def __RenderOurModuleFlags(self, module, output_lines, prefix=""):
"""Generates a help string for a given module."""
flags = self._GetFlagsDefinedByModule(module)
if flags:
self.__RenderModuleFlags(module, flags, output_lines, prefix)
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""):
"""Generates a help string for the key flags of a given module.
Args:
module: A module object or a module name (a string).
output_lines: A list of strings. The generated help message
lines will be appended to this list.
prefix: A string that is prepended to each generated help line.
"""
key_flags = self._GetKeyFlagsForModule(module)
if key_flags:
self.__RenderModuleFlags(module, key_flags, output_lines, prefix)
def ModuleHelp(self, module):
"""Describe the key flags of a module.
Args:
module: A module object or a module name (a string).
Returns:
string describing the key flags of a module.
"""
helplist = []
self.__RenderOurModuleKeyFlags(module, helplist)
return '\n'.join(helplist)
def MainModuleHelp(self):
"""Describe the key flags of the main module.
Returns:
string describing the key flags of a module.
"""
return self.ModuleHelp(_GetMainModule())
def __RenderFlagList(self, flaglist, output_lines, prefix=" "):
fl = self.FlagDict()
special_fl = _SPECIAL_FLAGS.FlagDict()
flaglist = [(flag.name, flag) for flag in flaglist]
flaglist.sort()
flagset = {}
for (name, flag) in flaglist:
# It's possible this flag got deleted or overridden since being
# registered in the per-module flaglist. Check now against the
# canonical source of current flag information, the FlagDict.
if fl.get(name, None) != flag and special_fl.get(name, None) != flag:
# a different flag is using this name now
continue
# only print help once
if flag in flagset: continue
flagset[flag] = 1
flaghelp = ""
if flag.short_name: flaghelp += "-%s," % flag.short_name
if flag.boolean:
flaghelp += "--[no]%s" % flag.name + ":"
else:
flaghelp += "--%s" % flag.name + ":"
flaghelp += " "
if flag.help:
flaghelp += flag.help
flaghelp = TextWrap(flaghelp, indent=prefix+" ",
firstline_indent=prefix)
if flag.default_as_str:
flaghelp += "\n"
flaghelp += TextWrap("(default: %s)" % flag.default_as_str,
indent=prefix+" ")
if flag.parser.syntactic_help:
flaghelp += "\n"
flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help,
indent=prefix+" ")
output_lines.append(flaghelp)
def get(self, name, default):
"""Returns the value of a flag (if not None) or a default value.
Args:
name: A string, the name of a flag.
default: Default value to use if the flag value is None.
"""
value = self.__getattr__(name)
if value is not None: # Can't do if not value, b/c value might be '0' or ""
return value
else:
return default
def ShortestUniquePrefixes(self, fl):
"""Returns: dictionary; maps flag names to their shortest unique prefix."""
# Sort the list of flag names
sorted_flags = []
for name, flag in fl.items():
sorted_flags.append(name)
if flag.boolean:
sorted_flags.append('no%s' % name)
sorted_flags.sort()
# For each name in the sorted list, determine the shortest unique
# prefix by comparing itself to the next name and to the previous
# name (the latter check uses cached info from the previous loop).
shortest_matches = {}
prev_idx = 0
for flag_idx in range(len(sorted_flags)):
curr = sorted_flags[flag_idx]
if flag_idx == (len(sorted_flags) - 1):
next = None
else:
next = sorted_flags[flag_idx+1]
next_len = len(next)
for curr_idx in range(len(curr)):
if (next is None
or curr_idx >= next_len
or curr[curr_idx] != next[curr_idx]):
# curr longer than next or no more chars in common
shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1]
prev_idx = curr_idx
break
else:
# curr shorter than (or equal to) next
shortest_matches[curr] = curr
prev_idx = curr_idx + 1 # next will need at least one more char
return shortest_matches
def __IsFlagFileDirective(self, flag_string):
"""Checks whether flag_string contain a --flagfile=<foo> directive."""
if isinstance(flag_string, type("")):
if flag_string.startswith('--flagfile='):
return 1
elif flag_string == '--flagfile':
return 1
elif flag_string.startswith('-flagfile='):
return 1
elif flag_string == '-flagfile':
return 1
else:
return 0
return 0
def ExtractFilename(self, flagfile_str):
"""Returns filename from a flagfile_str of form -[-]flagfile=filename.
The cases of --flagfile foo and -flagfile foo shouldn't be hitting
this function, as they are dealt with in the level above this
function.
"""
if flagfile_str.startswith('--flagfile='):
return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip())
elif flagfile_str.startswith('-flagfile='):
return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip())
else:
raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str)
def __GetFlagFileLines(self, filename, parsed_file_list):
"""Returns the useful (!=comments, etc) lines from a file with flags.
Args:
filename: A string, the name of the flag file.
parsed_file_list: A list of the names of the files we have
already read. MUTATED BY THIS FUNCTION.
Returns:
List of strings. See the note below.
NOTE(springer): This function checks for a nested --flagfile=<foo>
tag and handles the lower file recursively. It returns a list of
all the lines that _could_ contain command flags. This is
EVERYTHING except whitespace lines and comments (lines starting
with '#' or '//').
"""
line_list = [] # All line from flagfile.
flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags.
try:
file_obj = open(filename, 'r')
except IOError, e_msg:
raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg)
line_list = file_obj.readlines()
file_obj.close()
parsed_file_list.append(filename)
# This is where we check each line in the file we just read.
for line in line_list:
if line.isspace():
pass
# Checks for comment (a line that starts with '#').
elif line.startswith('#') or line.startswith('//'):
pass
# Checks for a nested "--flagfile=<bar>" flag in the current file.
# If we find one, recursively parse down into that file.
elif self.__IsFlagFileDirective(line):
sub_filename = self.ExtractFilename(line)
# We do a little safety check for reparsing a file we've already done.
if not sub_filename in parsed_file_list:
included_flags = self.__GetFlagFileLines(sub_filename,
parsed_file_list)
flag_line_list.extend(included_flags)
else: # Case of hitting a circularly included file.
sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' %
(sub_filename,))
else:
# Any line that's not a comment or a nested flagfile should get
# copied into 2nd position. This leaves earlier arguments
# further back in the list, thus giving them higher priority.
flag_line_list.append(line.strip())
return flag_line_list
def ReadFlagsFromFiles(self, argv, force_gnu=True):
"""Processes command line args, but also allow args to be read from file.
Args:
argv: A list of strings, usually sys.argv[1:], which may contain one or
more flagfile directives of the form --flagfile="./filename".
Note that the name of the program (sys.argv[0]) should be omitted.
force_gnu: If False, --flagfile parsing obeys normal flag semantics.
If True, --flagfile parsing instead follows gnu_getopt semantics.
*** WARNING *** force_gnu=False may become the future default!
Returns:
A new list which has the original list combined with what we read
from any flagfile(s).
References: Global gflags.FLAG class instance.
This function should be called before the normal FLAGS(argv) call.
This function scans the input list for a flag that looks like:
--flagfile=<somefile>. Then it opens <somefile>, reads all valid key
and value pairs and inserts them into the input list between the
first item of the list and any subsequent items in the list.
Note that your application's flags are still defined the usual way
using gflags DEFINE_flag() type functions.
Notes (assuming we're getting a commandline of some sort as our input):
--> Flags from the command line argv _should_ always take precedence!
--> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile.
It will be processed after the parent flag file is done.
--> For duplicate flags, first one we hit should "win".
--> In a flagfile, a line beginning with # or // is a comment.
--> Entirely blank lines _should_ be ignored.
"""
parsed_file_list = []
rest_of_args = argv
new_argv = []
while rest_of_args:
current_arg = rest_of_args[0]
rest_of_args = rest_of_args[1:]
if self.__IsFlagFileDirective(current_arg):
# This handles the case of -(-)flagfile foo. In this case the
# next arg really is part of this one.
if current_arg == '--flagfile' or current_arg == '-flagfile':
if not rest_of_args:
raise IllegalFlagValue('--flagfile with no argument')
flag_filename = os.path.expanduser(rest_of_args[0])
rest_of_args = rest_of_args[1:]
else:
# This handles the case of (-)-flagfile=foo.
flag_filename = self.ExtractFilename(current_arg)
new_argv.extend(
self.__GetFlagFileLines(flag_filename, parsed_file_list))
else:
new_argv.append(current_arg)
# Stop parsing after '--', like getopt and gnu_getopt.
if current_arg == '--':
break
# Stop parsing after a non-flag, like getopt.
if not current_arg.startswith('-'):
if not force_gnu and not self.__dict__['__use_gnu_getopt']:
break
if rest_of_args:
new_argv.extend(rest_of_args)
return new_argv
def FlagsIntoString(self):
"""Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag
assignment is separated by a newline.
NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString
from http://code.google.com/p/google-gflags
"""
s = ''
for flag in self.FlagDict().values():
if flag.value is not None:
s += flag.Serialize() + '\n'
return s
def AppendFlagsIntoFile(self, filename):
"""Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
"""
out_file = open(filename, 'a')
out_file.write(self.FlagsIntoString())
out_file.close()
def WriteHelpInXMLFormat(self, outfile=None):
"""Outputs flag documentation in XML format.
NOTE: We use element names that are consistent with those used by
the C++ command-line flag library, from
http://code.google.com/p/google-gflags
We also use a few new elements (e.g., <key>), but we do not
interfere / overlap with existing XML elements used by the C++
library. Please maintain this consistency.
Args:
outfile: File object we write to. Default None means sys.stdout.
"""
outfile = outfile or sys.stdout
outfile.write('<?xml version=\"1.0\"?>\n')
outfile.write('<AllFlags>\n')
indent = ' '
_WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]),
indent)
usage_doc = sys.modules['__main__'].__doc__
if not usage_doc:
usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0]
else:
usage_doc = usage_doc.replace('%s', sys.argv[0])
_WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent)
# Get list of key flags for the main module.
key_flags = self._GetKeyFlagsForModule(_GetMainModule())
# Sort flags by declaring module name and next by flag name.
flags_by_module = self.FlagsByModuleDict()
all_module_names = list(flags_by_module.keys())
all_module_names.sort()
for module_name in all_module_names:
flag_list = [(f.name, f) for f in flags_by_module[module_name]]
flag_list.sort()
for unused_flag_name, flag in flag_list:
is_key = flag in key_flags
flag.WriteInfoInXMLFormat(outfile, module_name,
is_key=is_key, indent=indent)
outfile.write('</AllFlags>\n')
outfile.flush()
def AddValidator(self, validator):
"""Register new flags validator to be checked.
Args:
validator: gflags_validators.Validator
Raises:
AttributeError: if validators work with a non-existing flag.
"""
for flag_name in validator.GetFlagsNames():
flag = self.FlagDict()[flag_name]
flag.validators.append(validator)
# end of FlagValues definition
# The global FlagValues instance
FLAGS = FlagValues()
def _StrOrUnicode(value):
"""Converts value to a python string or, if necessary, unicode-string."""
try:
return str(value)
except UnicodeEncodeError:
return unicode(value)
def _MakeXMLSafe(s):
"""Escapes <, >, and & from s, and removes XML 1.0-illegal chars."""
s = cgi.escape(s) # Escape <, >, and &
# Remove characters that cannot appear in an XML 1.0 document
# (http://www.w3.org/TR/REC-xml/#charsets).
#
# NOTE: if there are problems with current solution, one may move to
# XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;).
s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s)
# Convert non-ascii characters to entities. Note: requires python >=2.3
s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'uΈ'
return s
def _WriteSimpleXMLElement(outfile, name, value, indent):
"""Writes a simple XML element.
Args:
outfile: File object we write the XML element to.
name: A string, the name of XML element.
value: A Python object, whose string representation will be used
as the value of the XML element.
indent: A string, prepended to each line of generated output.
"""
value_str = _StrOrUnicode(value)
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
value_str = value_str.lower()
safe_value_str = _MakeXMLSafe(value_str)
outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name))
class Flag:
"""Information about a command-line flag.
'Flag' objects define the following fields:
.name - the name for this flag
.default - the default value for this flag
.default_as_str - default value as repr'd string, e.g., "'true'" (or None)
.value - the most recent parsed value of this flag; set by Parse()
.help - a help string or None if no help is available
.short_name - the single letter alias for this flag (or None)
.boolean - if 'true', this flag does not accept arguments
.present - true if this flag was parsed from command line flags.
.parser - an ArgumentParser object
.serializer - an ArgumentSerializer object
.allow_override - the flag may be redefined without raising an error
The only public method of a 'Flag' object is Parse(), but it is
typically only called by a 'FlagValues' object. The Parse() method is
a thin wrapper around the 'ArgumentParser' Parse() method. The parsed
value is saved in .value, and the .present attribute is updated. If
this flag was already present, a FlagsError is raised.
Parse() is also called during __init__ to parse the default value and
initialize the .value attribute. This enables other python modules to
safely use flags even if the __main__ module neglects to parse the
command line arguments. The .present attribute is cleared after
__init__ parsing. If the default value is set to None, then the
__init__ parsing step is skipped and the .value attribute is
initialized to None.
Note: The default value is also presented to the user in the help
string, so it is important that it be a legal value for this flag.
"""
def __init__(self, parser, serializer, name, default, help_string,
short_name=None, boolean=0, allow_override=0):
self.name = name
if not help_string:
help_string = '(no help available)'
self.help = help_string
self.short_name = short_name
self.boolean = boolean
self.present = 0
self.parser = parser
self.serializer = serializer
self.allow_override = allow_override
self.value = None
self.validators = []
self.SetDefault(default)
def __hash__(self):
return hash(id(self))
def __eq__(self, other):
return self is other
def __lt__(self, other):
if isinstance(other, Flag):
return id(self) < id(other)
return NotImplemented
def __GetParsedValueAsString(self, value):
if value is None:
return None
if self.serializer:
return repr(self.serializer.Serialize(value))
if self.boolean:
if value:
return repr('true')
else:
return repr('false')
return repr(_StrOrUnicode(value))
def Parse(self, argument):
try:
self.value = self.parser.Parse(argument)
except ValueError, e: # recast ValueError as IllegalFlagValue
raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e))
self.present += 1
def Unparse(self):
if self.default is None:
self.value = None
else:
self.Parse(self.default)
self.present = 0
def Serialize(self):
if self.value is None:
return ''
if self.boolean:
if self.value:
return "--%s" % self.name
else:
return "--no%s" % self.name
else:
if not self.serializer:
raise FlagsError("Serializer not present for flag %s" % self.name)
return "--%s=%s" % (self.name, self.serializer.Serialize(self.value))
def SetDefault(self, value):
"""Changes the default value (and current value too) for this Flag."""
# We can't allow a None override because it may end up not being
# passed to C++ code when we're overriding C++ flags. So we
# cowardly bail out until someone fixes the semantics of trying to
# pass None to a C++ flag. See swig_flags.Init() for details on
# this behavior.
# TODO(olexiy): Users can directly call this method, bypassing all flags
# validators (we don't have FlagValues here, so we can not check
# validators).
# The simplest solution I see is to make this method private.
# Another approach would be to store reference to the corresponding
# FlagValues with each flag, but this seems to be an overkill.
if value is None and self.allow_override:
raise DuplicateFlagCannotPropagateNoneToSwig(self.name)
self.default = value
self.Unparse()
self.default_as_str = self.__GetParsedValueAsString(self.value)
def Type(self):
"""Returns: a string that describes the type of this Flag."""
# NOTE: we use strings, and not the types.*Type constants because
# our flags can have more exotic types, e.g., 'comma separated list
# of strings', 'whitespace separated list of strings', etc.
return self.parser.Type()
def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''):
"""Writes common info about this flag, in XML format.
This is information that is relevant to all flags (e.g., name,
meaning, etc.). If you defined a flag that has some other pieces of
info, then please override _WriteCustomInfoInXMLFormat.
Please do NOT override this method.
Args:
outfile: File object we write to.
module_name: A string, the name of the module that defines this flag.
is_key: A boolean, True iff this flag is key for main module.
indent: A string that is prepended to each generated line.
"""
outfile.write(indent + '<flag>\n')
inner_indent = indent + ' '
if is_key:
_WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent)
_WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent)
# Print flag features that are relevant for all flags.
_WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent)
if self.short_name:
_WriteSimpleXMLElement(outfile, 'short_name', self.short_name,
inner_indent)
if self.help:
_WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent)
# The default flag value can either be represented as a string like on the
# command line, or as a Python object. We serialize this value in the
# latter case in order to remain consistent.
if self.serializer and not isinstance(self.default, str):
default_serialized = self.serializer.Serialize(self.default)
else:
default_serialized = self.default
_WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent)
_WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent)
_WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent)
# Print extra flag features this flag may have.
self._WriteCustomInfoInXMLFormat(outfile, inner_indent)
outfile.write(indent + '</flag>\n')
def _WriteCustomInfoInXMLFormat(self, outfile, indent):
"""Writes extra info about this flag, in XML format.
"Extra" means "not already printed by WriteInfoInXMLFormat above."
Args:
outfile: File object we write to.
indent: A string that is prepended to each generated line.
"""
# Usually, the parser knows the extra details about the flag, so
# we just forward the call to it.
self.parser.WriteCustomInfoInXMLFormat(outfile, indent)
# End of Flag definition
class _ArgumentParserCache(type):
"""Metaclass used to cache and share argument parsers among flags."""
_instances = {}
def __call__(mcs, *args, **kwargs):
"""Returns an instance of the argument parser cls.
This method overrides behavior of the __new__ methods in
all subclasses of ArgumentParser (inclusive). If an instance
for mcs with the same set of arguments exists, this instance is
returned, otherwise a new instance is created.
If any keyword arguments are defined, or the values in args
are not hashable, this method always returns a new instance of
cls.
Args:
args: Positional initializer arguments.
kwargs: Initializer keyword arguments.
Returns:
An instance of cls, shared or new.
"""
if kwargs:
return type.__call__(mcs, *args, **kwargs)
else:
instances = mcs._instances
key = (mcs,) + tuple(args)
try:
return instances[key]
except KeyError:
# No cache entry for key exists, create a new one.
return instances.setdefault(key, type.__call__(mcs, *args))
except TypeError:
# An object in args cannot be hashed, always return
# a new instance.
return type.__call__(mcs, *args)
class ArgumentParser(object):
"""Base class used to parse and convert arguments.
The Parse() method checks to make sure that the string argument is a
legal value and convert it to a native type. If the value cannot be
converted, it should throw a 'ValueError' exception with a human
readable explanation of why the value is illegal.
Subclasses should also define a syntactic_help string which may be
presented to the user to describe the form of the legal values.
Argument parser classes must be stateless, since instances are cached
and shared between flags. Initializer arguments are allowed, but all
member variables must be derived from initializer arguments only.
"""
__metaclass__ = _ArgumentParserCache
syntactic_help = ""
def Parse(self, argument):
"""Default implementation: always returns its argument unmodified."""
return argument
def Type(self):
return 'string'
def WriteCustomInfoInXMLFormat(self, outfile, indent):
pass
class ArgumentSerializer:
"""Base class for generating string representations of a flag value."""
def Serialize(self, value):
return _StrOrUnicode(value)
class ListSerializer(ArgumentSerializer):
def __init__(self, list_sep):
self.list_sep = list_sep
def Serialize(self, value):
return self.list_sep.join([_StrOrUnicode(x) for x in value])
# Flags validators
def RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS):
"""Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: string, name of the flag to be checked.
checker: method to validate the flag.
input - value of the corresponding flag (string, boolean, etc.
This value will be passed to checker by the library). See file's
docstring for examples.
output - Boolean.
Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise gflags_validators.Error(desired_error_message).
message: error text to be shown to the user if checker returns False.
If checker raises gflags_validators.Error, message from the raised
Error will be shown.
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name.
"""
flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name,
checker,
message))
def MarkFlagAsRequired(flag_name, flag_values=FLAGS):
"""Ensure that flag is not None during program execution.
Registers a flag validator, which will follow usual validator
rules.
Args:
flag_name: string, name of the flag
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name.
"""
RegisterValidator(flag_name,
lambda value: value is not None,
message='Flag --%s must be specified.' % flag_name,
flag_values=flag_values)
def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values):
"""Enforce lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser). Provides lower
and upper bounds, and help text to display.
name: string, name of the flag
flag_values: FlagValues
"""
if parser.lower_bound is not None or parser.upper_bound is not None:
def Checker(value):
if value is not None and parser.IsOutsideBounds(value):
message = '%s is not %s' % (value, parser.syntactic_help)
raise gflags_validators.Error(message)
return True
RegisterValidator(name,
Checker,
flag_values=flag_values)
# The DEFINE functions are explained in mode details in the module doc string.
def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None,
**args):
"""Registers a generic Flag object.
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
Auxiliary function: clients should use the specialized DEFINE_<type>
function instead.
Args:
parser: ArgumentParser that is used to parse the flag arguments.
name: A string, the flag name.
default: The default value of the flag.
help: A help string.
flag_values: FlagValues object the flag will be registered with.
serializer: ArgumentSerializer that serializes the flag value.
args: Dictionary with extra keyword args that are passes to the
Flag __init__.
"""
DEFINE_flag(Flag(parser, serializer, name, default, help, **args),
flag_values)
def DEFINE_flag(flag, flag_values=FLAGS):
"""Registers a 'Flag' object with a 'FlagValues' object.
By default, the global FLAGS 'FlagValue' object is used.
Typical users will use one of the more specialized DEFINE_xxx
functions, such as DEFINE_string or DEFINE_integer. But developers
who need to create Flag objects themselves should use this function
to register their flags.
"""
# copying the reference to flag_values prevents pychecker warnings
fv = flag_values
fv[flag.name] = flag
# Tell flag_values who's defining the flag.
if isinstance(flag_values, FlagValues):
# Regarding the above isinstance test: some users pass funny
# values of flag_values (e.g., {}) in order to avoid the flag
# registration (in the past, there used to be a flag_values ==
# FLAGS test here) and redefine flags with the same name (e.g.,
# debug). To avoid breaking their code, we perform the
# registration only if flag_values is a real FlagValues object.
module, module_name = _GetCallingModuleObjectAndName()
flag_values._RegisterFlagByModule(module_name, flag)
flag_values._RegisterFlagByModuleId(id(module), flag)
def _InternalDeclareKeyFlags(flag_names,
flag_values=FLAGS, key_flag_values=None):
"""Declares a flag as key for the calling module.
Internal function. User code should call DECLARE_key_flag or
ADOPT_module_key_flags instead.
Args:
flag_names: A list of strings that are names of already-registered
Flag objects.
flag_values: A FlagValues object that the flags listed in
flag_names have registered with (the value of the flag_values
argument from the DEFINE_* calls that defined those flags).
This should almost never need to be overridden.
key_flag_values: A FlagValues object that (among possibly many
other things) keeps track of the key flags for each module.
Default None means "same as flag_values". This should almost
never need to be overridden.
Raises:
UnrecognizedFlagError: when we refer to a flag that was not
defined yet.
"""
key_flag_values = key_flag_values or flag_values
module = _GetCallingModule()
for flag_name in flag_names:
if flag_name not in flag_values:
raise UnrecognizedFlagError(flag_name)
flag = flag_values.FlagDict()[flag_name]
key_flag_values._RegisterKeyFlagForModule(module, flag)
def DECLARE_key_flag(flag_name, flag_values=FLAGS):
"""Declares one flag as key to the current module.
Key flags are flags that are deemed really important for a module.
They are important when listing help messages; e.g., if the
--helpshort command-line flag is used, then only the key flags of the
main module are listed (instead of all flags, as in the case of
--help).
Sample usage:
gflags.DECLARED_key_flag('flag_1')
Args:
flag_name: A string, the name of an already declared flag.
(Redeclaring flags as key, including flags implicitly key
because they were declared in this module, is a no-op.)
flag_values: A FlagValues object. This should almost never
need to be overridden.
"""
if flag_name in _SPECIAL_FLAGS:
# Take care of the special flags, e.g., --flagfile, --undefok.
# These flags are defined in _SPECIAL_FLAGS, and are treated
# specially during flag parsing, taking precedence over the
# user-defined flags.
_InternalDeclareKeyFlags([flag_name],
flag_values=_SPECIAL_FLAGS,
key_flag_values=flag_values)
return
_InternalDeclareKeyFlags([flag_name], flag_values=flag_values)
def ADOPT_module_key_flags(module, flag_values=FLAGS):
"""Declares that all flags key to a module are key to the current module.
Args:
module: A module object.
flag_values: A FlagValues object. This should almost never need
to be overridden.
Raises:
FlagsError: When given an argument that is a module name (a
string), instead of a module object.
"""
# NOTE(salcianu): an even better test would be if not
# isinstance(module, types.ModuleType) but I didn't want to import
# types for such a tiny use.
if isinstance(module, str):
raise FlagsError('Received module name %s; expected a module object.'
% module)
_InternalDeclareKeyFlags(
[f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)],
flag_values=flag_values)
# If module is this flag module, take _SPECIAL_FLAGS into account.
if module == _GetThisModuleObjectAndName()[0]:
_InternalDeclareKeyFlags(
# As we associate flags with _GetCallingModuleObjectAndName(), the
# special flags defined in this module are incorrectly registered with
# a different module. So, we can't use _GetKeyFlagsForModule.
# Instead, we take all flags from _SPECIAL_FLAGS (a private
# FlagValues, where no other module should register flags).
[f.name for f in _SPECIAL_FLAGS.FlagDict().values()],
flag_values=_SPECIAL_FLAGS,
key_flag_values=flag_values)
#
# STRING FLAGS
#
def DEFINE_string(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value can be any string."""
parser = ArgumentParser()
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
#
# BOOLEAN FLAGS
#
class BooleanParser(ArgumentParser):
"""Parser of boolean values."""
def Convert(self, argument):
"""Converts the argument to a boolean; raise ValueError on errors."""
if type(argument) == str:
if argument.lower() in ['true', 't', '1']:
return True
elif argument.lower() in ['false', 'f', '0']:
return False
bool_argument = bool(argument)
if argument == bool_argument:
# The argument is a valid boolean (True, False, 0, or 1), and not just
# something that always converts to bool (list, string, int, etc.).
return bool_argument
raise ValueError('Non-boolean argument to boolean flag', argument)
def Parse(self, argument):
val = self.Convert(argument)
return val
def Type(self):
return 'bool'
class BooleanFlag(Flag):
"""Basic boolean flag.
Boolean flags do not take any arguments, and their value is either
True (1) or False (0). The false value is specified on the command
line by prepending the word 'no' to either the long or the short flag
name.
For example, if a Boolean flag was created whose long name was
'update' and whose short name was 'x', then this flag could be
explicitly unset through either --noupdate or --nox.
"""
def __init__(self, name, default, help, short_name=None, **args):
p = BooleanParser()
Flag.__init__(self, p, None, name, default, help, short_name, 1, **args)
if not self.help: self.help = "a boolean value"
def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args):
"""Registers a boolean flag.
Such a boolean flag does not take an argument. If a user wants to
specify a false value explicitly, the long option beginning with 'no'
must be used: i.e. --noflag
This flag will have a value of None, True or False. None is possible
if default=None and the user does not specify the flag on the command
line.
"""
DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values)
# Match C++ API to unconfuse C++ people.
DEFINE_bool = DEFINE_boolean
class HelpFlag(BooleanFlag):
"""
HelpFlag is a special boolean flag that prints usage information and
raises a SystemExit exception if it is ever found in the command
line arguments. Note this is called with allow_override=1, so other
apps can define their own --help flag, replacing this one, if they want.
"""
def __init__(self):
BooleanFlag.__init__(self, "help", 0, "show this help",
short_name="?", allow_override=1)
def Parse(self, arg):
if arg:
doc = sys.modules["__main__"].__doc__
flags = str(FLAGS)
print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])
if flags:
print "flags:"
print flags
sys.exit(1)
class HelpXMLFlag(BooleanFlag):
"""Similar to HelpFlag, but generates output in XML format."""
def __init__(self):
BooleanFlag.__init__(self, 'helpxml', False,
'like --help, but generates XML output',
allow_override=1)
def Parse(self, arg):
if arg:
FLAGS.WriteHelpInXMLFormat(sys.stdout)
sys.exit(1)
class HelpshortFlag(BooleanFlag):
"""
HelpshortFlag is a special boolean flag that prints usage
information for the "main" module, and rasies a SystemExit exception
if it is ever found in the command line arguments. Note this is
called with allow_override=1, so other apps can define their own
--helpshort flag, replacing this one, if they want.
"""
def __init__(self):
BooleanFlag.__init__(self, "helpshort", 0,
"show usage only for this module", allow_override=1)
def Parse(self, arg):
if arg:
doc = sys.modules["__main__"].__doc__
flags = FLAGS.MainModuleHelp()
print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])
if flags:
print "flags:"
print flags
sys.exit(1)
#
# Numeric parser - base class for Integer and Float parsers
#
class NumericParser(ArgumentParser):
"""Parser of numeric values.
Parsed value may be bounded to a given upper and lower bound.
"""
def IsOutsideBounds(self, val):
return ((self.lower_bound is not None and val < self.lower_bound) or
(self.upper_bound is not None and val > self.upper_bound))
def Parse(self, argument):
val = self.Convert(argument)
if self.IsOutsideBounds(val):
raise ValueError("%s is not %s" % (val, self.syntactic_help))
return val
def WriteCustomInfoInXMLFormat(self, outfile, indent):
if self.lower_bound is not None:
_WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent)
if self.upper_bound is not None:
_WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent)
def Convert(self, argument):
"""Default implementation: always returns its argument unmodified."""
return argument
# End of Numeric Parser
#
# FLOAT FLAGS
#
class FloatParser(NumericParser):
"""Parser of floating point values.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = "a"
number_name = "number"
syntactic_help = " ".join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(FloatParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound))
elif lower_bound == 0:
sh = "a non-negative %s" % self.number_name
elif upper_bound == 0:
sh = "a non-positive %s" % self.number_name
elif upper_bound is not None:
sh = "%s <= %s" % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = "%s >= %s" % (self.number_name, lower_bound)
self.syntactic_help = sh
def Convert(self, argument):
"""Converts argument to a float; raises ValueError on errors."""
return float(argument)
def Type(self):
return 'float'
# End of FloatParser
def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value must be a float.
If lower_bound or upper_bound are set, then this flag must be
within the given range.
"""
parser = FloatParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values)
#
# INTEGER FLAGS
#
class IntegerParser(NumericParser):
"""Parser of an integer value.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = "an"
number_name = "integer"
syntactic_help = " ".join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(IntegerParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound))
elif lower_bound == 1:
sh = "a positive %s" % self.number_name
elif upper_bound == -1:
sh = "a negative %s" % self.number_name
elif lower_bound == 0:
sh = "a non-negative %s" % self.number_name
elif upper_bound == 0:
sh = "a non-positive %s" % self.number_name
elif upper_bound is not None:
sh = "%s <= %s" % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = "%s >= %s" % (self.number_name, lower_bound)
self.syntactic_help = sh
def Convert(self, argument):
__pychecker__ = 'no-returnvalues'
if type(argument) == str:
base = 10
if len(argument) > 2 and argument[0] == "0" and argument[1] == "x":
base = 16
return int(argument, base)
else:
return int(argument)
def Type(self):
return 'int'
def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value must be an integer.
If lower_bound, or upper_bound are set, then this flag must be
within the given range.
"""
parser = IntegerParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values)
#
# ENUM FLAGS
#
class EnumParser(ArgumentParser):
"""Parser of a string enum value (a string value from a given set).
If enum_values (see below) is not specified, any string is allowed.
"""
def __init__(self, enum_values=None):
super(EnumParser, self).__init__()
self.enum_values = enum_values
def Parse(self, argument):
if self.enum_values and argument not in self.enum_values:
raise ValueError("value should be one of <%s>" %
"|".join(self.enum_values))
return argument
def Type(self):
return 'string enum'
class EnumFlag(Flag):
"""Basic enum flag; its value can be any string from list of enum_values."""
def __init__(self, name, default, help, enum_values=None,
short_name=None, **args):
enum_values = enum_values or []
p = EnumParser(enum_values)
g = ArgumentSerializer()
Flag.__init__(self, p, g, name, default, help, short_name, **args)
if not self.help: self.help = "an enum string"
self.help = "<%s>: %s" % ("|".join(enum_values), self.help)
def _WriteCustomInfoInXMLFormat(self, outfile, indent):
for enum_value in self.parser.enum_values:
_WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent)
def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS,
**args):
"""Registers a flag whose value can be any string from enum_values."""
DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args),
flag_values)
#
# LIST FLAGS
#
class BaseListParser(ArgumentParser):
"""Base class for a parser of lists of strings.
To extend, inherit from this class; from the subclass __init__, call
BaseListParser.__init__(self, token, name)
where token is a character used to tokenize, and name is a description
of the separator.
"""
def __init__(self, token=None, name=None):
assert name
super(BaseListParser, self).__init__()
self._token = token
self._name = name
self.syntactic_help = "a %s separated list" % self._name
def Parse(self, argument):
if isinstance(argument, list):
return argument
elif argument == '':
return []
else:
return [s.strip() for s in argument.split(self._token)]
def Type(self):
return '%s separated list of strings' % self._name
class ListParser(BaseListParser):
"""Parser for a comma-separated list of strings."""
def __init__(self):
BaseListParser.__init__(self, ',', 'comma')
def WriteCustomInfoInXMLFormat(self, outfile, indent):
BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent)
_WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent)
class WhitespaceSeparatedListParser(BaseListParser):
"""Parser for a whitespace-separated list of strings."""
def __init__(self):
BaseListParser.__init__(self, None, 'whitespace')
def WriteCustomInfoInXMLFormat(self, outfile, indent):
BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent)
separators = list(string.whitespace)
separators.sort()
for ws_char in string.whitespace:
_WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent)
def DEFINE_list(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value is a comma-separated list of strings."""
parser = ListParser()
serializer = ListSerializer(',')
DEFINE(parser, name, default, help, flag_values, serializer, **args)
def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value is a whitespace-separated list of strings.
Any whitespace can be used as a separator.
"""
parser = WhitespaceSeparatedListParser()
serializer = ListSerializer(' ')
DEFINE(parser, name, default, help, flag_values, serializer, **args)
#
# MULTI FLAGS
#
class MultiFlag(Flag):
"""A flag that can appear multiple time on the command-line.
The value of such a flag is a list that contains the individual values
from all the appearances of that flag on the command-line.
See the __doc__ for Flag for most behavior of this class. Only
differences in behavior are described here:
* The default value may be either a single value or a list of values.
A single value is interpreted as the [value] singleton list.
* The value of the flag is always a list, even if the option was
only supplied once, and even if the default value is a single
value
"""
def __init__(self, *args, **kwargs):
Flag.__init__(self, *args, **kwargs)
self.help += ';\n repeat this option to specify a list of values'
def Parse(self, arguments):
"""Parses one or more arguments with the installed parser.
Args:
arguments: a single argument or a list of arguments (typically a
list of default values); a single argument is converted
internally into a list containing one item.
"""
if not isinstance(arguments, list):
# Default value may be a list of values. Most other arguments
# will not be, so convert them into a single-item list to make
# processing simpler below.
arguments = [arguments]
if self.present:
# keep a backup reference to list of previously supplied option values
values = self.value
else:
# "erase" the defaults with an empty list
values = []
for item in arguments:
# have Flag superclass parse argument, overwriting self.value reference
Flag.Parse(self, item) # also increments self.present
values.append(self.value)
# put list of option values back in the 'value' attribute
self.value = values
def Serialize(self):
if not self.serializer:
raise FlagsError("Serializer not present for flag %s" % self.name)
if self.value is None:
return ''
s = ''
multi_value = self.value
for self.value in multi_value:
if s: s += ' '
s += Flag.Serialize(self)
self.value = multi_value
return s
def Type(self):
return 'multi ' + self.parser.Type()
def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS,
**args):
"""Registers a generic MultiFlag that parses its args with a given parser.
Auxiliary function. Normal users should NOT use it directly.
Developers who need to create their own 'Parser' classes for options
which can appear multiple times can call this module function to
register their flags.
"""
DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args),
flag_values)
def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of any strings.
Use the flag on the command line multiple times to place multiple
string values into the list. The 'default' may be a single string
(which will be converted into a single-element list) or a list of
strings.
"""
parser = ArgumentParser()
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of arbitrary integers.
Use the flag on the command line multiple times to place multiple
integer values into the list. The 'default' may be a single integer
(which will be converted into a single-element list) or a list of
integers.
"""
parser = IntegerParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of arbitrary floats.
Use the flag on the command line multiple times to place multiple
float values into the list. The 'default' may be a single float
(which will be converted into a single-element list) or a list of
floats.
"""
parser = FloatParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
# Now register the flags that we want to exist in all applications.
# These are all defined with allow_override=1, so user-apps can use
# these flagnames for their own purposes, if they want.
DEFINE_flag(HelpFlag())
DEFINE_flag(HelpshortFlag())
DEFINE_flag(HelpXMLFlag())
# Define special flags here so that help may be generated for them.
# NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module.
_SPECIAL_FLAGS = FlagValues()
DEFINE_string(
'flagfile', "",
"Insert flag definitions from the given file into the command line.",
_SPECIAL_FLAGS)
DEFINE_string(
'undefok', "",
"comma-separated list of flag names that it is okay to specify "
"on the command line even if the program does not define a flag "
"with that name. IMPORTANT: flags in this list that have "
"arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
| mit |
OmniDB/OmniDB | OmniDB/OmniDB_app/views/memory_objects.py | 1 | 9981 | import os
import json
import threading
import time
from django.http import JsonResponse
from datetime import datetime,timedelta
import OmniDB_app.include.OmniDatabase as OmniDatabase
global_object = {}
to_be_removed = []
def cleanup_thread():
while True:
v_remove_index = len(to_be_removed)-1
try:
while to_be_removed:
conn = to_be_removed.pop(0)
conn.v_connection.Close()
except:
None
for client in list(global_object):
# Client reached timeout
client_timeout_reached = datetime.now() > global_object[client]['last_update'] + timedelta(0,3600)
for tab_id in list(global_object[client]['tab_list']):
try:
# Tab reached timeout
tab_timeout_reached = datetime.now() > global_object[client]['tab_list'][tab_id]['last_update'] + timedelta(0,3600)
if client_timeout_reached or tab_timeout_reached or global_object[client]['tab_list'][tab_id]['to_be_removed'] == True:
close_tab_handler(global_object[client],tab_id)
except Exception as exc:
None
time.sleep(30)
t = threading.Thread(target=cleanup_thread)
t.setDaemon(True)
t.start()
def user_authenticated(function):
def wrap(request, *args, **kwargs):
#User not authenticated
if request.user.is_authenticated:
return function(request, *args, **kwargs)
else:
v_return = {}
v_return['v_data'] = ''
v_return['v_error'] = True
v_return['v_error_id'] = 1
return JsonResponse(v_return)
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
def database_required(p_check_timeout = True, p_open_connection = True):
def decorator(function):
def wrap(request, *args, **kwargs):
v_return = {
'v_data': '',
'v_error': False,
'v_error_id': -1
}
v_session = request.session.get('omnidb_session')
json_object = json.loads(request.POST.get('data', None))
v_database_index = json_object['p_database_index']
v_tab_id = json_object['p_tab_id']
if v_database_index != None:
try:
if p_check_timeout:
#Check database prompt timeout
v_timeout = v_session.DatabaseReachPasswordTimeout(int(v_database_index))
if v_timeout['timeout']:
v_return['v_data'] = {'password_timeout': True, 'message': v_timeout['message'] }
v_return['v_error'] = True
return JsonResponse(v_return)
v_database = get_database_object(
p_session = request.session,
p_tab_id = v_tab_id,
p_database_index = v_database_index,
p_attempt_to_open_connection = p_open_connection
)
except Exception as exc:
v_return['v_data'] = {'password_timeout': True, 'message': str(exc) }
v_return['v_error'] = True
return JsonResponse(v_return)
else:
v_database = None
return function(request, v_database, *args, **kwargs)
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
return decorator
def close_tab_handler(p_client_object,p_tab_object_id):
try:
tab_object = p_client_object['tab_list'][p_tab_object_id]
del p_client_object['tab_list'][p_tab_object_id]
if tab_object['type'] == 'query' or tab_object['type'] == 'console' or tab_object['type'] == 'connection' or tab_object['type'] == 'edit':
try:
tab_object['omnidatabase'].v_connection.Cancel(False)
except Exception:
None
try:
tab_object['omnidatabase'].v_connection.Close()
except Exception as exc:
None
elif tab_object['type'] == 'debug':
tab_object['cancelled'] = True
try:
tab_object['omnidatabase_control'].v_connection.Cancel(False)
except Exception:
None
try:
tab_object['omnidatabase_control'].v_connection.Terminate(tab_object['debug_pid'])
except Exception:
None
try:
tab_object['omnidatabase_control'].v_connection.Close()
except Exception:
None
try:
tab_object['omnidatabase_debug'].v_connection.Close()
except Exception:
None
elif tab_object['type'] == 'terminal':
if tab_object['thread']!=None:
tab_object['thread'].stop()
if tab_object['terminal_type'] == 'local':
tab_object['terminal_object'].terminate()
else:
tab_object['terminal_object'].close()
tab_object['terminal_ssh_client'].close()
except Exception as exc:
None
def clear_client_object(
p_client_id = None
):
try:
client_object = global_object[p_client_id]
for tab_id in list(client_object['tab_list']):
global_object[p_client_id]['tab_list'][tab_id]['to_be_removed'] = True
try:
client_object['polling_lock'].release()
except:
None
try:
client_object['returning_data_lock'].release()
except:
None
except Exception as exc:
None
def create_tab_object(
p_session,
p_tab_id,
p_object
):
v_object = p_object
v_object['last_update'] = datetime.now()
v_object['to_be_removed'] = False
global_object[p_session.session_key]['tab_list'][p_tab_id] = v_object
return v_object
def get_client_object(p_client_id):
#get client attribute in global object or create if it doesn't exist
try:
client_object = global_object[p_client_id]
except Exception as exc:
client_object = {
'id': p_client_id,
'polling_lock': threading.Lock(),
'returning_data_lock': threading.Lock(),
'returning_data': [],
'tab_list': {},
'last_update': datetime.now()
}
global_object[p_client_id] = client_object
return client_object
def get_database_object(
p_session = None,
p_tab_id = None,
p_database_index = None,
p_attempt_to_open_connection = False
):
v_session = p_session.get('omnidb_session')
v_client_id = p_session.session_key
v_client_object = get_client_object(v_client_id)
# Retrieving tab object
try:
v_tab_object = v_client_object['tab_list'][p_tab_id]
except Exception as exc:
# Create global lock object
v_tab_object = create_tab_object(
p_session,
p_tab_id,
{
'omnidatabase': None,
'type': 'connection'
}
)
return get_database_tab_object(
v_session,
v_client_object,
v_tab_object,
p_tab_id,
p_database_index,
p_attempt_to_open_connection,
True
)
def get_database_tab_object(
p_session = None,
p_client_object = None,
p_tab_object = None,
p_connection_tab_id = None,
p_database_index = None,
p_attempt_to_open_connection = False,
p_use_lock = False
):
v_global_database_object = p_session.v_databases[p_database_index]['database']
v_current_tab_database = p_session.v_tabs_databases[p_connection_tab_id]
# Updating time
p_tab_object['last_update'] = datetime.now()
if (p_tab_object['omnidatabase'] == None or
(v_global_database_object.v_db_type!=p_tab_object['omnidatabase'].v_db_type or
v_global_database_object.v_connection.v_host!=p_tab_object['omnidatabase'].v_connection.v_host or
str(v_global_database_object.v_connection.v_port)!=str(p_tab_object['omnidatabase'].v_connection.v_port) or
v_current_tab_database!=p_tab_object['omnidatabase'].v_active_service or
v_global_database_object.v_active_user!=p_tab_object['omnidatabase'].v_active_user or
v_global_database_object.v_connection.v_password!=p_tab_object['omnidatabase'].v_connection.v_password)
):
v_database_new = OmniDatabase.Generic.InstantiateDatabase(
v_global_database_object.v_db_type,
v_global_database_object.v_connection.v_host,
str(v_global_database_object.v_connection.v_port),
v_current_tab_database,
v_global_database_object.v_active_user,
v_global_database_object.v_connection.v_password,
v_global_database_object.v_conn_id,
v_global_database_object.v_alias,
p_conn_string = v_global_database_object.v_conn_string,
p_parse_conn_string = False
)
if p_use_lock:
v_database_new.v_lock = threading.Lock()
# Instead of waiting for garbage collector to clear existing connection,
# put it in the list of to be removed connections and let the cleaning
# thread close it
if (p_tab_object['omnidatabase']):
to_be_removed.append(p_tab_object['omnidatabase'])
p_tab_object['omnidatabase'] = v_database_new
# Try to open connection if not opened yet
if p_attempt_to_open_connection and (not p_tab_object['omnidatabase'].v_connection.v_con or p_tab_object['omnidatabase'].v_connection.GetConStatus() == 0):
p_tab_object['omnidatabase'].v_connection.Open()
return p_tab_object['omnidatabase']
| mit |
h2oai/h2o | py/testdir_single_jvm/test_summary2_uniform_int_w_NA.py | 9 | 8411 | import unittest, time, sys, random, math, getpass
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_import as h2i, h2o_util, h2o_print as h2p
import h2o_summ, h2o_browse as h2b, h2o_util
print "Like test_summary_uniform, but with integers only"
DO_MEDIAN = False
MAX_QBINS = 1
MAX_QBINS = 1000000
DO_REAL = False
ROWS = 10000 # passes
ROWS = 100000 # passes
ROWS = 1000000 # corrupted hcnt2_min/max and ratio 5
NA_ROW_RATIO = 1
def write_syn_dataset(csvPathname, rowCount, colCount, expectedMin, expectedMax, SEED):
r1 = random.Random(SEED)
dsf = open(csvPathname, "w+")
expectedRange = (expectedMax - expectedMin)
for i in range(rowCount):
rowData = []
if DO_REAL:
ri = expectedMin + (random.random() * expectedRange)
else:
ri = random.randint(expectedMin,expectedMax)
for j in range(colCount):
rowData.append(ri)
rowDataCsv = ",".join(map(str,rowData))
for k in range(NA_ROW_RATIO):
dsf.write(rowDataCsv + "\n")
dsf.close()
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
global SEED
SEED = h2o.setup_random_seed()
h2o.init()
# h2b.browseTheCloud()
@classmethod
def tearDownClass(cls):
# h2o.sleep(3600)
h2o.tear_down_cloud()
def test_summary2_uniform_int_w_NA(self):
SYNDATASETS_DIR = h2o.make_syn_dir()
M = 100
tryList = [
# colname, (min, 25th, 50th, 75th, max)
(ROWS, 1, 'B.hex', 1, 1000*M, ('C1', 1.0*M, 250.0*M, 500.0*M, 750.0*M, 1000.0*M)),
(ROWS, 1, 'B.hex', 1, 1000, ('C1', 1.0, 250.0, 500.0, 750.0, 1000.0)),
(ROWS, 1, 'x.hex', 1, 20000, ('C1', 1.0, 5000.0, 10000.0, 15000.0, 20000.0)),
(ROWS, 1, 'x.hex', -5000, 0, ('C1', -5000.00, -3750.0, -2500.0, -1250.0, 0)),
(ROWS, 1, 'x.hex', -100000, 100000, ('C1', -100000.0, -50000.0, 0, 50000.0, 100000.0)),
# (ROWS, 1, 'A.hex', 1, 101, ('C1', 1.0, 26.00, 51.00, 76.00, 101.0)),
# (ROWS, 1, 'A.hex', -99, 99, ('C1', -99, -49.0, 0, 49.00, 99)),
(ROWS, 1, 'B.hex', 1, 10000, ('C1', 1.0, 2501.0, 5001.0, 7501.0, 10000.0)),
(ROWS, 1, 'B.hex', -100, 100, ('C1', -100.0, -50.0, 0.0, 50.0, 100.0)),
(ROWS, 1, 'C.hex', 1, 100000, ('C1', 1.0, 25001.0, 50001.0, 75001.0, 100000.0)),
# (ROWS, 1, 'C.hex', -101, 101, ('C1', -101, -51, -1, 49.0, 100.0)),
]
if not DO_REAL:
# only 3 integer values!
tryList.append(\
(1000000, 1, 'x.hex', -1, 1, ('C1', -1.0, -1, 0.000, 1, 1.00)) \
)
timeoutSecs = 10
trial = 1
n = h2o.nodes[0]
lenNodes = len(h2o.nodes)
x = 0
timeoutSecs = 60
for (rowCount, colCount, hex_key, expectedMin, expectedMax, expected) in tryList:
# max error = half the bin size?
maxDelta = ((expectedMax - expectedMin)/(MAX_QBINS + 0.0))
# add 5% for fp errors?
maxDelta = 1.05 * maxDelta
# also need to add some variance due to random distribution?
# maybe a percentage of the mean
distMean = (expectedMax - expectedMin) / 2
maxShift = distMean * .01
maxDelta = maxDelta + maxShift
SEEDPERFILE = random.randint(0, sys.maxint)
x += 1
csvFilename = 'syn_' + "binary" + "_" + str(rowCount) + 'x' + str(colCount) + '.csv'
csvPathname = SYNDATASETS_DIR + '/' + csvFilename
print "Creating random", csvPathname
write_syn_dataset(csvPathname, rowCount, colCount, expectedMin, expectedMax, SEEDPERFILE)
csvPathnameFull = h2i.find_folder_and_filename(None, csvPathname, returnFullPath=True)
parseResult = h2i.import_parse(path=csvPathname, schema='put', hex_key=hex_key, timeoutSecs=60, doSummary=False)
print "Parse result['destination_key']:", parseResult['destination_key']
inspect = h2o_cmd.runInspect(None, parseResult['destination_key'])
print "\n" + csvFilename
numRows = inspect["numRows"]
numCols = inspect["numCols"]
summaryResult = h2o_cmd.runSummary(key=hex_key, max_qbins=MAX_QBINS)
h2o.verboseprint("summaryResult:", h2o.dump_json(summaryResult))
# only one column
column = summaryResult['summaries'][0]
colname = column['colname']
self.assertEqual(colname, expected[0])
coltype = column['type']
nacnt = column['nacnt']
stats = column['stats']
stattype= stats['type']
# FIX! we should compare mean and sd to expected?
mean = stats['mean']
sd = stats['sd']
print "colname:", colname, "mean (2 places):", h2o_util.twoDecimals(mean)
print "colname:", colname, "std dev. (2 places):", h2o_util.twoDecimals(sd)
zeros = stats['zeros']
mins = stats['mins']
maxs = stats['maxs']
h2o_util.assertApproxEqual(mins[0], expected[1], tol=maxDelta, msg='min is not approx. expected')
h2o_util.assertApproxEqual(maxs[0], expected[5], tol=maxDelta, msg='max is not approx. expected')
pct = stats['pct']
# the thresholds h2o used, should match what we expected
expectedPct= [0.01, 0.05, 0.1, 0.25, 0.33, 0.5, 0.66, 0.75, 0.9, 0.95, 0.99]
pctile = stats['pctile']
h2o_util.assertApproxEqual(pctile[3], expected[2], tol=maxDelta, msg='25th percentile is not approx. expected')
h2o_util.assertApproxEqual(pctile[5], expected[3], tol=maxDelta, msg='50th percentile (median) is not approx. expected')
h2o_util.assertApproxEqual(pctile[7], expected[4], tol=maxDelta, msg='75th percentile is not approx. expected')
hstart = column['hstart']
hstep = column['hstep']
hbrk = column['hbrk']
hcnt = column['hcnt']
print "pct:", pct
print "hcnt:", hcnt
print "len(hcnt)", len(hcnt)
# don't check the last bin
for b in hcnt[1:-1]:
# should we be able to check for a uniform distribution in the files?
e = numRows/len(hcnt) # expect 21 thresholds, so 20 bins. each 5% of rows (uniform distribution)
# don't check the edge bins
self.assertAlmostEqual(b, rowCount/len(hcnt), delta=.01*rowCount,
msg="Bins not right. b: %s e: %s" % (b, e))
pt = h2o_util.twoDecimals(pctile)
mx = h2o_util.twoDecimals(maxs)
mn = h2o_util.twoDecimals(mins)
print "colname:", colname, "pctile (2 places):", pt
print "colname:", colname, "maxs: (2 places):", mx
print "colname:", colname, "mins: (2 places):", mn
# FIX! we should do an exec and compare using the exec quantile too
compareActual = mn[0], pt[3], pt[5], pt[7], mx[0]
h2p.green_print("min/25/50/75/max colname:", colname, "(2 places):", compareActual)
print "maxs colname:", colname, "(2 places):", mx
print "mins colname:", colname, "(2 places):", mn
trial += 1
scipyCol = 0
# don't check if colname is empty..means it's a string and scipy doesn't parse right?
if colname!='':
# don't do for enums
# also get the median with a sort (h2o_summ.percentileOnSortedlist()
h2o_summ.quantile_comparisons(
csvPathnameFull,
col=0, # what col to extract from the csv
datatype='float',
quantile=0.5 if DO_MEDIAN else 0.999,
h2oSummary2=pctile[5 if DO_MEDIAN else 10],
# h2oQuantilesApprox=qresult_single,
# h2oQuantilesExact=qresult,
)
h2o.nodes[0].remove_all_keys()
if __name__ == '__main__':
h2o.unit_main()
| apache-2.0 |
kevinthesun/mxnet | python/mxnet/symbol_doc.py | 44 | 10153 | # 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.
# coding: utf-8
# pylint: disable=unused-argument, too-many-arguments
"""Extra symbol documents
Guidelines
----------
To add extra doc to the operator `XXX`, write a class `XXXDoc`, deriving
from the base class `SymbolDoc`, and put the extra doc as the docstring
of `XXXDoc`.
The document added here should be Python-specific. Documents that are useful
for all language bindings should be added to the C++ side where the operator
is defined / registered.
The code snippet in the docstring will be run using `doctest`. During running,
the environment will have access to
- all the global names in this file (e.g. `SymbolDoc`)
- all the operators (e.g. `FullyConnected`)
- the name `test_utils` for `mx.test_utils` (e.g. `test_utils.reldiff`)
- the name `mx` (e.g. `mx.nd.zeros`)
- the name `np`
The following documents are recommended:
- *Examples*: simple and short code snippet showing how to use this operator.
It should show typical calling examples and behaviors (e.g. maps an input
of what shape to an output of what shape).
- *Regression Test*: longer test code for the operators. We normally do not
expect the users to read those, but they will be executed by `doctest` to
ensure the behavior of each operator does not change unintentionally.
"""
from __future__ import absolute_import as _abs
import re as _re
from .base import build_param_doc as _build_param_doc
class SymbolDoc(object):
"""The base class for attaching doc to operators."""
@staticmethod
def get_output_shape(sym, **input_shapes):
"""Get user friendly information of the output shapes."""
_, s_outputs, _ = sym.infer_shape(**input_shapes)
return dict(zip(sym.list_outputs(), s_outputs))
class ActivationDoc(SymbolDoc):
"""
Examples
--------
A one-hidden-layer MLP with ReLU activation:
>>> data = Variable('data')
>>> mlp = FullyConnected(data=data, num_hidden=128, name='proj')
>>> mlp = Activation(data=mlp, act_type='relu', name='activation')
>>> mlp = FullyConnected(data=mlp, num_hidden=10, name='mlp')
>>> mlp
<Symbol mlp>
Regression Test
---------------
ReLU activation
>>> test_suites = [
... ('relu', lambda x: np.maximum(x, 0)),
... ('sigmoid', lambda x: 1 / (1 + np.exp(-x))),
... ('tanh', lambda x: np.tanh(x)),
... ('softrelu', lambda x: np.log(1 + np.exp(x)))
... ]
>>> x = test_utils.random_arrays((2, 3, 4))
>>> for act_type, numpy_impl in test_suites:
... op = Activation(act_type=act_type, name='act')
... y = test_utils.simple_forward(op, act_data=x)
... y_np = numpy_impl(x)
... print('%s: %s' % (act_type, test_utils.almost_equal(y, y_np)))
relu: True
sigmoid: True
tanh: True
softrelu: True
"""
class DropoutDoc(SymbolDoc):
"""
Examples
--------
Apply dropout to corrupt input as zero with probability 0.2:
>>> data = Variable('data')
>>> data_dp = Dropout(data=data, p=0.2)
Regression Test
---------------
>>> shape = (100, 100) # take larger shapes to be more statistical stable
>>> x = np.ones(shape)
>>> op = Dropout(p=0.5, name='dp')
>>> # dropout is identity during testing
>>> y = test_utils.simple_forward(op, dp_data=x, is_train=False)
>>> test_utils.almost_equal(x, y)
True
>>> y = test_utils.simple_forward(op, dp_data=x, is_train=True)
>>> # expectation is (approximately) unchanged
>>> np.abs(x.mean() - y.mean()) < 0.1
True
>>> set(np.unique(y)) == set([0, 2])
True
"""
class EmbeddingDoc(SymbolDoc):
"""
Examples
--------
Assume we want to map the 26 English alphabet letters to 16-dimensional
vectorial representations.
>>> vocabulary_size = 26
>>> embed_dim = 16
>>> seq_len, batch_size = (10, 64)
>>> input = Variable('letters')
>>> op = Embedding(data=input, input_dim=vocabulary_size, output_dim=embed_dim,
... name='embed')
>>> SymbolDoc.get_output_shape(op, letters=(seq_len, batch_size))
{'embed_output': (10L, 64L, 16L)}
Regression Test
---------------
>>> vocab_size, embed_dim = (26, 16)
>>> batch_size = 12
>>> word_vecs = test_utils.random_arrays((vocab_size, embed_dim))
>>> op = Embedding(name='embed', input_dim=vocab_size, output_dim=embed_dim)
>>> x = np.random.choice(vocab_size, batch_size)
>>> y = test_utils.simple_forward(op, embed_data=x, embed_weight=word_vecs)
>>> y_np = word_vecs[x]
>>> test_utils.almost_equal(y, y_np)
True
"""
class FlattenDoc(SymbolDoc):
"""
Examples
--------
Flatten is usually applied before `FullyConnected`, to reshape the 4D tensor
produced by convolutional layers to 2D matrix:
>>> data = Variable('data') # say this is 4D from some conv/pool
>>> flatten = Flatten(data=data, name='flat') # now this is 2D
>>> SymbolDoc.get_output_shape(flatten, data=(2, 3, 4, 5))
{'flat_output': (2L, 60L)}
Regression Test
---------------
>>> test_dims = [(2, 3, 4, 5), (2, 3), (2,)]
>>> op = Flatten(name='flat')
>>> for dims in test_dims:
... x = test_utils.random_arrays(dims)
... y = test_utils.simple_forward(op, flat_data=x)
... y_np = x.reshape((dims[0], np.prod(dims[1:]).astype('int32')))
... print('%s: %s' % (dims, test_utils.almost_equal(y, y_np)))
(2, 3, 4, 5): True
(2, 3): True
(2,): True
"""
class FullyConnectedDoc(SymbolDoc):
"""
Examples
--------
Construct a fully connected operator with target dimension 512.
>>> data = Variable('data') # or some constructed NN
>>> op = FullyConnected(data=data,
... num_hidden=512,
... name='FC1')
>>> op
<Symbol FC1>
>>> SymbolDoc.get_output_shape(op, data=(128, 100))
{'FC1_output': (128L, 512L)}
A simple 3-layer MLP with ReLU activation:
>>> net = Variable('data')
>>> for i, dim in enumerate([128, 64]):
... net = FullyConnected(data=net, num_hidden=dim, name='FC%d' % i)
... net = Activation(data=net, act_type='relu', name='ReLU%d' % i)
>>> # 10-class predictor (e.g. MNIST)
>>> net = FullyConnected(data=net, num_hidden=10, name='pred')
>>> net
<Symbol pred>
Regression Test
---------------
>>> dim_in, dim_out = (3, 4)
>>> x, w, b = test_utils.random_arrays((10, dim_in), (dim_out, dim_in), (dim_out,))
>>> op = FullyConnected(num_hidden=dim_out, name='FC')
>>> out = test_utils.simple_forward(op, FC_data=x, FC_weight=w, FC_bias=b)
>>> # numpy implementation of FullyConnected
>>> out_np = np.dot(x, w.T) + b
>>> test_utils.almost_equal(out, out_np)
True
"""
def _build_doc(func_name,
desc,
arg_names,
arg_types,
arg_desc,
key_var_num_args=None,
ret_type=None):
"""Build docstring for symbolic functions."""
param_str = _build_param_doc(arg_names, arg_types, arg_desc)
if key_var_num_args:
desc += '\nThis function support variable length of positional input.'
doc_str = ('%s\n\n' +
'%s\n' +
'name : string, optional.\n' +
' Name of the resulting symbol.\n\n' +
'Returns\n' +
'-------\n' +
'Symbol\n' +
' The result symbol.')
doc_str = doc_str % (desc, param_str)
extra_doc = "\n" + '\n'.join([x.__doc__ for x in type.__subclasses__(SymbolDoc)
if x.__name__ == '%sDoc' % func_name])
doc_str += _re.sub(_re.compile(" "), "", extra_doc)
doc_str = _re.sub('NDArray-or-Symbol', 'Symbol', doc_str)
return doc_str
class ConcatDoc(SymbolDoc):
"""
Examples
--------
Concat two (or more) inputs along a specific dimension:
>>> a = Variable('a')
>>> b = Variable('b')
>>> c = Concat(a, b, dim=1, name='my-concat')
>>> c
<Symbol my-concat>
>>> SymbolDoc.get_output_shape(c, a=(128, 10, 3, 3), b=(128, 15, 3, 3))
{'my-concat_output': (128L, 25L, 3L, 3L)}
Note the shape should be the same except on the dimension that is being
concatenated.
"""
class BroadcastPlusDoc(SymbolDoc):
"""
Examples
--------
>>> a = Variable('a')
>>> b = Variable('b')
>>> c = broadcast_plus(a, b)
Normal summation with matching shapes:
>>> dev = mx.context.cpu();
>>> x = c.bind(dev, args={'a': mx.nd.ones((2, 2)), 'b' : mx.nd.ones((2, 2))})
>>> x.forward()
[<NDArray 2x2 @cpu(0)>]
>>> print x.outputs[0].asnumpy()
[[ 2. 2.]
[ 2. 2.]]
Broadcasting:
>>> x = c.bind(dev, args={'a': mx.nd.ones((2, 2)), 'b' : mx.nd.ones((1, 1))})
>>> x.forward()
[<NDArray 2x2 @cpu(0)>]
>>> print x.outputs[0].asnumpy()
[[ 2. 2.]
[ 2. 2.]]
>>> x = c.bind(dev, args={'a': mx.nd.ones((2, 1)), 'b' : mx.nd.ones((1, 2))})
>>> x.forward()
[<NDArray 2x2 @cpu(0)>]
>>> print x.outputs[0].asnumpy()
[[ 2. 2.]
[ 2. 2.]]
>>> x = c.bind(dev, args={'a': mx.nd.ones((1, 2)), 'b' : mx.nd.ones((2, 1))})
>>> x.forward()
[<NDArray 2x2 @cpu(0)>]
>>> print x.outputs[0].asnumpy()
[[ 2. 2.]
[ 2. 2.]]
"""
| apache-2.0 |
rohit21122012/DCASE2013 | runs/2016/dnn2016med_traps/traps10/src/sound_event_detection.py | 56 | 6116 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
def event_detection(feature_data, model_container, hop_length_seconds=0.01, smoothing_window_length_seconds=1.0,
decision_threshold=0.0, minimum_event_length=0.1, minimum_event_gap=0.1):
"""Sound event detection
Parameters
----------
feature_data : numpy.ndarray [shape=(n_features, t)]
Feature matrix
model_container : dict
Sound event model pairs [positive and negative] in dict
hop_length_seconds : float > 0.0
Feature hop length in seconds, used to convert feature index into time-stamp
(Default value=0.01)
smoothing_window_length_seconds : float > 0.0
Accumulation window (look-back) length, withing the window likelihoods are accumulated.
(Default value=1.0)
decision_threshold : float > 0.0
Likelihood ratio threshold for making the decision.
(Default value=0.0)
minimum_event_length : float > 0.0
Minimum event length in seconds, shorten than given are filtered out from the output.
(Default value=0.1)
minimum_event_gap : float > 0.0
Minimum allowed gap between events in seconds from same event label class.
(Default value=0.1)
Returns
-------
results : list (event dicts)
Detection result, event list
"""
smoothing_window = int(smoothing_window_length_seconds / hop_length_seconds)
results = []
for event_label in model_container['models']:
positive = model_container['models'][event_label]['positive'].score_samples(feature_data)[0]
negative = model_container['models'][event_label]['negative'].score_samples(feature_data)[0]
# Lets keep the system causal and use look-back while smoothing (accumulating) likelihoods
for stop_id in range(0, feature_data.shape[0]):
start_id = stop_id - smoothing_window
if start_id < 0:
start_id = 0
positive[start_id] = sum(positive[start_id:stop_id])
negative[start_id] = sum(negative[start_id:stop_id])
likelihood_ratio = positive - negative
event_activity = likelihood_ratio > decision_threshold
# Find contiguous segments and convert frame-ids into times
event_segments = contiguous_regions(event_activity) * hop_length_seconds
# Preprocess the event segments
event_segments = postprocess_event_segments(event_segments=event_segments,
minimum_event_length=minimum_event_length,
minimum_event_gap=minimum_event_gap)
for event in event_segments:
results.append((event[0], event[1], event_label))
return results
def contiguous_regions(activity_array):
"""Find contiguous regions from bool valued numpy.array.
Transforms boolean values for each frame into pairs of onsets and offsets.
Parameters
----------
activity_array : numpy.array [shape=(t)]
Event activity array, bool values
Returns
-------
change_indices : numpy.ndarray [shape=(2, number of found changes)]
Onset and offset indices pairs in matrix
"""
# Find the changes in the activity_array
change_indices = numpy.diff(activity_array).nonzero()[0]
# Shift change_index with one, focus on frame after the change.
change_indices += 1
if activity_array[0]:
# If the first element of activity_array is True add 0 at the beginning
change_indices = numpy.r_[0, change_indices]
if activity_array[-1]:
# If the last element of activity_array is True, add the length of the array
change_indices = numpy.r_[change_indices, activity_array.size]
# Reshape the result into two columns
return change_indices.reshape((-1, 2))
def postprocess_event_segments(event_segments, minimum_event_length=0.1, minimum_event_gap=0.1):
"""Post process event segment list. Makes sure that minimum event length and minimum event gap conditions are met.
Parameters
----------
event_segments : numpy.ndarray [shape=(2, number of event)]
Event segments, first column has the onset, second has the offset.
minimum_event_length : float > 0.0
Minimum event length in seconds, shorten than given are filtered out from the output.
(Default value=0.1)
minimum_event_gap : float > 0.0
Minimum allowed gap between events in seconds from same event label class.
(Default value=0.1)
Returns
-------
event_results : numpy.ndarray [shape=(2, number of event)]
postprocessed event segments
"""
# 1. remove short events
event_results_1 = []
for event in event_segments:
if event[1] - event[0] >= minimum_event_length:
event_results_1.append((event[0], event[1]))
if len(event_results_1):
# 2. remove small gaps between events
event_results_2 = []
# Load first event into event buffer
buffered_event_onset = event_results_1[0][0]
buffered_event_offset = event_results_1[0][1]
for i in range(1, len(event_results_1)):
if event_results_1[i][0] - buffered_event_offset > minimum_event_gap:
# The gap between current event and the buffered is bigger than minimum event gap,
# store event, and replace buffered event
event_results_2.append((buffered_event_onset, buffered_event_offset))
buffered_event_onset = event_results_1[i][0]
buffered_event_offset = event_results_1[i][1]
else:
# The gap between current event and the buffered is smalle than minimum event gap,
# extend the buffered event until the current offset
buffered_event_offset = event_results_1[i][1]
# Store last event from buffer
event_results_2.append((buffered_event_onset, buffered_event_offset))
return event_results_2
else:
return event_results_1
| mit |
rgbkrk/compose | tests/integration/testcases.py | 3 | 2736 | from __future__ import absolute_import
from __future__ import unicode_literals
from docker import errors
from docker.utils import version_lt
from pytest import skip
from .. import unittest
from compose.cli.docker_client import docker_client
from compose.config.config import ServiceLoader
from compose.const import LABEL_PROJECT
from compose.progress_stream import stream_output
from compose.service import Service
def pull_busybox(client):
try:
client.inspect_image('busybox:latest')
except errors.APIError:
client.pull('busybox:latest', stream=False)
class DockerClientTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.client = docker_client()
def tearDown(self):
for c in self.client.containers(
all=True,
filters={'label': '%s=composetest' % LABEL_PROJECT}):
self.client.kill(c['Id'])
self.client.remove_container(c['Id'])
for i in self.client.images(
filters={'label': 'com.docker.compose.test_image'}):
self.client.remove_image(i)
def create_service(self, name, **kwargs):
if 'image' not in kwargs and 'build' not in kwargs:
kwargs['image'] = 'busybox:latest'
if 'command' not in kwargs:
kwargs['command'] = ["top"]
links = kwargs.get('links', None)
volumes_from = kwargs.get('volumes_from', None)
net = kwargs.get('net', None)
workaround_options = ['links', 'volumes_from', 'net']
for key in workaround_options:
try:
del kwargs[key]
except KeyError:
pass
options = ServiceLoader(working_dir='.', filename=None, service_name=name, service_dict=kwargs).make_service_dict()
labels = options.setdefault('labels', {})
labels['com.docker.compose.test-name'] = self.id()
if links:
options['links'] = links
if volumes_from:
options['volumes_from'] = volumes_from
if net:
options['net'] = net
return Service(
project='composetest',
client=self.client,
**options
)
def check_build(self, *args, **kwargs):
kwargs.setdefault('rm', True)
build_output = self.client.build(*args, **kwargs)
stream_output(build_output, open('/dev/null', 'w'))
def require_engine_version(self, minimum):
# Drop '-dev' or '-rcN' suffix
engine = self.client.version()['Version'].split('-', 1)[0]
if version_lt(engine, minimum):
skip(
"Engine version is too low ({} < {})"
.format(engine, minimum)
)
| apache-2.0 |
0111001101111010/open-health-inspection-api | venv/lib/python2.7/site-packages/pip/_vendor/requests/status_codes.py | 695 | 3136 | # -*- coding: utf-8 -*-
from .structures import LookupDict
_codes = {
# Informational.
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('resume_incomplete', 'resume'),
# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
}
codes = LookupDict(name='status_codes')
for (code, titles) in list(_codes.items()):
for title in titles:
setattr(codes, title, code)
if not title.startswith('\\'):
setattr(codes, title.upper(), code)
| gpl-2.0 |
numenta-archive/htmresearch | projects/capybara/anomaly_detection/run_models.py | 6 | 4879 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
Groups together code used for creating a NuPIC model and dealing with IO.
"""
import importlib
import csv
import os
from nupic.data.inference_shifter import InferenceShifter
from nupic.frameworks.opf.model_factory import ModelFactory
import nupic_anomaly_output
from settings import METRICS, PATIENT_IDS, SENSORS, CONVERTED_DATA_DIR, MODEL_PARAMS_DIR, MODEL_RESULTS_DIR
def createModel(modelParams):
"""
Given a model params dictionary, create a CLA Model. Automatically enables
inference for metric_value.
:param modelParams: Model params dict
:return: OPF Model object
"""
model = ModelFactory.create(modelParams)
model.enableInference({"predictedField": "metric_value"})
return model
def getModelParamsFromName(csvName):
"""
Given a csv name, assumes a matching model params python module exists within
the model_params directory and attempts to import it.
:param csvName: CSV name, used to guess the model params module name.
:return: OPF Model params dictionary
"""
print "Creating model from %s..." % csvName
importName = "%s.%s" % (MODEL_PARAMS_DIR, csvName.replace(" ", "_"))
print "Importing model params from %s" % importName
try:
importedModelParams = importlib.import_module(importName).MODEL_PARAMS
except ImportError:
raise Exception("No model params exist for '%s'. "
"Run trajectory_converter.py first!"
% csvName)
return importedModelParams
def runIoThroughNupic(inputData, model, metric, sensor, patientId, plot):
"""
Handles looping over the input data and passing each row into the given model
object, as well as extracting the result object and passing it into an output
handler.
:param inputData: file path to input data CSV
:param model: OPF Model object
:param csvName: CSV name, used for output handler naming
:param plot: Whether to use matplotlib or not. If false, uses file output.
"""
inputFile = open(inputData, "rb")
csvReader = csv.reader(inputFile.read().splitlines())
# skip header rows
csvReader.next()
csvReader.next()
csvReader.next()
csvName = "%s_%s_%s" % (metric, sensor, patientId)
print "running model with model_params '%s'" % csvName
shifter = InferenceShifter()
if plot:
output = nupic_anomaly_output.NuPICPlotOutput(csvName)
else:
if not os.path.exists(MODEL_RESULTS_DIR):
os.makedirs(MODEL_RESULTS_DIR)
output = nupic_anomaly_output.NuPICFileOutput("%s/%s" % (MODEL_RESULTS_DIR,
csvName))
counter = 0
for row in csvReader:
counter += 1
if (counter % 100 == 0):
print "Read %i lines..." % counter
metric_value = float(row[0])
result = model.run({
"metric_value": metric_value
})
if plot:
result = shifter.shift(result)
prediction = result.inferences["multiStepBestPredictions"][0]
anomalyScore = result.inferences["anomalyScore"]
output.write(counter, metric_value, prediction, anomalyScore)
output.close()
inputFile.close()
def runModel(metric, sensor, patientId, plot=False):
"""
Assumes the CSV Name corresponds to both a like-named model_params file in the
model_params directory, and that the data exists in a like-named CSV file in
the current directory.
:param csvName: Important for finding model params and input CSV file
:param plot: Plot in matplotlib? Don't use this unless matplotlib is
installed.
"""
csvName = "%s_%s_%s" % (metric, sensor, patientId)
model = createModel(getModelParamsFromName(csvName))
inputData = "%s/%s.csv" % (CONVERTED_DATA_DIR, csvName)
runIoThroughNupic(inputData, model, metric, sensor, patientId, plot)
if __name__ == "__main__":
for sensor in SENSORS:
for patientId in PATIENT_IDS:
for metric in METRICS:
runModel(metric, sensor, patientId)
| agpl-3.0 |
eestay/edx-platform | common/lib/xmodule/xmodule/vertical_block.py | 6 | 5013 | """
VerticalBlock - an XBlock which renders its children in a column.
"""
import logging
from copy import copy
from lxml import etree
from xblock.core import XBlock
from xblock.fragment import Fragment
from xmodule.mako_module import MakoTemplateBlockBase
from xmodule.progress import Progress
from xmodule.seq_module import SequenceFields
from xmodule.studio_editable import StudioEditableBlock
from xmodule.x_module import STUDENT_VIEW, XModuleFields
from xmodule.xml_module import XmlParserMixin
log = logging.getLogger(__name__)
# HACK: This shouldn't be hard-coded to two types
# OBSOLETE: This obsoletes 'type'
CLASS_PRIORITY = ['video', 'problem']
class VerticalBlock(SequenceFields, XModuleFields, StudioEditableBlock, XmlParserMixin, MakoTemplateBlockBase, XBlock):
"""
Layout XBlock for rendering subblocks vertically.
"""
mako_template = 'widgets/sequence-edit.html'
js_module_name = "VerticalBlock"
has_children = True
def student_view(self, context):
"""
Renders the student view of the block in the LMS.
"""
fragment = Fragment()
contents = []
child_context = {} if not context else copy(context)
child_context['child_of_vertical'] = True
# pylint: disable=no-member
for child in self.get_display_items():
rendered_child = child.render(STUDENT_VIEW, child_context)
fragment.add_frag_resources(rendered_child)
contents.append({
'id': child.location.to_deprecated_string(),
'content': rendered_child.content
})
fragment.add_content(self.system.render_template('vert_module.html', {
'items': contents,
'xblock_context': context,
}))
return fragment
def author_view(self, context):
"""
Renders the Studio preview view, which supports drag and drop.
"""
fragment = Fragment()
root_xblock = context.get('root_xblock')
is_root = root_xblock and root_xblock.location == self.location # pylint: disable=no-member
# For the container page we want the full drag-and-drop, but for unit pages we want
# a more concise version that appears alongside the "View =>" link-- unless it is
# the unit page and the vertical being rendered is itself the unit vertical (is_root == True).
if is_root or not context.get('is_unit_page'):
self.render_children(context, fragment, can_reorder=True, can_add=True)
return fragment
def get_progress(self):
"""
Returns the progress on this block and all children.
"""
# TODO: Cache progress or children array?
children = self.get_children() # pylint: disable=no-member
progresses = [child.get_progress() for child in children]
progress = reduce(Progress.add_counts, progresses, None)
return progress
def get_icon_class(self):
"""
Returns the highest priority icon class.
"""
child_classes = set(child.get_icon_class() for child in self.get_children()) # pylint: disable=no-member
new_class = 'other'
for higher_class in CLASS_PRIORITY:
if higher_class in child_classes:
new_class = higher_class
return new_class
@classmethod
def definition_from_xml(cls, xml_object, system):
children = []
for child in xml_object:
try:
child_block = system.process_xml(etree.tostring(child, encoding='unicode')) # pylint: disable=no-member
children.append(child_block.scope_ids.usage_id)
except Exception as exc: # pylint: disable=broad-except
log.exception("Unable to load child when parsing Vertical. Continuing...")
if system.error_tracker is not None:
system.error_tracker(u"ERROR: {0}".format(exc))
continue
return {}, children
def definition_to_xml(self, resource_fs):
xml_object = etree.Element('vertical') # pylint: disable=no-member
for child in self.get_children(): # pylint: disable=no-member
self.runtime.add_block_as_child_node(child, xml_object)
return xml_object
@property
def non_editable_metadata_fields(self):
"""
Gather all fields which can't be edited.
"""
non_editable_fields = super(VerticalBlock, self).non_editable_metadata_fields
non_editable_fields.extend([
self.fields['due'],
])
return non_editable_fields
def studio_view(self, context):
fragment = super(VerticalBlock, self).studio_view(context)
# This continues to use the old XModuleDescriptor javascript code to enabled studio editing.
# TODO: Remove this when studio better supports editing of pure XBlocks.
fragment.add_javascript('VerticalBlock = XModule.Descriptor;')
return fragment
| agpl-3.0 |
madelynfreed/rlundo | venv/lib/python2.7/site-packages/IPython/nbconvert/exporters/tests/test_html.py | 6 | 2654 | """Tests for HTMLExporter"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .base import ExportersTestsBase
from ..html import HTMLExporter
from IPython.nbformat import v4
import re
class TestHTMLExporter(ExportersTestsBase):
"""Tests for HTMLExporter"""
exporter_class = HTMLExporter
should_include_raw = ['html']
def test_constructor(self):
"""
Can a HTMLExporter be constructed?
"""
HTMLExporter()
def test_export(self):
"""
Can a HTMLExporter export something?
"""
(output, resources) = HTMLExporter().from_filename(self._get_notebook())
assert len(output) > 0
def test_export_basic(self):
"""
Can a HTMLExporter export using the 'basic' template?
"""
(output, resources) = HTMLExporter(template_file='basic').from_filename(self._get_notebook())
assert len(output) > 0
def test_export_full(self):
"""
Can a HTMLExporter export using the 'full' template?
"""
(output, resources) = HTMLExporter(template_file='full').from_filename(self._get_notebook())
assert len(output) > 0
def test_prompt_number(self):
"""
Does HTMLExporter properly format input and output prompts?
"""
(output, resources) = HTMLExporter(template_file='full').from_filename(
self._get_notebook(nb_name="prompt_numbers.ipynb"))
in_regex = r"In \[(.*)\]:"
out_regex = r"Out\[(.*)\]:"
ins = ["2", "10", " ", " ", "*", "0"]
outs = ["10"]
assert re.findall(in_regex, output) == ins
assert re.findall(out_regex, output) == outs
def test_png_metadata(self):
"""
Does HTMLExporter with the 'basic' template treat pngs with width/height metadata correctly?
"""
(output, resources) = HTMLExporter(template_file='basic').from_filename(
self._get_notebook(nb_name="pngmetadata.ipynb"))
assert len(output) > 0
def test_javascript_output(self):
nb = v4.new_notebook(
cells=[
v4.new_code_cell(
outputs=[v4.new_output(
output_type='display_data',
data={
'application/javascript': "javascript_output();"
}
)]
)
]
)
(output, resources) = HTMLExporter(template_file='basic').from_notebook_node(nb)
self.assertIn('javascript_output', output)
| gpl-3.0 |
ahmetabdi/SickRage | lib/unidecode/x093.py | 252 | 4666 | data = (
'Lun ', # 0x00
'Kua ', # 0x01
'Ling ', # 0x02
'Bei ', # 0x03
'Lu ', # 0x04
'Li ', # 0x05
'Qiang ', # 0x06
'Pou ', # 0x07
'Juan ', # 0x08
'Min ', # 0x09
'Zui ', # 0x0a
'Peng ', # 0x0b
'An ', # 0x0c
'Pi ', # 0x0d
'Xian ', # 0x0e
'Ya ', # 0x0f
'Zhui ', # 0x10
'Lei ', # 0x11
'A ', # 0x12
'Kong ', # 0x13
'Ta ', # 0x14
'Kun ', # 0x15
'Du ', # 0x16
'Wei ', # 0x17
'Chui ', # 0x18
'Zi ', # 0x19
'Zheng ', # 0x1a
'Ben ', # 0x1b
'Nie ', # 0x1c
'Cong ', # 0x1d
'Qun ', # 0x1e
'Tan ', # 0x1f
'Ding ', # 0x20
'Qi ', # 0x21
'Qian ', # 0x22
'Zhuo ', # 0x23
'Qi ', # 0x24
'Yu ', # 0x25
'Jin ', # 0x26
'Guan ', # 0x27
'Mao ', # 0x28
'Chang ', # 0x29
'Tian ', # 0x2a
'Xi ', # 0x2b
'Lian ', # 0x2c
'Tao ', # 0x2d
'Gu ', # 0x2e
'Cuo ', # 0x2f
'Shu ', # 0x30
'Zhen ', # 0x31
'Lu ', # 0x32
'Meng ', # 0x33
'Lu ', # 0x34
'Hua ', # 0x35
'Biao ', # 0x36
'Ga ', # 0x37
'Lai ', # 0x38
'Ken ', # 0x39
'Kazari ', # 0x3a
'Bu ', # 0x3b
'Nai ', # 0x3c
'Wan ', # 0x3d
'Zan ', # 0x3e
'[?] ', # 0x3f
'De ', # 0x40
'Xian ', # 0x41
'[?] ', # 0x42
'Huo ', # 0x43
'Liang ', # 0x44
'[?] ', # 0x45
'Men ', # 0x46
'Kai ', # 0x47
'Ying ', # 0x48
'Di ', # 0x49
'Lian ', # 0x4a
'Guo ', # 0x4b
'Xian ', # 0x4c
'Du ', # 0x4d
'Tu ', # 0x4e
'Wei ', # 0x4f
'Cong ', # 0x50
'Fu ', # 0x51
'Rou ', # 0x52
'Ji ', # 0x53
'E ', # 0x54
'Rou ', # 0x55
'Chen ', # 0x56
'Ti ', # 0x57
'Zha ', # 0x58
'Hong ', # 0x59
'Yang ', # 0x5a
'Duan ', # 0x5b
'Xia ', # 0x5c
'Yu ', # 0x5d
'Keng ', # 0x5e
'Xing ', # 0x5f
'Huang ', # 0x60
'Wei ', # 0x61
'Fu ', # 0x62
'Zhao ', # 0x63
'Cha ', # 0x64
'Qie ', # 0x65
'She ', # 0x66
'Hong ', # 0x67
'Kui ', # 0x68
'Tian ', # 0x69
'Mou ', # 0x6a
'Qiao ', # 0x6b
'Qiao ', # 0x6c
'Hou ', # 0x6d
'Tou ', # 0x6e
'Cong ', # 0x6f
'Huan ', # 0x70
'Ye ', # 0x71
'Min ', # 0x72
'Jian ', # 0x73
'Duan ', # 0x74
'Jian ', # 0x75
'Song ', # 0x76
'Kui ', # 0x77
'Hu ', # 0x78
'Xuan ', # 0x79
'Duo ', # 0x7a
'Jie ', # 0x7b
'Zhen ', # 0x7c
'Bian ', # 0x7d
'Zhong ', # 0x7e
'Zi ', # 0x7f
'Xiu ', # 0x80
'Ye ', # 0x81
'Mei ', # 0x82
'Pai ', # 0x83
'Ai ', # 0x84
'Jie ', # 0x85
'[?] ', # 0x86
'Mei ', # 0x87
'Chuo ', # 0x88
'Ta ', # 0x89
'Bang ', # 0x8a
'Xia ', # 0x8b
'Lian ', # 0x8c
'Suo ', # 0x8d
'Xi ', # 0x8e
'Liu ', # 0x8f
'Zu ', # 0x90
'Ye ', # 0x91
'Nou ', # 0x92
'Weng ', # 0x93
'Rong ', # 0x94
'Tang ', # 0x95
'Suo ', # 0x96
'Qiang ', # 0x97
'Ge ', # 0x98
'Shuo ', # 0x99
'Chui ', # 0x9a
'Bo ', # 0x9b
'Pan ', # 0x9c
'Sa ', # 0x9d
'Bi ', # 0x9e
'Sang ', # 0x9f
'Gang ', # 0xa0
'Zi ', # 0xa1
'Wu ', # 0xa2
'Ying ', # 0xa3
'Huang ', # 0xa4
'Tiao ', # 0xa5
'Liu ', # 0xa6
'Kai ', # 0xa7
'Sun ', # 0xa8
'Sha ', # 0xa9
'Sou ', # 0xaa
'Wan ', # 0xab
'Hao ', # 0xac
'Zhen ', # 0xad
'Zhen ', # 0xae
'Luo ', # 0xaf
'Yi ', # 0xb0
'Yuan ', # 0xb1
'Tang ', # 0xb2
'Nie ', # 0xb3
'Xi ', # 0xb4
'Jia ', # 0xb5
'Ge ', # 0xb6
'Ma ', # 0xb7
'Juan ', # 0xb8
'Kasugai ', # 0xb9
'Habaki ', # 0xba
'Suo ', # 0xbb
'[?] ', # 0xbc
'[?] ', # 0xbd
'[?] ', # 0xbe
'Na ', # 0xbf
'Lu ', # 0xc0
'Suo ', # 0xc1
'Ou ', # 0xc2
'Zu ', # 0xc3
'Tuan ', # 0xc4
'Xiu ', # 0xc5
'Guan ', # 0xc6
'Xuan ', # 0xc7
'Lian ', # 0xc8
'Shou ', # 0xc9
'Ao ', # 0xca
'Man ', # 0xcb
'Mo ', # 0xcc
'Luo ', # 0xcd
'Bi ', # 0xce
'Wei ', # 0xcf
'Liu ', # 0xd0
'Di ', # 0xd1
'Qiao ', # 0xd2
'Cong ', # 0xd3
'Yi ', # 0xd4
'Lu ', # 0xd5
'Ao ', # 0xd6
'Keng ', # 0xd7
'Qiang ', # 0xd8
'Cui ', # 0xd9
'Qi ', # 0xda
'Chang ', # 0xdb
'Tang ', # 0xdc
'Man ', # 0xdd
'Yong ', # 0xde
'Chan ', # 0xdf
'Feng ', # 0xe0
'Jing ', # 0xe1
'Biao ', # 0xe2
'Shu ', # 0xe3
'Lou ', # 0xe4
'Xiu ', # 0xe5
'Cong ', # 0xe6
'Long ', # 0xe7
'Zan ', # 0xe8
'Jian ', # 0xe9
'Cao ', # 0xea
'Li ', # 0xeb
'Xia ', # 0xec
'Xi ', # 0xed
'Kang ', # 0xee
'[?] ', # 0xef
'Beng ', # 0xf0
'[?] ', # 0xf1
'[?] ', # 0xf2
'Zheng ', # 0xf3
'Lu ', # 0xf4
'Hua ', # 0xf5
'Ji ', # 0xf6
'Pu ', # 0xf7
'Hui ', # 0xf8
'Qiang ', # 0xf9
'Po ', # 0xfa
'Lin ', # 0xfb
'Suo ', # 0xfc
'Xiu ', # 0xfd
'San ', # 0xfe
'Cheng ', # 0xff
)
| gpl-3.0 |
haojunyu/numpy | benchmarks/benchmarks/bench_function_base.py | 42 | 2328 | from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Bincount(Benchmark):
def setup(self):
self.d = np.arange(80000, dtype=np.intp)
self.e = self.d.astype(np.float64)
def time_bincount(self):
np.bincount(self.d)
def time_weights(self):
np.bincount(self.d, weights=self.e)
class Median(Benchmark):
def setup(self):
self.e = np.arange(10000, dtype=np.float32)
self.o = np.arange(10001, dtype=np.float32)
def time_even(self):
np.median(self.e)
def time_odd(self):
np.median(self.o)
def time_even_inplace(self):
np.median(self.e, overwrite_input=True)
def time_odd_inplace(self):
np.median(self.o, overwrite_input=True)
def time_even_small(self):
np.median(self.e[:500], overwrite_input=True)
def time_odd_small(self):
np.median(self.o[:500], overwrite_input=True)
class Percentile(Benchmark):
def setup(self):
self.e = np.arange(10000, dtype=np.float32)
self.o = np.arange(10001, dtype=np.float32)
def time_quartile(self):
np.percentile(self.e, [25, 75])
def time_percentile(self):
np.percentile(self.e, [25, 35, 55, 65, 75])
class Select(Benchmark):
def setup(self):
self.d = np.arange(20000)
self.e = self.d.copy()
self.cond = [(self.d > 4), (self.d < 2)]
self.cond_large = [(self.d > 4), (self.d < 2)] * 10
def time_select(self):
np.select(self.cond, [self.d, self.e])
def time_select_larger(self):
np.select(self.cond_large, ([self.d, self.e] * 10))
class Sort(Benchmark):
def setup(self):
self.e = np.arange(10000, dtype=np.float32)
self.o = np.arange(10001, dtype=np.float32)
def time_sort(self):
np.sort(self.e)
def time_sort_inplace(self):
self.e.sort()
def time_argsort(self):
self.e.argsort()
class Where(Benchmark):
def setup(self):
self.d = np.arange(20000)
self.e = self.d.copy()
self.cond = (self.d > 5000)
def time_1(self):
np.where(self.cond)
def time_2(self):
np.where(self.cond, self.d, self.e)
def time_2_broadcast(self):
np.where(self.cond, self.d, 0)
| bsd-3-clause |
ibmsoe/tensorflow | tensorflow/contrib/solvers/python/kernel_tests/lanczos_test.py | 128 | 3549 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.solvers.python.ops import lanczos
from tensorflow.contrib.solvers.python.ops import util
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test as test_lib
def _add_test(test, test_name, fn):
test_name = "_".join(["test", test_name])
if hasattr(test, test_name):
raise RuntimeError("Test %s defined more than once" % test_name)
setattr(test, test_name, fn)
class LanczosBidiagTest(test_lib.TestCase):
pass # Filled in below.
def _get_lanczos_tests(dtype_, use_static_shape_, shape_, orthogonalize_,
steps_):
def test_lanczos_bidiag(self):
np.random.seed(1)
a_np = np.random.uniform(
low=-1.0, high=1.0, size=np.prod(shape_)).reshape(shape_).astype(dtype_)
tol = 1e-12 if dtype_ == np.float64 else 1e-5
with self.test_session() as sess:
if use_static_shape_:
a = constant_op.constant(a_np)
else:
a = array_ops.placeholder(dtype_)
operator = util.create_operator(a)
lbd = lanczos.lanczos_bidiag(
operator, steps_, orthogonalize=orthogonalize_)
# The computed factorization should satisfy the equations
# A * V = U * B
# A' * U[:, :-1] = V * B[:-1, :]'
av = math_ops.matmul(a, lbd.v)
ub = lanczos.bidiag_matmul(lbd.u, lbd.alpha, lbd.beta, adjoint_b=False)
atu = math_ops.matmul(a, lbd.u[:, :-1], adjoint_a=True)
vbt = lanczos.bidiag_matmul(lbd.v, lbd.alpha, lbd.beta, adjoint_b=True)
if use_static_shape_:
av_val, ub_val, atu_val, vbt_val = sess.run([av, ub, atu, vbt])
else:
av_val, ub_val, atu_val, vbt_val = sess.run([av, ub, atu, vbt],
feed_dict={a: a_np})
self.assertAllClose(av_val, ub_val, atol=tol, rtol=tol)
self.assertAllClose(atu_val, vbt_val, atol=tol, rtol=tol)
return [test_lanczos_bidiag]
if __name__ == "__main__":
for dtype in np.float32, np.float64:
for shape in [[4, 4], [7, 4], [5, 8]]:
for orthogonalize in True, False:
for steps in range(1, min(shape) + 1):
for use_static_shape in True, False:
arg_string = "%s_%s_%s_%s_staticshape_%s" % (
dtype.__name__, "_".join(map(str, shape)), orthogonalize, steps,
use_static_shape)
for test_fn in _get_lanczos_tests(dtype, use_static_shape, shape,
orthogonalize, steps):
name = "_".join(["Lanczos", test_fn.__name__, arg_string])
_add_test(LanczosBidiagTest, name, test_fn)
test_lib.main()
| apache-2.0 |
aragos/tichu-tournament | python/openpyxl/styles/stylesheet.py | 1 | 7378 | from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
Alias,
Typed,
Sequence
)
from openpyxl.descriptors.sequence import NestedSequence
from openpyxl.descriptors.excel import ExtensionList
from openpyxl.utils.indexed_list import IndexedList
from openpyxl.xml.constants import ARC_STYLE, SHEET_MAIN_NS
from openpyxl.xml.functions import fromstring
from .colors import ColorList, COLOR_INDEX
from .differential import DifferentialStyle
from .table import TableStyleList
from .borders import Border
from .fills import Fill
from .fonts import Font
from .numbers import (
NumberFormatList,
BUILTIN_FORMATS,
BUILTIN_FORMATS_REVERSE
)
from .alignment import Alignment
from .protection import Protection
from .named_styles import (
NamedStyle,
NamedCellStyle,
NamedCellStyleList
)
from .cell_style import CellStyle, CellStyleList
class Stylesheet(Serialisable):
tagname = "styleSheet"
numFmts = Typed(expected_type=NumberFormatList)
fonts = NestedSequence(expected_type=Font, count=True)
fills = NestedSequence(expected_type=Fill, count=True)
borders = NestedSequence(expected_type=Border, count=True)
cellStyleXfs = Typed(expected_type=CellStyleList)
cellXfs = Typed(expected_type=CellStyleList)
cellStyles = Typed(expected_type=NamedCellStyleList)
dxfs = NestedSequence(expected_type=DifferentialStyle, count=True)
tableStyles = Typed(expected_type=TableStyleList, allow_none=True)
colors = Typed(expected_type=ColorList, allow_none=True)
extLst = Typed(expected_type=ExtensionList, allow_none=True)
__elements__ = ('numFmts', 'fonts', 'fills', 'borders', 'cellStyleXfs',
'cellXfs', 'cellStyles', 'dxfs', 'tableStyles', 'colors')
def __init__(self,
numFmts=None,
fonts=(),
fills=(),
borders=(),
cellStyleXfs=None,
cellXfs=None,
cellStyles=None,
dxfs=(),
tableStyles=None,
colors=None,
extLst=None,
):
if numFmts is None:
numFmts = NumberFormatList()
self.numFmts = numFmts
self.fonts = fonts
self.fills = fills
self.borders = borders
if cellStyleXfs is None:
cellStyleXfs = CellStyleList()
self.cellStyleXfs = cellStyleXfs
if cellXfs is None:
cellXfs = CellStyleList()
self.cellXfs = cellXfs
if cellStyles is None:
cellStyles = NamedCellStyleList()
self.cellStyles = cellStyles
self.dxfs = dxfs
self.tableStyles = tableStyles
self.colors = colors
self.cell_styles = self.cellXfs._to_array()
self.alignments = self.cellXfs.alignments
self.protections = self.cellXfs.prots
self._normalise_numbers()
self.named_styles = self._merge_named_styles()
@classmethod
def from_tree(cls, node):
# strip all attribs
attrs = dict(node.attrib)
for k in attrs:
del node.attrib[k]
return super(Stylesheet, cls).from_tree(node)
def _merge_named_styles(self):
"""
Merge named style names "cellStyles" with their associated styles "cellStyleXfs"
"""
named_styles = self.cellStyles.names
custom = self.custom_formats
formats = self.number_formats
for style in named_styles:
xf = self.cellStyleXfs[style.xfId]
style.font = self.fonts[xf.fontId]
style.fill = self.fills[xf.fillId]
style.border = self.borders[xf.borderId]
if xf.numFmtId in custom:
fmt = custom[xf.numFmtId]
style.numFmtId = formats.index(fmt) + 164
if xf.alignment:
style.alignment = xf.alignment
if xf.protection:
style.protection = xf.protection
return named_styles
def _split_named_styles(self, wb):
"""
Convert NamedStyle into separate CellStyle and Xf objects
"""
names = []
xfs = []
for idx, style in enumerate(wb._named_styles):
name = NamedCellStyle(
name=style.name,
builtinId=style.builtinId,
hidden=style.hidden,
xfId = idx
)
names.append(name)
xf = CellStyle()
xf.fontId = wb._fonts.add(style.font)
xf.borderId = wb._borders.add(style.border)
xf.fillId = wb._fills.add(style.fill)
fmt = style.number_format
if fmt in BUILTIN_FORMATS_REVERSE:
fmt = BUILTIN_FORMATS_REVERSE[fmt]
else:
fmt = wb._number_formats.add(style.number_format) + 164
xf.numFmtId = fmt
xfs.append(xf)
self.cellStyles.cellStyle = names
self.cellStyleXfs = CellStyleList(xf=xfs)
@property
def number_formats(self):
fmts = [n.formatCode for n in self.numFmts.numFmt]
return IndexedList(fmts)
@property
def custom_formats(self):
return dict([(n.numFmtId, n.formatCode) for n in self.numFmts.numFmt])
def _normalise_numbers(self):
"""
Rebase numFmtIds with a floor of 164
"""
custom = self.custom_formats
formats = self.number_formats
for style in self.cell_styles:
if style.numFmtId in custom:
fmt = custom[style.numFmtId]
style.numFmtId = formats.index(fmt) + 164
def apply_stylesheet(archive, wb):
"""
Add styles to workbook if present
"""
try:
src = archive.read(ARC_STYLE)
except KeyError:
return wb
node = fromstring(src)
stylesheet = Stylesheet.from_tree(node)
wb._cell_styles = stylesheet.cell_styles
wb._named_styles = stylesheet.named_styles
wb._borders = IndexedList(stylesheet.borders)
wb._fonts = IndexedList(stylesheet.fonts)
wb._fills = IndexedList(stylesheet.fills)
wb._differential_styles = IndexedList(stylesheet.dxfs)
wb._number_formats = stylesheet.number_formats
wb._protections = stylesheet.protections
wb._alignments = stylesheet.alignments
if stylesheet.colors is not None:
wb._colors = stylesheet.colors.index
def write_stylesheet(wb):
stylesheet = Stylesheet()
stylesheet.fonts = wb._fonts
stylesheet.fills = wb._fills
stylesheet.borders = wb._borders
stylesheet.dxfs = wb._differential_styles
from .numbers import NumberFormat
fmts = []
for idx, code in enumerate(wb._number_formats, 164):
fmt = NumberFormat(idx, code)
fmts.append(fmt)
stylesheet.numFmts.numFmt = fmts
xfs = []
for style in wb._cell_styles:
xf = CellStyle.from_array(style)
if style.alignmentId:
xf.alignment = wb._alignments[style.alignmentId]
if style.protectionId:
xf.protection = wb._protections[style.protectionId]
xfs.append(xf)
stylesheet.cellXfs = CellStyleList(xf=xfs)
stylesheet._split_named_styles(wb)
stylesheet.tableStyles = TableStyleList()
tree = stylesheet.to_tree()
tree.set("xmlns", SHEET_MAIN_NS)
return tree
| mit |
SnappleCap/oh-mainline | vendor/packages/PyYaml/lib3/yaml/__init__.py | 96 | 9607 |
from .error import *
from .tokens import *
from .events import *
from .nodes import *
from .loader import *
from .dumper import *
__version__ = '3.10'
try:
from .cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
import io
def scan(stream, Loader=Loader):
"""
Scan a YAML stream and produce scanning tokens.
"""
loader = Loader(stream)
try:
while loader.check_token():
yield loader.get_token()
finally:
loader.dispose()
def parse(stream, Loader=Loader):
"""
Parse a YAML stream and produce parsing events.
"""
loader = Loader(stream)
try:
while loader.check_event():
yield loader.get_event()
finally:
loader.dispose()
def compose(stream, Loader=Loader):
"""
Parse the first YAML document in a stream
and produce the corresponding representation tree.
"""
loader = Loader(stream)
try:
return loader.get_single_node()
finally:
loader.dispose()
def compose_all(stream, Loader=Loader):
"""
Parse all YAML documents in a stream
and produce corresponding representation trees.
"""
loader = Loader(stream)
try:
while loader.check_node():
yield loader.get_node()
finally:
loader.dispose()
def load(stream, Loader=Loader):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
"""
loader = Loader(stream)
try:
return loader.get_single_data()
finally:
loader.dispose()
def load_all(stream, Loader=Loader):
"""
Parse all YAML documents in a stream
and produce corresponding Python objects.
"""
loader = Loader(stream)
try:
while loader.check_data():
yield loader.get_data()
finally:
loader.dispose()
def safe_load(stream):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
Resolve only basic YAML tags.
"""
return load(stream, SafeLoader)
def safe_load_all(stream):
"""
Parse all YAML documents in a stream
and produce corresponding Python objects.
Resolve only basic YAML tags.
"""
return load_all(stream, SafeLoader)
def emit(events, stream=None, Dumper=Dumper,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None):
"""
Emit YAML parsing events into a stream.
If stream is None, return the produced string instead.
"""
getvalue = None
if stream is None:
stream = io.StringIO()
getvalue = stream.getvalue
dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
allow_unicode=allow_unicode, line_break=line_break)
try:
for event in events:
dumper.emit(event)
finally:
dumper.dispose()
if getvalue:
return getvalue()
def serialize_all(nodes, stream=None, Dumper=Dumper,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None):
"""
Serialize a sequence of representation trees into a YAML stream.
If stream is None, return the produced string instead.
"""
getvalue = None
if stream is None:
if encoding is None:
stream = io.StringIO()
else:
stream = io.BytesIO()
getvalue = stream.getvalue
dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
allow_unicode=allow_unicode, line_break=line_break,
encoding=encoding, version=version, tags=tags,
explicit_start=explicit_start, explicit_end=explicit_end)
try:
dumper.open()
for node in nodes:
dumper.serialize(node)
dumper.close()
finally:
dumper.dispose()
if getvalue:
return getvalue()
def serialize(node, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a representation tree into a YAML stream.
If stream is None, return the produced string instead.
"""
return serialize_all([node], stream, Dumper=Dumper, **kwds)
def dump_all(documents, stream=None, Dumper=Dumper,
default_style=None, default_flow_style=None,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None):
"""
Serialize a sequence of Python objects into a YAML stream.
If stream is None, return the produced string instead.
"""
getvalue = None
if stream is None:
if encoding is None:
stream = io.StringIO()
else:
stream = io.BytesIO()
getvalue = stream.getvalue
dumper = Dumper(stream, default_style=default_style,
default_flow_style=default_flow_style,
canonical=canonical, indent=indent, width=width,
allow_unicode=allow_unicode, line_break=line_break,
encoding=encoding, version=version, tags=tags,
explicit_start=explicit_start, explicit_end=explicit_end)
try:
dumper.open()
for data in documents:
dumper.represent(data)
dumper.close()
finally:
dumper.dispose()
if getvalue:
return getvalue()
def dump(data, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
"""
return dump_all([data], stream, Dumper=Dumper, **kwds)
def safe_dump_all(documents, stream=None, **kwds):
"""
Serialize a sequence of Python objects into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead.
"""
return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
def safe_dump(data, stream=None, **kwds):
"""
Serialize a Python object into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead.
"""
return dump_all([data], stream, Dumper=SafeDumper, **kwds)
def add_implicit_resolver(tag, regexp, first=None,
Loader=Loader, Dumper=Dumper):
"""
Add an implicit scalar detector.
If an implicit scalar value matches the given regexp,
the corresponding tag is assigned to the scalar.
first is a sequence of possible initial characters or None.
"""
Loader.add_implicit_resolver(tag, regexp, first)
Dumper.add_implicit_resolver(tag, regexp, first)
def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
"""
Add a path based resolver for the given tag.
A path is a list of keys that forms a path
to a node in the representation tree.
Keys can be string values, integers, or None.
"""
Loader.add_path_resolver(tag, path, kind)
Dumper.add_path_resolver(tag, path, kind)
def add_constructor(tag, constructor, Loader=Loader):
"""
Add a constructor for the given tag.
Constructor is a function that accepts a Loader instance
and a node object and produces the corresponding Python object.
"""
Loader.add_constructor(tag, constructor)
def add_multi_constructor(tag_prefix, multi_constructor, Loader=Loader):
"""
Add a multi-constructor for the given tag prefix.
Multi-constructor is called for a node if its tag starts with tag_prefix.
Multi-constructor accepts a Loader instance, a tag suffix,
and a node object and produces the corresponding Python object.
"""
Loader.add_multi_constructor(tag_prefix, multi_constructor)
def add_representer(data_type, representer, Dumper=Dumper):
"""
Add a representer for the given type.
Representer is a function accepting a Dumper instance
and an instance of the given data type
and producing the corresponding representation node.
"""
Dumper.add_representer(data_type, representer)
def add_multi_representer(data_type, multi_representer, Dumper=Dumper):
"""
Add a representer for the given type.
Multi-representer is a function accepting a Dumper instance
and an instance of the given data type or subtype
and producing the corresponding representation node.
"""
Dumper.add_multi_representer(data_type, multi_representer)
class YAMLObjectMetaclass(type):
"""
The metaclass for YAMLObject.
"""
def __init__(cls, name, bases, kwds):
super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml)
cls.yaml_dumper.add_representer(cls, cls.to_yaml)
class YAMLObject(metaclass=YAMLObjectMetaclass):
"""
An object that can dump itself to a YAML stream
and load itself from a YAML stream.
"""
__slots__ = () # no direct instantiation, so allow immutable subclasses
yaml_loader = Loader
yaml_dumper = Dumper
yaml_tag = None
yaml_flow_style = None
@classmethod
def from_yaml(cls, loader, node):
"""
Convert a representation node to a Python object.
"""
return loader.construct_yaml_object(node, cls)
@classmethod
def to_yaml(cls, dumper, data):
"""
Convert a Python object to a representation node.
"""
return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
flow_style=cls.yaml_flow_style)
| agpl-3.0 |
kostoulhs/android_kernel_samsung_expressltexx | Documentation/networking/cxacru-cf.py | 14668 | 1626 | #!/usr/bin/env python
# Copyright 2009 Simon Arlott
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Usage: cxacru-cf.py < cxacru-cf.bin
# Output: values string suitable for the sysfs adsl_config attribute
#
# Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110
# contains mis-aligned values which will stop the modem from being able
# to make a connection. If the first and last two bytes are removed then
# the values become valid, but the modulation will be forced to ANSI
# T1.413 only which may not be appropriate.
#
# The original binary format is a packed list of le32 values.
import sys
import struct
i = 0
while True:
buf = sys.stdin.read(4)
if len(buf) == 0:
break
elif len(buf) != 4:
sys.stdout.write("\n")
sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf)))
sys.exit(1)
if i > 0:
sys.stdout.write(" ")
sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0]))
i += 1
sys.stdout.write("\n")
| gpl-2.0 |
jsseb/gcode_parser | test.py | 1 | 2801 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Generate Gcode for Lissajous Curve
Future ref will generate Gcode for other curves
Test range : [1,1 + np.pi,0.1]
Test delta : 0
'''
import numpy as np
import argparse
try:
import matplotlib.pyplot as plt
except ImportError:
pass
def lissajous(a,b,rng,delta=None):
X = []
Y = []
if delta == None:
delta = ((b-1)/b) * np.pi/2
N = (rng[1]-rng[0])/rng[2]
for t in np.linspace(rng[0], rng[1], num=N):
#X = a*sin(a*t + delta)
#Y = b*sin(b*t)
X.append(a*np.sin(a*t + delta))
Y.append(b*np.sin(b*t))
curve = [X,Y]
return curve
def squares(a,b,n,d,change):
X = []
Y = []
x = a
y = b
l = d
for i in range(n):
X.append(x)
Y.append(y)
X.append(x+l)
Y.append(y)
X.append(x+l)
Y.append(y-l)
X.append(x)
Y.append(y-l)
X.append(x)
Y.append(y)
x = x+change
y = y-change
l = l-2*change
return [X,Y]
def lines(x,y,n,d,change):
X = []
Y = []
for i in range(n):
X.append(x+2*i)
Y.append(y)
X.append(x+2*i)
Y.append(y+d+i*change)
return [X,Y]
def print_data(curve,filename=None):
n = [[x,y] for x,y in zip(curve[0],curve[1])]
if filename is None:
f = open('lissa.txt','w')
else:
f = open(filename,'w')
n = str(n)
n = n.replace('[','')
n = n.replace(',','')
n = n.replace(']','\n')
n = n.replace('\'','')
f.write("{}".format(n))
f.close()
def plot_data(curve):
plt.plot(curve[0],curve[1],'-')
plt.show()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Prints and Plots the Lissajous Knot')
parser.add_argument('--x',dest='x',required=True)
parser.add_argument('--y',dest='y',required=True)
parser.add_argument('--c',dest='c',required=False)
parser.add_argument('--d',dest='d',required=False)
parser.add_argument('--n',dest='n',required=False)
parser.add_argument('--delta',dest='delta',required=False)
parser.add_argument('--precission',dest='precission',required=False)
parser.add_argument('--o',dest='option',required=True)
parser.add_argument('--plot',dest='plot',required=False)
parser.add_argument('--print',dest='file',required=False)
parser.add_argument('--output',dest='filename',required=False)
args = parser.parse_args()
if args.precission is None:
precission = 0.01
else:
precission = float(args.precission)
if args.x is not None and args.y is not None:
if args.option == 'squares':
points = squares(int(args.x),int(args.y),int(args.n),int(args.d),int(args.c))
if args.option == 'lines':
points = lines(int(args.x),int(args.y),int(args.n),int(args.d),int(args.c))
if args.option == 'lissa':
points = lissajous(int(args.x),int(args.y),[0,2*np.pi, precission],delta = args.delta)
if args.file is not None:
print_data(points,filename=args.filename)
if args.plot is not None:
plot_data(points) | mit |
ptemplier/ansible | lib/ansible/modules/cloud/vmware/vmware_dvs_host.py | 29 | 8384 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_dvs_host
short_description: Add or remove a host from distributed virtual switch
description:
- Add or remove a host from distributed virtual switch
version_added: 2.0
author: "Joseph Callen (@jcpowermac)"
notes:
- Tested on vSphere 5.5
requirements:
- "python >= 2.7"
- PyVmomi
options:
esxi_hostname:
description:
- The ESXi hostname
required: True
switch_name:
description:
- The name of the Distributed vSwitch
required: True
vmnics:
description:
- The ESXi hosts vmnics to use with the Distributed vSwitch
required: True
state:
description:
- If the host should be present or absent attached to the vSwitch
choices: ['present', 'absent']
required: True
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
# Example vmware_dvs_host command from Ansible Playbooks
- name: Add Host to dVS
local_action:
module: vmware_dvs_host
hostname: vcenter_ip_or_hostname
username: vcenter_username
password: vcenter_password
esxi_hostname: esxi_hostname_as_listed_in_vcenter
switch_name: dvSwitch
vmnics:
- vmnic0
- vmnic1
state: present
'''
try:
from collections import Counter
HAS_COLLECTIONS_COUNTER = True
except ImportError:
HAS_COLLECTIONS_COUNTER = False
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import (HAS_PYVMOMI, connect_to_api, find_dvs_by_name,
find_hostsystem_by_name, vmware_argument_spec, wait_for_task)
class VMwareDvsHost(object):
def __init__(self, module):
self.module = module
self.dv_switch = None
self.uplink_portgroup = None
self.host = None
self.dv_switch = None
self.nic = None
self.content = connect_to_api(self.module)
self.state = self.module.params['state']
self.switch_name = self.module.params['switch_name']
self.esxi_hostname = self.module.params['esxi_hostname']
self.vmnics = self.module.params['vmnics']
def process_state(self):
try:
dvs_host_states = {
'absent': {
'present': self.state_destroy_dvs_host,
'absent': self.state_exit_unchanged,
},
'present': {
'update': self.state_update_dvs_host,
'present': self.state_exit_unchanged,
'absent': self.state_create_dvs_host,
}
}
dvs_host_states[self.state][self.check_dvs_host_state()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def find_dvspg_by_name(self):
portgroups = self.dv_switch.portgroup
for pg in portgroups:
if pg.name == self.portgroup_name:
return pg
return None
def find_dvs_uplink_pg(self):
# There should only always be a single uplink port group on
# a distributed virtual switch
if len(self.dv_switch.config.uplinkPortgroup):
return self.dv_switch.config.uplinkPortgroup[0]
else:
return None
# operation should be edit, add and remove
def modify_dvs_host(self, operation):
spec = vim.DistributedVirtualSwitch.ConfigSpec()
spec.configVersion = self.dv_switch.config.configVersion
spec.host = [vim.dvs.HostMember.ConfigSpec()]
spec.host[0].operation = operation
spec.host[0].host = self.host
if operation in ("edit", "add"):
spec.host[0].backing = vim.dvs.HostMember.PnicBacking()
count = 0
for nic in self.vmnics:
spec.host[0].backing.pnicSpec.append(vim.dvs.HostMember.PnicSpec())
spec.host[0].backing.pnicSpec[count].pnicDevice = nic
spec.host[0].backing.pnicSpec[count].uplinkPortgroupKey = self.uplink_portgroup.key
count += 1
task = self.dv_switch.ReconfigureDvs_Task(spec)
changed, result = wait_for_task(task)
return changed, result
def state_destroy_dvs_host(self):
operation = "remove"
changed = True
result = None
if not self.module.check_mode:
changed, result = self.modify_dvs_host(operation)
self.module.exit_json(changed=changed, result=str(result))
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def state_update_dvs_host(self):
operation = "edit"
changed = True
result = None
if not self.module.check_mode:
changed, result = self.modify_dvs_host(operation)
self.module.exit_json(changed=changed, result=str(result))
def state_create_dvs_host(self):
operation = "add"
changed = True
result = None
if not self.module.check_mode:
changed, result = self.modify_dvs_host(operation)
self.module.exit_json(changed=changed, result=str(result))
def find_host_attached_dvs(self):
for dvs_host_member in self.dv_switch.config.host:
if dvs_host_member.config.host.name == self.esxi_hostname:
return dvs_host_member.config.host
return None
def check_uplinks(self):
pnic_device = []
for dvs_host_member in self.dv_switch.config.host:
if dvs_host_member.config.host == self.host:
for pnicSpec in dvs_host_member.config.backing.pnicSpec:
pnic_device.append(pnicSpec.pnicDevice)
return Counter(pnic_device) == Counter(self.vmnics)
def check_dvs_host_state(self):
self.dv_switch = find_dvs_by_name(self.content, self.switch_name)
if self.dv_switch is None:
raise Exception("A distributed virtual switch %s does not exist" % self.switch_name)
self.uplink_portgroup = self.find_dvs_uplink_pg()
if self.uplink_portgroup is None:
raise Exception("An uplink portgroup does not exist on the distributed virtual switch %s"
% self.switch_name)
self.host = self.find_host_attached_dvs()
if self.host is None:
# We still need the HostSystem object to add the host
# to the distributed vswitch
self.host = find_hostsystem_by_name(self.content, self.esxi_hostname)
if self.host is None:
self.module.fail_json(msg="The esxi_hostname %s does not exist in vCenter" % self.esxi_hostname)
return 'absent'
else:
if self.check_uplinks():
return 'present'
else:
return 'update'
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(esxi_hostname=dict(required=True, type='str'),
switch_name=dict(required=True, type='str'),
vmnics=dict(required=True, type='list'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_PYVMOMI:
module.fail_json(msg='pyvmomi is required for this module')
if not HAS_COLLECTIONS_COUNTER:
module.fail_json(msg='collections.Counter from Python-2.7 is required for this module')
vmware_dvs_host = VMwareDvsHost(module)
vmware_dvs_host.process_state()
if __name__ == '__main__':
main()
| gpl-3.0 |
Ocramius/FrameworkBenchmarks | activeweb/setup.py | 6 | 1700 |
import subprocess
import sys
import os
import setup_util
def start(args, logfile, errfile):
setup_util.replace_text("activeweb/src/main/webapp/WEB-INF/resin-web.xml", "localhost", args.database_host)
setup_util.replace_text("activeweb/src/main/java/app/config/DbConfig.java", "localhost", args.database_host)
try:
subprocess.check_call("mvn clean package", shell=True, cwd="activeweb", stderr=errfile, stdout=logfile)
if os.name == 'nt':
subprocess.check_call("rmdir /s /q C:\\Java\\resin\\webapps", shell=True, stderr=errfile, stdout=logfile)
subprocess.check_call("mkdir C:\\Java\\resin\\webapps", shell=True, stderr=errfile, stdout=logfile)
subprocess.check_call("cp activeweb\\target\\activeweb.war C:\\Java\\resin\\webapps\\activeweb.war", shell=True, stderr=errfile, stdout=logfile)
subprocess.check_call("C:\\Java\\resin\\bin\\start.bat", shell=True, stderr=errfile, stdout=logfile)
return 0
subprocess.check_call("rm -rf $RESIN_HOME/webapps/*", shell=True, stderr=errfile, stdout=logfile)
subprocess.check_call("cp activeweb/target/activeweb.war $RESIN_HOME/webapps/", shell=True, stderr=errfile, stdout=logfile)
subprocess.check_call("$RESIN_HOME/bin/resinctl start", shell=True, stderr=errfile, stdout=logfile)
return 0
except subprocess.CalledProcessError:
return 1
def stop(logfile, errfile):
try:
if os.name == 'nt':
subprocess.check_call("C:\\Java\\resin\\bin\\stop.bat", shell=True, stderr=errfile, stdout=logfile)
return 0
subprocess.check_call("$RESIN_HOME/bin/resinctl shutdown", shell=True, stderr=errfile, stdout=logfile)
return 0
except subprocess.CalledProcessError:
return 1
| bsd-3-clause |
ForestMars/ks | sites/all/themes/bismuth/assets/plugins/vector-map/converter/converter.py | 97 | 10296 | #
# jVectorMap version 1.2.2
#
# Copyright 2011-2013, Kirill Lebedev
# Licensed under the MIT license.
#
import argparse
import sys
from osgeo import ogr
from osgeo import osr
import json
import shapely.geometry
import codecs
class Map:
def __init__(self, name, language):
self.paths = {}
self.name = name
self.language = language
self.width = 0
self.heoght = 0
self.bbox = []
def addPath(self, path, code, name):
self.paths[code] = {"path": path, "name": name}
def getJSCode(self):
map = {"paths": self.paths, "width": self.width, "height": self.height, "insets": self.insets, "projection": self.projection}
return "jQuery.fn.vectorMap('addMap', '"+self.name+"_"+self.projection['type']+"_"+self.language+"',"+json.dumps(map)+');'
class Converter:
def __init__(self, args):
self.map = Map(args['name'], args.get('language'))
if args.get('sources'):
self.sources = args['sources']
else:
self.sources = [{
'input_file': args.get('input_file'),
'where': args.get('where'),
'codes_file': args.get('codes_file'),
'country_name_index': args.get('country_name_index'),
'country_code_index': args.get('country_code_index'),
'input_file_encoding': args.get('input_file_encoding')
}]
default_source = {
'where': '',
'codes_file': '',
'country_name_index': '0',
'country_code_index': '1',
'input_file_encoding': 'iso-8859-1'
}
for index in range(len(self.sources)):
for key in default_source:
if self.sources[index].get(key) is None:
self.sources[index][key] = default_source[key]
self.features = {}
self.width = args.get('width')
self.minimal_area = args.get('minimal_area')
self.longitude0 = args.get('longitude0')
self.projection = args.get('projection')
self.precision = args.get('precision')
self.buffer_distance = args.get('buffer_distance')
self.simplify_tolerance = args.get('simplify_tolerance')
if args.get('viewport'):
self.viewport = map(lambda s: float(s), args.get('viewport').split(' '))
else:
self.viewport = False
# spatial reference to convert to
self.spatialRef = osr.SpatialReference()
self.spatialRef.ImportFromProj4('+proj='+self.projection+' +a=6381372 +b=6381372 +lat_0=0 +lon_0='+str(self.longitude0))
# handle map insets
if args.get('insets'):
self.insets = json.loads(args.get('insets'))
else:
self.insets = []
def loadData(self):
for sourceConfig in self.sources:
self.loadDataSource( sourceConfig )
def loadDataSource(self, sourceConfig):
source = ogr.Open( sourceConfig['input_file'] )
layer = source.GetLayer(0)
layer.SetAttributeFilter( sourceConfig['where'].encode('ascii') )
self.viewportRect = False
if self.viewport:
layer.SetSpatialFilterRect( *sourceConfig.get('viewport') )
transformation = osr.CoordinateTransformation( layer.GetSpatialRef(), self.spatialRef )
point1 = transformation.TransformPoint(self.viewport[0], self.viewport[1])
point2 = transformation.TransformPoint(self.viewport[2], self.viewport[3])
self.viewportRect = shapely.geometry.box(point1[0], point1[1], point2[0], point2[1])
layer.ResetReading()
# load codes from external tsv file if present or geodata file otherwise
codes = {}
if sourceConfig.get('codes_file'):
for line in codecs.open(sourceConfig.get('codes_file'), 'r', "utf-8"):
row = map(lambda s: s.strip(), line.split('\t'))
codes[row[1]] = row[0]
else:
nextCode = 0
for feature in layer:
code = feature.GetFieldAsString(sourceConfig.get('country_code_index'))
if code == '-99':
code = '_'+str(nextCode)
nextCode += 1
name = feature.GetFieldAsString(sourceConfig.get('country_name_index')).decode(sourceConfig.get('input_file_encoding'))
codes[name] = code
layer.ResetReading()
# load features
for feature in layer:
geometry = feature.GetGeometryRef()
geometryType = geometry.GetGeometryType()
if geometryType == ogr.wkbPolygon or geometryType == ogr.wkbMultiPolygon:
geometry.TransformTo( self.spatialRef )
shapelyGeometry = shapely.wkb.loads( geometry.ExportToWkb() )
if not shapelyGeometry.is_valid:
#buffer to fix selfcrosses
shapelyGeometry = shapelyGeometry.buffer(0, 1)
shapelyGeometry = self.applyFilters(shapelyGeometry)
if shapelyGeometry:
name = feature.GetFieldAsString(sourceConfig.get('country_name_index')).decode(sourceConfig.get('input_file_encoding'))
code = codes[name]
self.features[code] = {"geometry": shapelyGeometry, "name": name, "code": code}
else:
raise Exception, "Wrong geometry type: "+geometryType
def convert(self, outputFile):
self.loadData()
codes = self.features.keys()
self.map.insets = []
envelope = []
for inset in self.insets:
insetBbox = self.renderMapInset(inset['codes'], inset['left'], inset['top'], inset['width'])
insetHeight = (insetBbox[3] - insetBbox[1]) * (inset['width'] / (insetBbox[2] - insetBbox[0]))
self.map.insets.append({
"bbox": [{"x": insetBbox[0], "y": -insetBbox[3]}, {"x": insetBbox[2], "y": -insetBbox[1]}],
"left": inset['left'],
"top": inset['top'],
"width": inset['width'],
"height": insetHeight
})
envelope.append(
shapely.geometry.box(
inset['left'], inset['top'], inset['left'] + inset['width'], inset['top'] + insetHeight
)
)
for code in inset['codes']:
codes.remove(code)
insetBbox = self.renderMapInset(codes, 0, 0, self.width)
insetHeight = (insetBbox[3] - insetBbox[1]) * (self.width / (insetBbox[2] - insetBbox[0]))
envelope.append( shapely.geometry.box( 0, 0, self.width, insetHeight ) )
mapBbox = shapely.geometry.MultiPolygon( envelope ).bounds
self.map.width = mapBbox[2] - mapBbox[0]
self.map.height = mapBbox[3] - mapBbox[1]
self.map.insets.append({
"bbox": [{"x": insetBbox[0], "y": -insetBbox[3]}, {"x": insetBbox[2], "y": -insetBbox[1]}],
"left": 0,
"top": 0,
"width": self.width,
"height": insetHeight
})
self.map.projection = {"type": self.projection, "centralMeridian": float(self.longitude0)}
open(outputFile, 'w').write( self.map.getJSCode() )
def renderMapInset(self, codes, left, top, width):
envelope = []
for code in codes:
envelope.append( self.features[code]['geometry'].envelope )
bbox = shapely.geometry.MultiPolygon( envelope ).bounds
scale = (bbox[2]-bbox[0]) / width
# generate SVG paths
for code in codes:
feature = self.features[code]
geometry = feature['geometry']
if self.buffer_distance:
geometry = geometry.buffer(self.buffer_distance*scale, 1)
if geometry.is_empty:
continue
if self.simplify_tolerance:
geometry = geometry.simplify(self.simplify_tolerance, preserve_topology=True)
if isinstance(geometry, shapely.geometry.multipolygon.MultiPolygon):
polygons = geometry.geoms
else:
polygons = [geometry]
path = ''
for polygon in polygons:
rings = []
rings.append(polygon.exterior)
rings.extend(polygon.interiors)
for ring in rings:
for pointIndex in range( len(ring.coords) ):
point = ring.coords[pointIndex]
if pointIndex == 0:
path += 'M'+str( round( (point[0]-bbox[0]) / scale + left, self.precision) )
path += ','+str( round( (bbox[3] - point[1]) / scale + top, self.precision) )
else:
path += 'l' + str( round(point[0]/scale - ring.coords[pointIndex-1][0]/scale, self.precision) )
path += ',' + str( round(ring.coords[pointIndex-1][1]/scale - point[1]/scale, self.precision) )
path += 'Z'
self.map.addPath(path, feature['code'], feature['name'])
return bbox
def applyFilters(self, geometry):
if self.viewportRect:
geometry = self.filterByViewport(geometry)
if not geometry:
return False
if self.minimal_area:
geometry = self.filterByMinimalArea(geometry)
if not geometry:
return False
return geometry
def filterByViewport(self, geometry):
try:
return geometry.intersection(self.viewportRect)
except shapely.geos.TopologicalError:
return False
def filterByMinimalArea(self, geometry):
if isinstance(geometry, shapely.geometry.multipolygon.MultiPolygon):
polygons = geometry.geoms
else:
polygons = [geometry]
polygons = filter(lambda p: p.area > self.minimal_area, polygons)
return shapely.geometry.multipolygon.MultiPolygon(polygons)
parser = argparse.ArgumentParser(conflict_handler='resolve')
parser.add_argument('input_file')
parser.add_argument('output_file')
parser.add_argument('--country_code_index', type=int)
parser.add_argument('--country_name_index', type=int)
parser.add_argument('--codes_file', type=str)
parser.add_argument('--where', type=str)
parser.add_argument('--width', type=float)
parser.add_argument('--insets', type=str)
parser.add_argument('--minimal_area', type=float)
parser.add_argument('--buffer_distance', type=float)
parser.add_argument('--simplify_tolerance', type=float)
parser.add_argument('--viewport', type=str)
parser.add_argument('--longitude0', type=str)
parser.add_argument('--projection', type=str)
parser.add_argument('--name', type=str)
parser.add_argument('--language', type=str)
parser.add_argument('--input_file_encoding', type=str)
parser.add_argument('--precision', type=int)
args = vars(parser.parse_args())
default_args = {
'buffer_distance': -0.4,
'longitude0': '0',
'projection': 'mill',
'name': 'world',
'language': 'en',
'precision': 2,
'insets': ''
}
if args['input_file'][-4:] == 'json':
args.update( json.loads( open(args['input_file'], 'r').read() ) )
for key in default_args:
if default_args.get(key) and args.get(key) is None:
args[key] = default_args[key]
converter = Converter(args)
converter.convert(args['output_file']) | gpl-2.0 |
jboes/CatKit | catkit/pawprint/db.py | 1 | 8899 | import numpy as np
import sqlite3
from sqlite3 import IntegrityError
class FingerprintDB():
"""A class for accessing a temporary SQLite database. This
function works as a context manager and should be used as follows:
with FingerprintDB() as fpdb:
(Perform operation here)
This syntax will automatically construct the temporary database,
or access an existing one. Upon exiting the indentation, the
changes to the database will be automatically committed.
"""
def __init__(self, db_name='fingerprints.db', verbose=False):
"""Initialize the database.
Parameters
----------
db_name : str
Name of the database file to access.
verbose : bool
Print additional information
"""
self.db_name = db_name
self.verbose = verbose
def __enter__(self):
"""This function is automatically called whenever the class
is used together with a 'with' statement.
"""
self.con = sqlite3.connect(self.db_name)
self.c = self.con.cursor()
self.create_table()
return self
def __exit__(self, type, value, tb):
"""Upon exiting the 'with' statement, __exit__ is called."""
self.con.commit()
self.con.close()
def create_table(self):
"""Creates the database table framework used in SQLite.
This includes 3 tables: images, parameters, and fingerprints.
The images table currently stores ase_id information and
a unqiue string. This can be adapted in the future to support
atoms objects.
The parameters table stores a symbol (10 character maximum)
for convenient reference and a description of the parameter.
The fingerprints table holds a unique image and parmeter ID
along with a float value for each. The ID pair must be unique.
"""
self.c.execute("""CREATE TABLE IF NOT EXISTS images(
iid INTEGER PRIMARY KEY AUTOINCREMENT,
ase_id CHAR(32) UNIQUE NOT NULL,
identity TEXT
)""")
self.c.execute("""CREATE TABLE IF NOT EXISTS parameters(
pid INTEGER PRIMARY KEY AUTOINCREMENT,
symbol CHAR(10) UNIQUE NOT NULL,
description TEXT
)""")
self.c.execute("""CREATE TABLE IF NOT EXISTS fingerprints(
entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
image_id INT NOT NULL,
param_id INT NOT NULL,
value REAL,
FOREIGN KEY(image_id) REFERENCES images(image_id)
ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY(param_id) REFERENCES parameters(param_id)
ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE(image_id, param_id)
)""")
def image_entry(self, d, identity=None):
"""Enters a single ase-db image into the fingerprint database.
The ase-db ID with identity must be unique. If not, it will be skipped.
This table can be expanded to contain atoms objects in the future.
Parameters
----------
d : ase-db object
Database entry to parse.
identity : str
An identifier of the users choice.
Returns
-------
ase_id : int
The ase id collected.
"""
ase_id = d.id
try:
self.c.execute("""INSERT INTO images (ase_id, identity)
VALUES(?, ?)""", (ase_id, identity))
except (IntegrityError):
if self.verbose:
print('ASE ID with identifier already defined: {} {}'.format(
ase_id, identity))
return ase_id
def parameter_entry(self, symbol=None, description=None):
"""Enters a unique parameter into the database.
Parameters
----------
symbol : str
A unique symbol the entry can be referenced by. If None,
the symbol will be the ID of the parameter
as a string.
description : str
A description of the parameter.
"""
if not symbol:
self.c.execute("""SELECT MAX(pid) FROM parameters""")
symbol = str(int(self.c.fetchone()[0]) + 1)
# The symbol must be unique. If not, it will be skipped.
try:
self.c.execute("""INSERT INTO parameters (symbol, description)
VALUES(?, ?)""", (symbol, description))
except (IntegrityError):
if self.verbose:
print('Symbol already defined: {}'.format(symbol))
# Each instance needs to be commited to ensure no overwriting.
# This could potentially result in slowdown.
self.con.commit()
def get_parameters(self, selection=None, display=False):
"""Get an array of integer values which correspond to the
parameter IDs for a set of provided symbols.
Parameters
----------
selection : list
Symbols in parameters table to be selected. If no selection
is made, return all parameters.
display : bool
Print parameter descriptions.
Returns
-------
parameter_ids : array (n,)
Integer values of selected parameters.
"""
if not selection:
self.c.execute("""SELECT pid, symbol, description
FROM parameters""")
res = self.c.fetchall()
else:
res = []
for i, s in enumerate(selection):
self.c.execute("""SELECT pid, symbol, description
FROM parameters WHERE symbol = '{}'""".format(s))
res += [self.c.fetchone()]
if display:
print('[ID ]: key - Description')
print('---------------------------')
for r in res:
print('[{0:^3}]: {1:<10} - {2}'.format(*r))
parameter_ids = np.array(res).T[0].astype(int)
return parameter_ids
def fingerprint_entry(self, ase_id, param_id, value):
"""Enters a fingerprint value to the database for a given ase and
parameter id.
Parameters
----------
ase_id : int
The unique id associated with an atoms object in the database.
param_id : int or str
The parameter ID or symbol associated with and entry in the
parameters table.
value : float
The value of the parameter for the atoms object.
"""
# If parameter symbol is given, get the ID
if isinstance(param_id, str):
self.c.execute("""SELECT pid FROM parameters
WHERE symbol = '{}'""".format(param_id))
param_id = self.c.fetchone()
if param_id:
param_id = param_id[0]
else:
raise (KeyError, 'parameter symbol not found')
self.c.execute("""SELECT iid FROM images
WHERE ase_id = {}""".format(ase_id))
image_id = self.c.fetchone()[0]
self.c.execute("""INSERT INTO fingerprints (image_id, param_id, value)
VALUES(?, ?, ?)""", (int(image_id), int(param_id), float(value)))
def get_fingerprints(self, ase_ids=None, params=[]):
"""Get the array of values associated with the provided parameters
for each ase_id.
Parameters
----------
ase_id : list
The ase-id associated with an atoms object in the database.
params : list
List of symbols or int in parameters table to be selected.
Returns
-------
fingerprint : array (n,)
An array of values associated with the given parameters
(a fingerprint) for each ase_id.
"""
if isinstance(params, np.ndarray):
params = params.tolist()
if not params or isinstance(params[0], str):
params = self.get_parameters(selection=params)
psel = ','.join(params.astype(str))
elif isinstance(params[0], int):
psel = ','.join(np.array(params).astype(str))
if ase_ids is None:
cmd = """SELECT GROUP_CONCAT(IFNULL(value, 'nan')) FROM
fingerprints JOIN images on fingerprints.image_id = images.iid
WHERE param_id IN ({})
GROUP BY ase_id
ORDER BY images.iid""".format(psel)
else:
asel = ','.join(np.array(ase_ids).astype(str))
cmd = """SELECT GROUP_CONCAT(IFNULL(value, 'nan')) FROM
fingerprints JOIN images on fingerprints.image_id = images.iid
WHERE param_id IN ({}) AND ase_id IN ({})
GROUP BY ase_id""".format(psel, asel)
self.c.execute(cmd)
fetch = self.c.fetchall()
fingerprint = np.zeros((len(fetch), len(params)))
for i, f in enumerate(fetch):
fingerprint[i] = f[0].split(',')
return fingerprint
| gpl-3.0 |
tkdchen/Nitrate | src/tests/core/test_ajax.py | 2 | 37813 | # -*- coding: utf-8 -*-
import json
from collections.abc import Iterable
from http import HTTPStatus
from operator import itemgetter
from textwrap import dedent
from typing import Optional, List, Union, Dict, Any
from unittest.mock import patch
import pytest
from bs4 import BeautifulSoup
from django import test
from django.contrib.auth.models import User
from django.core import mail, serializers
from django.core.mail import EmailMessage
from django.db.models import Max
from django.http import QueryDict
from django.urls import reverse
from tcms.core.ajax import strip_parameters, SORT_KEY_MAX, SORT_KEY_RANGE
from tcms.logs.models import TCMSLogModel
from tcms.management.models import (
Component,
Priority,
TCMSEnvGroup,
TCMSEnvProperty,
TCMSEnvValue,
TestBuild,
TestEnvironment,
TestTag,
Version,
)
from tcms.testcases.models import TestCase, TestCaseStatus, TestCasePlan, TestCaseCategory
from tcms.testruns.models import TestCaseRun, TestCaseRunStatus
from tests import factories as f, BasePlanCase, BaseCaseRun, remove_perm_from_user, BaseDataContext
from tests import AuthMixin, HelperAssertions, user_should_have_perm
@pytest.mark.parametrize(
"data,skip_params,expected",
[
[{}, ["type"], {}],
[QueryDict(""), ["type"], {}],
[{"name": "abc"}, [], {"name": "abc"}],
[{"name": "abc"}, ["type"], {"name": "abc"}],
[{"name": "abc", "type": ""}, ["type"], {"name": "abc"}],
[{"name": "", "type": ""}, ["type"], {}],
[QueryDict("lang=py&ver=3.9&info="), ["ver"], {"lang": "py"}],
[QueryDict("lang=py&ver=3.9&info="), ("ver",), {"lang": "py"}],
],
)
def test_strip_parameters(
data: Union[QueryDict, Dict[str, Any]], skip_params: Iterable, expected: Dict[str, Any]
):
assert expected == strip_parameters(data, skip_params)
class TestChangeCaseRunAssignee(BaseCaseRun):
"""Test AJAX request to change case runs' assignee"""
auto_login = True
@classmethod
def setUpTestData(cls):
super().setUpTestData()
user_should_have_perm(cls.tester, "testruns.change_testcaserun")
cls.assignee = f.UserFactory(username="expert-tester")
cls.case_run_3.assignee = None
cls.case_run_3.save(update_fields=["assignee"])
cls.url = reverse("patch-case-runs")
def test_given_assignee_does_not_exist(self):
result = User.objects.aggregate(max_pk=Max("pk"))
user_id = result["max_pk"] + 1
resp = self.client.patch(
self.url,
data={
"case_run": [self.case_run_1.pk],
"target_field": "assignee",
"new_value": user_id,
},
content_type="application/json",
)
self.assertJsonResponse(
resp,
{"message": [f"No user with id {user_id} exists."]},
status_code=HTTPStatus.BAD_REQUEST,
)
def test_specified_case_runs_do_not_exist(self):
result = TestCaseRun.objects.aggregate(max_pk=Max("pk"))
case_run_id = result["max_pk"] + 1
resp = self.client.patch(
self.url,
data={
"case_run": [case_run_id],
"target_field": "assignee",
"new_value": self.assignee.pk,
},
content_type="application/json",
)
self.assertJsonResponse(
resp,
{"message": [f"Test case run {case_run_id} does not exist."]},
status_code=HTTPStatus.BAD_REQUEST,
)
def test_change_assignee(self):
mail.outbox = []
update_targets = [self.case_run_1, self.case_run_3]
case_run: TestCaseRun
resp = self.client.patch(
self.url,
data={
"case_run": [case_run.pk for case_run in update_targets],
"target_field": "assignee",
"new_value": self.assignee.pk,
},
content_type="application/json",
)
self.assertEqual(200, resp.status_code)
original_assignees = {
self.case_run_1.pk: self.case_run_1.assignee.username,
self.case_run_3.pk: "None",
}
for case_run in update_targets:
self.assertEqual(self.assignee, TestCaseRun.objects.get(pk=case_run.pk).assignee)
self.assertTrue(
TCMSLogModel.objects.filter(
who=self.tester,
field="assignee",
original_value=original_assignees[case_run.pk],
new_value=self.assignee.username,
object_pk=case_run.pk,
).exists()
)
self._assert_sent_mail()
def _assert_sent_mail(self):
out_mail = mail.outbox[0]
self.assertEqual(f"Assignee of run {self.test_run.pk} has been changed", out_mail.subject)
self.assertSetEqual(
set(self.test_run.get_notification_recipients()), set(out_mail.recipients())
)
expected_body = dedent(
f"""\
### Links ###
Test run: {self.test_run.get_full_url()}
### Info ###
The assignee of case run in test run {self.test_run.pk}: {self.test_run.summary}
has been changed: Following is the new status:
### Test case runs information ###
* {self.case_run_1.pk}: {self.case_run_1.case.summary} - {self.assignee.username}
* {self.case_run_3.pk}: {self.case_run_3.case.summary} - {self.assignee.username}"""
)
self.assertEqual(expected_body, out_mail.body)
class TestSendMailNotifyOnTestCaseReviewerIsChanged(BasePlanCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
user_should_have_perm(cls.tester, "testcases.change_testcase")
cls.reviewer = f.UserFactory(username="case-reviewer")
def test_ensure_mail_notify_is_sent(self):
mail.outbox = []
self.login_tester()
resp = self.client.patch(
reverse("patch-cases"),
data={
"from_plan": self.plan.pk,
"case": [self.case.pk, self.case_2.pk],
"target_field": "reviewer",
"new_value": self.reviewer.username,
},
content_type="application/json",
)
self.assertEqual(200, resp.status_code)
case = TestCase.objects.get(pk=self.case.pk)
self.assertEqual(self.reviewer.username, case.reviewer.username)
case = TestCase.objects.get(pk=self.case_2.pk)
self.assertEqual(self.reviewer.username, case.reviewer.username)
out_mail: EmailMessage = mail.outbox[0]
self.assertEqual("You have been the reviewer of cases", out_mail.subject)
self.assertListEqual([self.reviewer.email], out_mail.recipients())
assigned_by = self.tester.username
expected_body = dedent(
f"""\
You have been assigned as the reviewer of the following Test Cases by {assigned_by}.
### Test cases information ###
[{self.case.pk}] {self.case.summary} - {self.case.get_full_url()}
[{self.case_2.pk}] {self.case_2.summary} - {self.case_2.get_full_url()}
"""
)
self.assertEqual(expected_body, out_mail.body)
class TestChangeCaseRunStatus(BaseCaseRun):
"""Test the AJAX request to change one or more case run status"""
auto_login = True
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.url = reverse("patch-case-runs")
cls.perm = "testruns.change_testcaserun"
user_should_have_perm(cls.tester, cls.perm)
cls.running_status = TestCaseRunStatus.objects.get(name="RUNNING")
cls.request_data = {
"case_run": [cls.case_run_1.pk, cls.case_run_3.pk],
"target_field": "case_run_status",
"new_value": cls.running_status.pk,
}
cls.me = f.UserFactory(username="me")
cls.case_run_6.tested_by = cls.me
cls.case_run_6.save()
def test_failure_when_no_permission(self):
remove_perm_from_user(self.tester, self.perm)
resp = self.client.patch(self.url, data=self.request_data, content_type="application/json")
self.assert403(resp)
def test_change_status(self):
resp = self.client.patch(self.url, data=self.request_data, content_type="application/json")
self.assertEqual(200, resp.status_code)
case_run: TestCaseRun
for case_run in [self.case_run_1, self.case_run_3]:
self.assertEqual(
self.running_status, TestCaseRun.objects.get(pk=case_run.pk).case_run_status
)
original_status = case_run.case_run_status.name
self.assertTrue(
TCMSLogModel.objects.filter(
who=self.tester,
field="case_run_status",
original_value=original_status,
new_value=self.running_status.name,
object_pk=case_run.pk,
).exists()
)
def test_no_case_runs_to_update(self):
data = self.request_data.copy()
result = TestCaseRun.objects.aggregate(max_pk=Max("pk"))
nonexisting_pk = result["max_pk"] + 1
data["case_run"] = [nonexisting_pk]
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assertJsonResponse(
resp,
{"message": [f"Test case run {nonexisting_pk} does not exist."]},
status_code=HTTPStatus.BAD_REQUEST,
)
def test_log_action_for_tested_by_changed(self):
"""Test log action when case run's tested_by is changed"""
data = self.request_data.copy()
# case run 6's tested_by will be updated to the request.user
data["case_run"] = [self.case_run_1.pk, self.case_run_6.pk]
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assert200(resp)
self.assertEqual(self.tester, TestCaseRun.objects.get(pk=self.case_run_6.pk).tested_by)
self.assertTrue(
TCMSLogModel.objects.filter(
who=self.tester,
field="tested_by",
original_value=self.me.username,
new_value=self.tester.username,
object_pk=self.case_run_6.pk,
).exists()
)
def test_avoid_updating_duplicate_status(self):
data = self.request_data.copy()
idle_status = TestCaseRunStatus.objects.get(name="IDLE")
# Both of the case runs' status should not be updated duplicately.
data["new_value"] = idle_status.pk
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assert200(resp)
for case_run_pk in data["case_run"]:
self.assertFalse(
TCMSLogModel.objects.filter(
who=self.tester,
field="case_run_status",
original_value=str(self.running_status),
new_value=str(idle_status),
object_pk=case_run_pk,
).exists()
)
class TestUpdateCaseRunsSortkey(BaseCaseRun):
"""Test AJAX request /ajax/update/case-run-sortkey/"""
auto_login = True
@classmethod
def setUpTestData(cls):
super().setUpTestData()
user_should_have_perm(cls.tester, "testruns.change_testcaserun")
cls.original_sort_key = 0
TestCaseRun.objects.all().update(sortkey=cls.original_sort_key)
cls.url = reverse("patch-case-runs")
def test_update_nonexisting_case_run(self):
result = TestCaseRun.objects.aggregate(max_pk=Max("pk"))
nonexisting_pk = result["max_pk"] + 1
resp = self.client.patch(
self.url,
data={
"case_run": [nonexisting_pk],
"target_field": "sortkey",
"new_value": 2,
},
content_type="application/json",
)
self.assertJsonResponse(
resp,
{"message": [f"Test case run {nonexisting_pk} does not exist."]},
status_code=HTTPStatus.BAD_REQUEST,
)
def test_sort_key_is_not_integer(self):
resp = self.client.patch(
self.url,
data={
"case_run": [self.case_run_4.pk],
"target_field": "sortkey",
"new_value": "sortkey100",
},
content_type="application/json",
)
self.assertJsonResponse(
resp,
{"message": ["Sort key must be a positive integer."]},
status_code=HTTPStatus.BAD_REQUEST,
)
def test_new_sort_key_is_not_in_range(self):
resp = self.client.patch(
self.url,
data={
"case_run": [self.case_run_4.pk],
"target_field": "sortkey",
"new_value": SORT_KEY_MAX + 1,
},
content_type="application/json",
)
self.assertJsonResponse(
resp,
{"message": [f"New sortkey is out of range {SORT_KEY_RANGE}."]},
status_code=HTTPStatus.BAD_REQUEST,
)
def test_update_sort_key(self):
new_sort_key = 2
update_targets: List[TestCaseRun] = [self.case_run_2, self.case_run_4]
case_run: TestCaseRun
update_targets_pks: List[int] = [case_run.pk for case_run in update_targets]
resp = self.client.patch(
self.url,
data={
"case_run": update_targets_pks,
"target_field": "sortkey",
"new_value": new_sort_key,
},
content_type="application/json",
)
self.assert200(resp)
for case_run in update_targets:
self.assertEqual(new_sort_key, TestCaseRun.objects.get(pk=case_run.pk).sortkey)
self.assertTrue(
TCMSLogModel.objects.filter(
who=self.tester,
field="sortkey",
original_value=str(self.original_sort_key),
new_value=str(new_sort_key),
object_pk=case_run.pk,
).exists()
)
# Other case runs' sortkey should not be changed.
sort_keys: List[int] = TestCaseRun.objects.exclude(pk__in=update_targets_pks).values_list(
"sortkey", flat=True
)
for sort_key in sort_keys:
self.assertEqual(self.original_sort_key, sort_key)
class TestUpdateCasesDefaultTester(AuthMixin, HelperAssertions, test.TestCase):
"""Test set default tester to selected cases"""
auto_login = True
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.plan = f.TestPlanFactory(owner=cls.tester, author=cls.tester)
cls.case_1 = f.TestCaseFactory(
author=cls.tester, reviewer=cls.tester, default_tester=cls.tester, plan=[cls.plan]
)
cls.case_2 = f.TestCaseFactory(
author=cls.tester, reviewer=cls.tester, default_tester=None, plan=[cls.plan]
)
user_should_have_perm(cls.tester, "testcases.change_testcase")
cls.user_1 = f.UserFactory(username="user1")
cls.url = reverse("patch-cases")
def test_set_default_tester(self):
resp = self.client.patch(
self.url,
data={
"from_plan": self.plan.pk,
"case": [self.case_1.pk, self.case_2.pk],
"target_field": "default_tester",
"new_value": self.user_1.username,
},
content_type="application/json",
)
self.assertJsonResponse(resp, {})
case: TestCase
for case in [self.case_1, self.case_2]:
self.assertEqual(self.user_1, TestCase.objects.get(pk=case.pk).default_tester)
self.assertTrue(
TCMSLogModel.objects.filter(
who=self.tester,
field="default_tester",
original_value="None"
if case.default_tester is None
else case.default_tester.username,
new_value=self.user_1.username,
).exists()
)
def test_given_username_does_not_exist(self):
resp = self.client.patch(
self.url,
data={
"from_plan": self.plan.pk,
"case": [self.case_1.pk, self.case_2.pk],
"target_field": "default_tester",
"new_value": "unknown",
},
content_type="application/json",
)
self.assertJsonResponse(
resp,
{
"message": [
"unknown cannot be set as a default tester, since this user does not exist.",
]
},
status_code=HTTPStatus.BAD_REQUEST,
)
case: TestCase
for case in [self.case_1, self.case_2]:
self.assertEqual(case.default_tester, TestCase.objects.get(pk=case.pk).default_tester)
class TestChangeTestCasePriority(BasePlanCase):
"""Test AJAX request to change test case priority"""
auto_login = True
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.perm = "testcases.change_testcase"
user_should_have_perm(cls.tester, cls.perm)
cls.url = reverse("patch-cases")
cls.request_data = {
"case": [cls.case_1.pk, cls.case_3.pk],
"target_field": "priority",
"new_value": None, # Must be set in the individual test
}
def test_change_priority(self):
data = self.request_data.copy()
p4 = Priority.objects.get(value="P4")
data["new_value"] = p4.pk
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assert200(resp)
self.assertEqual(p4, TestCase.objects.get(pk=self.case_1.pk).priority)
self.assertEqual(p4, TestCase.objects.get(pk=self.case_3.pk).priority)
case: TestCase
for case in [self.case_1, self.case_3]:
self.assertTrue(
TCMSLogModel.objects.filter(
who=self.tester,
field="priority",
original_value=case.priority.value,
new_value=p4.value,
).exists()
)
def test_unknown_priority(self):
data = self.request_data.copy()
result = Priority.objects.aggregate(max_pk=Max("pk"))
data["new_value"] = result["max_pk"] + 1
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assertJsonResponse(
resp,
{"message": ["The priority you specified to change does not exist."]},
status_code=HTTPStatus.BAD_REQUEST,
)
class TestChangeTestCaseReviewer(BasePlanCase):
"""Test AJAX request to change test case reviewer"""
auto_login = True
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.perm = "testcases.change_testcase"
user_should_have_perm(cls.tester, cls.perm)
cls.url = reverse("patch-cases")
cls.request_data = {
"case": [cls.case_1.pk, cls.case_3.pk],
"target_field": "reviewer",
"new_value": None, # Must be set in the individual test
}
cls.reviewer = f.UserFactory(username="reviewer")
def test_change_reviewer(self):
data = self.request_data.copy()
data["new_value"] = self.reviewer.username
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assert200(resp)
case: TestCase
for case in [self.case_1, self.case_3]:
self.assertEqual(self.reviewer, TestCase.objects.get(pk=case.pk).reviewer)
self.assertTrue(
TCMSLogModel.objects.filter(
who=self.tester,
field="reviewer",
original_value=str(case.reviewer),
new_value=self.reviewer.username,
).exists()
)
def test_nonexistent_reviewer(self):
data = self.request_data.copy()
data["new_value"] = "someone"
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assertJsonResponse(
resp,
{"message": ["Reviewer someone is not found"]},
status_code=HTTPStatus.BAD_REQUEST,
)
class TestChangeTestCaseStatus(BasePlanCase):
"""Test AJAX request to change test case status"""
auto_login = True
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.perm = "testcases.change_testcase"
user_should_have_perm(cls.tester, cls.perm)
cls.url = reverse("patch-cases")
cls.request_data = {
"from_plan": cls.plan.pk,
"case": [cls.case_1.pk, cls.case_3.pk],
"target_field": "case_status",
"new_value": None, # Must be set in the individual test
}
def test_change_status(self):
data = self.request_data.copy()
data["new_value"] = self.case_status_proposed.pk
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assertJsonResponse(resp, {})
case: TestCase
for case in [self.case_1, self.case_3]:
self.assertEqual(
self.case_status_proposed, TestCase.objects.get(pk=case.pk).case_status
)
self.assertTrue(
TCMSLogModel.objects.filter(
who=self.tester,
field="case_status",
original_value=case.case_status.name,
new_value=self.case_status_proposed.name,
).exists()
)
def test_nonexistent_status(self):
data = self.request_data.copy()
result = TestCaseStatus.objects.aggregate(max_pk=Max("pk"))
data["new_value"] = result["max_pk"] + 1
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assertJsonResponse(
resp,
{"message": ["The status you choose does not exist."]},
status_code=HTTPStatus.BAD_REQUEST,
)
def test_avoid_updating_duplicate_status(self):
data = self.request_data.copy()
confirmed_status = TestCaseStatus.objects.get(name="CONFIRMED")
data["new_value"] = confirmed_status.pk
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assert200(resp)
for case_pk in data["case"]:
self.assertFalse(
TCMSLogModel.objects.filter(
who=self.tester,
field="case_status",
original_value=str(TestCase.objects.get(pk=case_pk).case_status),
new_value=confirmed_status.pk,
object_pk=case_pk,
).exists()
)
class TestChangeTestCaseSortKey(BasePlanCase):
"""Test AJAX request to change test case sort key"""
auto_login = True
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.perm = "testcases.change_testcase"
user_should_have_perm(cls.tester, cls.perm)
cls.url = reverse("patch-cases")
cls.new_sort_key = 100
cls.request_data = {
"plan": cls.plan.pk,
"case": [cls.case_1.pk, cls.case_3.pk],
"target_field": "sortkey",
"new_value": cls.new_sort_key,
}
def test_change_sort_key(self):
data = self.request_data.copy()
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assert200(resp)
self.assertEqual(
self.new_sort_key,
TestCasePlan.objects.get(plan=self.plan, case=self.case_1).sortkey,
)
self.assertEqual(
self.new_sort_key,
TestCasePlan.objects.get(plan=self.plan, case=self.case_3).sortkey,
)
def test_sort_key_is_out_of_range(self):
data = self.request_data.copy()
for sort_key in [SORT_KEY_MAX + 1, SORT_KEY_MAX + 10]:
data["new_value"] = sort_key
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assertJsonResponse(
resp,
{"message": ["New sortkey is out of range [0, 32300]."]},
status_code=HTTPStatus.BAD_REQUEST,
)
@patch("django.db.models.Manager.bulk_update")
def test_avoid_updating_duplicate_sort_key(self, bulk_update):
data = self.request_data.copy()
# Sort key of case_3 should not be updated.
new_sort_key = TestCasePlan.objects.get(plan=self.plan, case=self.case_3).sortkey
data["new_value"] = new_sort_key
resp = self.client.patch(self.url, data=data, content_type="application/json")
self.assert200(resp)
args, _ = bulk_update.call_args
changed, changed_fields = args
self.assertEqual(1, len(changed)) # Only sortkey of the case_1 is changed.
changed_rel = changed[0]
self.assertEqual(self.case_1, changed_rel.case)
self.assertEqual(new_sort_key, changed_rel.sortkey)
self.assertListEqual(["sortkey"], changed_fields)
class TestModuleUpdateActions(AuthMixin, HelperAssertions, test.TestCase):
"""Test the core behavior of ModuleUpdateActions class"""
auto_login = True
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.case = f.TestCaseFactory()
cls.perm = "testcases.change_testcase"
def setUp(self):
super().setUp()
user_should_have_perm(self.tester, self.perm)
def _request(
self, target_field: Optional[str] = None, new_status: Optional[TestCaseStatus] = None
):
new_value = 1 if new_status is None else new_status.pk
return self.client.patch(
reverse("patch-cases"),
data={
"case": [self.case.pk],
"target_field": target_field or "case_status",
"new_value": new_value,
},
content_type="application/json",
)
def test_no_perm(self):
remove_perm_from_user(self.tester, self.perm)
self.assert403(self._request())
@patch("tcms.core.ajax.PatchTestCasesView._simple_patch")
def test_return_default_json_if_action_returns_nothing(self, _update_case_status):
_update_case_status.return_value = None
self.assertJsonResponse(self._request(), {})
def test_cannot_find_action_method(self):
self.assertJsonResponse(
self._request("unknown_field"),
{"message": "Not know what to update."},
status_code=HTTPStatus.BAD_REQUEST,
)
@patch("tcms.core.ajax.PatchTestCasesView._simple_patch")
def test_handle_raised_error_from_action_method(self, _update_case_status):
_update_case_status.side_effect = ValueError
self.assertJsonResponse(
self._request(),
{
"message": "Update failed. Please try again or request support from your organization."
},
status_code=HTTPStatus.BAD_REQUEST,
)
def test_missing_target_field(self):
resp = self.client.patch(
reverse("patch-cases"),
data={
"case": [self.case.pk],
"new_value": 1,
},
content_type="application/json",
)
self.assertJsonResponse(
resp, {"message": "Missing argument target_field."}, status_code=HTTPStatus.BAD_REQUEST
)
def test_missing_new_value(self):
resp = self.client.patch(
reverse("patch-cases"),
data={
"case": [self.case.pk],
"target_field": "case_status",
},
content_type="application/json",
)
self.assertJsonResponse(
resp, {"message": ["Missing argument new_value."]}, status_code=HTTPStatus.BAD_REQUEST
)
@patch("tcms.testcases.models.TestCase.log_action")
@patch("tcms.core.ajax.logger")
def test_fallback_to_warning_if_log_action_fails(self, logger, log_action):
log_action.side_effect = ValueError("something wrong")
new_status = TestCaseStatus.objects.exclude(pk=self.case.case_status.pk)[0]
resp = self._request(new_status=new_status)
self.assert200(resp)
logger.warning.assert_called_once_with(
"Failed to log update action for case run %s. Field: %s, original: %s, new: %s, by: %s",
self.case.pk,
"case_status",
str(TestCaseStatus.objects.get(pk=self.case.case_status.pk)),
str(new_status),
User.objects.get(pk=self.tester.pk),
)
class TestAjaxGetInfo(HelperAssertions, test.TestCase):
"""Test AJAX request to get management objects"""
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.product_a = f.ProductFactory(name="Product A")
cls.product_b = f.ProductFactory(name="Product B")
cls.pa_ver_1_0 = f.VersionFactory(product=cls.product_a, value="1.0")
cls.pa_ver_1_1 = f.VersionFactory(product=cls.product_a, value="1.1")
cls.pa_ver_1_2dev = f.VersionFactory(product=cls.product_a, value="1.2dev")
cls.pb_ver_202101 = f.VersionFactory(product=cls.product_b, value="202101")
cls.pb_ver_202103 = f.VersionFactory(product=cls.product_b, value="202103")
cls.build_1 = f.TestBuildFactory(name="build1", product=cls.product_a)
cls.build_2 = f.TestBuildFactory(name="build2", product=cls.product_a, is_active=False)
cls.build_3 = f.TestBuildFactory(name="build3", product=cls.product_b)
cls.case_category_1 = f.TestCaseCategoryFactory(name="functional", product=cls.product_a)
cls.case_category_2 = f.TestCaseCategoryFactory(name="auto", product=cls.product_a)
cls.case_category_3 = f.TestCaseCategoryFactory(name="manual", product=cls.product_b)
cls.component_db = f.ComponentFactory(name="db", product=cls.product_a)
cls.component_docs = f.ComponentFactory(name="docs", product=cls.product_a)
cls.component_cli = f.ComponentFactory(name="cli", product=cls.product_b)
cls.env_win = f.TestEnvironmentFactory(name="win", product=cls.product_a)
cls.env_linux = f.TestEnvironmentFactory(name="linux", product=cls.product_a)
cls.env_bsd = f.TestEnvironmentFactory(name="bsd", product=cls.product_a)
cls.env_group_a = f.TCMSEnvGroupFactory(name="group-a")
cls.env_group_b = f.TCMSEnvGroupFactory(name="group-b")
cls.env_property_py = f.TCMSEnvPropertyFactory(name="python")
f.TCMSEnvValueFactory(value="3.8", property=cls.env_property_py)
f.TCMSEnvValueFactory(value="3.9", property=cls.env_property_py)
f.TCMSEnvValueFactory(value="3.10", property=cls.env_property_py)
cls.env_property_go = f.TCMSEnvPropertyFactory(name="go")
f.TCMSEnvValueFactory(value="1.14", property=cls.env_property_go)
f.TCMSEnvValueFactory(value="1.15", property=cls.env_property_go)
cls.env_property_rust = f.TCMSEnvPropertyFactory(name="rust")
f.TCMSEnvGroupPropertyMapFactory(group=cls.env_group_a, property=cls.env_property_py)
f.TCMSEnvGroupPropertyMapFactory(group=cls.env_group_a, property=cls.env_property_go)
f.TCMSEnvGroupPropertyMapFactory(group=cls.env_group_b, property=cls.env_property_rust)
cls.url = reverse("ajax-getinfo")
def test_unknown_info_type(self):
resp = self.client.get(
self.url, data={"product_id": self.product_a.pk, "info_type": "unknown info type"}
)
self.assertJsonResponse(
resp, {"message": "Unrecognizable infotype"}, status_code=HTTPStatus.BAD_REQUEST
)
def test_missing_info_type(self):
resp = self.client.get(self.url, data={"product_id": self.product_a.pk})
self.assertJsonResponse(
resp, {"message": "Missing parameter info_type."}, status_code=HTTPStatus.BAD_REQUEST
)
def test_invalid_product_id(self):
resp = self.client.get(self.url, data={"product_id": "productname", "info_type": "envs"})
self.assertJsonResponse(
resp,
{"message": "Invalid product id productname. It must be a positive integer."},
status_code=HTTPStatus.BAD_REQUEST,
)
def test_get_data_in_ulli_format(self):
resp = self.client.get(
self.url,
data={"product_id": self.product_a.pk, "info_type": "builds", "format": "ulli"},
)
bs = BeautifulSoup(resp.content.decode(), "html.parser")
build_names = sorted(item.text for item in bs.find_all("li"))
expected = sorted(
TestBuild.objects.filter(product=self.product_a).values_list("name", flat=True)
)
self.assertListEqual(expected, build_names)
@staticmethod
def _sort_serialized_data(json_data):
return sorted(json_data, key=itemgetter("pk"))
def _assert_request_data(self, request_data, expected_objects):
resp = self.client.get(self.url, data=request_data)
test_data = self._sort_serialized_data(json.loads(resp.content))
expected = self._sort_serialized_data(
json.loads(serializers.serialize("json", expected_objects, fields=("name", "value"))),
)
self.assertEqual(expected, test_data)
def test_get_versions(self):
self._assert_request_data(
{"product_id": self.product_a.pk, "info_type": "versions"},
Version.objects.filter(product=self.product_a),
)
def test_get_test_builds(self):
products = [self.product_a.pk, self.product_b.pk]
for is_active in [True, False]:
data = {"product_id": products, "info_type": "builds"}
if is_active:
data["is_active"] = 1
expected_filter = {"product__in": products}
if is_active:
expected_filter["is_active"] = 1
self._assert_request_data(data, TestBuild.objects.filter(**expected_filter))
def test_get_case_categories(self):
self._assert_request_data(
{"product_id": self.product_a.pk, "info_type": "categories"},
TestCaseCategory.objects.filter(product=self.product_a),
)
def test_get_case_components(self):
self._assert_request_data(
{"product_id": self.product_a.pk, "info_type": "components"},
Component.objects.filter(product=self.product_a),
)
def test_get_environments(self):
self._assert_request_data(
{"product_id": self.product_a.pk, "info_type": "envs"},
TestEnvironment.objects.filter(product=self.product_a),
)
def test_get_env_groups(self):
self._assert_request_data({"info_type": "env_groups"}, TCMSEnvGroup.objects.all())
def test_get_env_properties(self):
self._assert_request_data({"info_type": "env_properties"}, TCMSEnvProperty.objects.all())
def test_get_env_properties_by_group(self):
self._assert_request_data(
{"info_type": "env_properties", "env_group_id": self.env_group_a.pk},
TCMSEnvProperty.objects.filter(name__in=["python", "go"]),
)
def test_get_env_values(self):
self._assert_request_data(
{"info_type": "env_values", "env_property_id": self.env_property_go.pk},
TCMSEnvValue.objects.filter(value__in=["1.14", "1.15"]),
)
def test_get_env_values_without_specifying_property_id(self):
self._assert_request_data({"info_type": "env_values"}, [])
@pytest.mark.parametrize(
"criteria,expected_username",
[
[{"username": "user1"}, "user1"],
[{"email__contains": "myhome.io"}, "user2"],
],
)
def test_get_users_info(criteria, expected_username, base_data: BaseDataContext, client):
User.objects.create(username="user1", email="user1@localhost")
User.objects.create(username="user2", email="user2@myhome.io")
data = {"info_type": "users"}
data.update(criteria)
response = client.get(reverse("ajax-getinfo"), data=data)
test_data = sorted(json.loads(response.content), key=itemgetter("pk"))
expected = sorted(
json.loads(
serializers.serialize(
"json", User.objects.filter(username=expected_username), fields=("name", "value")
)
),
key=itemgetter("pk"),
)
assert expected == test_data
@pytest.mark.parametrize(
"criteria,expected_tags",
[
[{}, ["python", "rust", "ruby", "perl"]],
[{"name__startswith": "ru"}, ["rust", "ruby"]],
],
)
@pytest.mark.django_db
def test_get_tags_info(criteria: Dict[str, str], expected_tags: List[str], client):
for tag in ("python", "rust", "ruby", "perl"):
TestTag.objects.create(name=tag)
data = {"info_type": "tags"}
data.update(criteria)
response = client.get(reverse("ajax-getinfo"), data=data)
got = sorted(item["fields"]["name"] for item in json.loads(response.content))
expected = sorted(expected_tags)
assert expected == got
| gpl-2.0 |
Anthrocon-Reg/ubersystem | uber/site_sections/graphs.py | 2 | 6718 | from uber.common import *
# TODO: DOM: this whole thing needs a major overhaul, it's a nightmare
# this spits out data in the wrong format needed for the javascript,
# and the javascript does a ton of unneeded processing to work around it.
# imports the actual hardcoded graph data for previous magfest years
# (yes, its hardcoded and not from the DB). only used for money graph,
# newer graphs read directly from DB
from uber.graph_data import *
def graphable():
atts = list(Attendee.objects.values())
groups = list(Group.objects.values())
start = min(x["registered"].date() for x in atts + groups)
end = max(x["registered"].date() for x in atts + groups)
days, regs = defaultdict(int), defaultdict(int)
for x in atts + groups:
days[x["registered"].date()] += x["amount_paid"]
total = 0
sums = {}
day = start
while day <= end:
total += days[day]
sums[day.strftime("%Y-%m-%d")] = total
day += timedelta(days=1)
return sums
def get_graphs_data():
# warning: this code is horrifying. holy shit.
m12_regs = [
Attendee.objects.filter(
Q(paid=HAS_PAID) |
Q(paid=PAID_BY_GROUP, group__amount_paid__gt=0)).count(),
Attendee.objects.filter(paid=NOT_PAID).count()
]
curr = graphable()
until = (EPOCH.date() - date.today()).days
# TODO: replace hardcoded dates below with these
# these are END DATES
m6_date = date(2008, 1, 6) # date magfest ENDS
m7_date = date(2009, 1, 4) # date magfest ENDS
m8_date = date(2010, 1, 4) # date magfest ENDS
m9_date = date(2011, 1, 16) # date magfest ENDS
m10_date = date(2012, 1, 8) # date magfest ENDS
m11_date = date(2013, 1, 6) # date magfest ENDS
m12_date = date(2014, 1, 5) # date magfest ENDS
return {
"m6_date": m6_date.isoformat(),
"m7_date": m7_date.isoformat(),
"m8_date": m8_date.isoformat(),
"m9_date": m9_date.isoformat(),
"m10_date": m10_date.isoformat(),
"m11_date": m11_date.isoformat(),
"m12_date": m12_date.isoformat(),
"until": until,
#"needed": Money.objects.filter(Q(pledged=False) | Q(pre_con=True),
# paid_by=MAGFEST_FUNDS, type=DEBIT)
# .aggregate(Sum('amount')).values()[0],
"curr_total": max(curr.values()),
"m6_by_now": m6[(date(2008, 1, 3) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m7_by_now": m7[(date(2009, 1, 1) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m8_by_now": m8[(date(2010, 1, 1) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m9_by_now": m9[(date(2011, 1, 13) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m10_by_now": m10[(date(2012, 1, 5) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m11_by_now": m11[(date(2013, 1, 3) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m6_pre_con": m6["2008-01-02"],
"m7_pre_con": m7["2008-12-31"],
"m8_pre_con": m8["2009-12-30"],
"m9_pre_con": m9["2011-01-12"],
"m10_pre_con": m10["2012-01-04"],
"m11_pre_con": m11["2013-01-02"],
"m6_coords": sorted(m6.items()),
"m6_lookup": m6,
"m7_coords": sorted(m7.items()),
"m7_lookup": m7,
"m8_coords": sorted(m8.items()),
"m8_lookup": m8,
"m9_coords": sorted(m9.items()),
"m9_lookup": m9,
"m10_coords": sorted(m10.items()),
"m10_lookup": m10,
"m11_coords": sorted(m11.items()),
"m11_lookup": m11,
"m12_coords": sorted(curr.items()),
"m12_lookup": curr,
#"m6_regs": m6_regs.get((date(2008, 1, 3) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
#"m7_regs": m7_regs.get((date(2009, 1, 1) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
#"m8_regs": m8_regs.get((date(2010, 1, 1) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
#"m9_regs": m9_regs.get((date(2011, 1, 13) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
#"m10_regs": m10_regs.get((date(2012, 1, 5) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
#"m11_regs": m11_regs.get((date(2013, 1, 3) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
#"m12_regs": m12_regs
}
@all_renderable(PEOPLE)
class Root:
def index(self):
return {
"test": "test423"
}
# this code is dead as hell.
def graphs(self):
m10_regs = [
Attendee.objects.filter(
Q(paid=HAS_PAID) |
Q(paid=PAID_BY_GROUP, group__amount_paid__gt=0)).count(),
Attendee.objects.filter(paid=NOT_PAID).count()
]
curr = graphable()
until = (EPOCH.date() - date.today()).days
return {
"until": until,
"needed": Money.objects.filter(
Q(pledged=False) |
Q(pre_con=True),
paid_by=MAGFEST_FUNDS,
type=DEBIT).aggregate(Sum('amount')).values()[0],
"curr_total": max(curr.values()),
"m6_by_now": m6[(date(2008, 1, 3) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m7_by_now": m7[(date(2009, 1, 1) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m8_by_now": m8[(date(2010, 1, 1) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m9_by_now": m9[(date(2011, 1, 13) - timedelta(days=until)).strftime("%Y-%m-%d")],
"m6_pre_con": m6["2008-01-02"],
"m7_pre_con": m7["2008-12-31"],
"m8_pre_con": m8["2009-12-30"],
"m9_pre_con": m9["2011-01-12"],
"m6_coords": sorted(m6.items()),
"m6_lookup": m6,
"m7_coords": sorted(m7.items()),
"m7_lookup": m7,
"m8_coords": sorted(m8.items()),
"m8_lookup": m8,
"m9_coords": sorted(m9.items()),
"m9_lookup": m9,
"m10_coords": sorted(curr.items()),
"m10_lookup": curr,
"m6_regs": m6_regs.get((date(2008,1,3) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
"m7_regs": m7_regs.get((date(2009,1,1) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
"m8_regs": m8_regs.get((date(2010,1,1) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
"m9_regs": m9_regs.get((date(2011,1,13) - timedelta(days=until)).strftime("%Y-%m-%d"), [0,0]),
"m10_regs": m10_regs
}
def graphs2(self):
return get_graphs_data()
def graphs3(self):
return get_graphs_data()
graphs.restricted = (PEOPLE, MONEY)
graphs2.restricted = (PEOPLE, MONEY)
graphs3.restricted = (PEOPLE, MONEY)
| gpl-3.0 |
psychopy/versions | psychopy/iohub/client/connect.py | 1 | 12274 | # -*- coding: utf-8 -*-
# Part of the psychopy.iohub library.
# Copyright (C) 2012-2016 iSolver Software Solutions
# Distributed under the terms of the GNU General Public License (GPL).
from __future__ import division, absolute_import, print_function
import os
from .. import _DATA_STORE_AVAILABLE, IOHUB_DIRECTORY
from . import ioHubConnection
from ..util import yload, yLoader, readConfig
def launchHubServer(**kwargs):
"""
Starts the ioHub Server subprocess, and return a
:class:`psychopy.iohub.client.ioHubConnection` object that is used to
access enabled iohub device's events, get events, and control the
ioHub process during the experiment.
By default (no kwargs specified), the ioHub server does not create an
ioHub HDF5 file, events are available to the experiment program at runtime.
The following Devices are enabled by default:
- Keyboard: named 'keyboard', with runtime event reporting enabled.
- Mouse: named 'mouse', with runtime event reporting enabled.
- Monitor: named 'monitor'.
- Experiment: named 'experiment'.
To customize how the ioHub Server is initialized when started, use
one or more of the following keyword arguments when calling the function:
+---------------------+-----------------+---------------+-----------------+
| kwarg Name | Value Type | Description |
+=====================+=================+===============+=================+
| experiment_code | str, <= 24 char | If experiment_code is provided, |
| | | an ioHub HDF5 file will be |
| | | created for the session. |
+---------------------+-----------------+---------------+-----------------+
| session_code | str, <= 24 char | When specified, used as the name|
| | | of the ioHub HDF5 file created |
| | | for the session. |
+---------------------+-----------------+---------------+-----------------+
| experiment_info | dict | Can be used to save the |
| | | following experiment metadata |
| | | fields: |
+---------------------+-----------------+---------------+-----------------+
| | - code: str, <= 24 char |
| | - title: str, <= 48 char |
| | - description: str, < 256 char |
| | - version: str, <= 6 char |
+---------------------+-----------------+---------------+-----------------+
| session_info | dict | Can be used to save the |
| | | following session metadata |
| | | fields: |
+---------------------+-----------------+---------------+-----------------+
| | - code: str, <= 24 char |
| | - name: str, <= 48 char |
| | - comments: str, < 256 char |
| | - user_variables: dict |
+---------------------+-----------------+---------------+-----------------+
| datastore_name | str | Used to provide an ioHub HDF5 |
| | | file name different than the |
| | | session_code. |
+---------------------+-----------------+---------------+-----------------+
|psychopy_monitor_name| str | Provides the path of a |
| | | PsychoPy Monitor Center config |
| | | file. Information like display |
| | | size is read and used to update |
| | | the ioHub Display Device config.|
+---------------------+-----------------+---------------+-----------------+
| iohub_config_name | str | Specifies the name of the |
| | | iohub_config.yaml file that |
| | | contains the ioHub Device |
| | | list to be used by the ioHub |
| | | Server. i.e. the 'device_list' |
| | | section of the yaml file. |
+---------------------+-----------------+---------------+-----------------+
| iohub.device.path | dict | Add an ioHub Device by using the|
| | | device class path as the key, |
| Multiple Device's | | and the device's configuration |
| can be specified | | in a dict value. |
| using separate | | |
| kwarg entries. | | |
+---------------------+-----------------+---------------+-----------------+
Examples:
A. Wait for the 'q' key to be pressed::
from psychopy.iohub.client import launchHubServer
# Start the ioHub process. 'io' can now be used during the
# experiment to access iohub devices and read iohub device events.
io=launchHubServer()
print "Press any Key to Exit Example....."
# Wait until a keyboard event occurs
keys = io.devices.keyboard.waitForKeys(['q',])
print("Key press detected: {}".format(keys))
print("Exiting experiment....")
# Stop the ioHub Server
io.quit()
Please see the psychopy/demos/coder/iohub/launchHub.py demo for examples
of different ways to use the launchHubServer function.
"""
experiment_code = kwargs.get('experiment_code', None)
if experiment_code:
del kwargs['experiment_code']
experiment_info = kwargs.get('experiment_info')
if experiment_info:
del kwargs['experiment_info']
for k, v in list(experiment_info.items()):
if k in ['code', 'title', 'description', 'version']:
experiment_info[k] = u"{}".format(v)
if experiment_info.get('code'):
experiment_code = experiment_info['code']
elif experiment_code:
experiment_info['code'] = experiment_code
elif experiment_code:
experiment_info = dict(code=experiment_code)
session_code = kwargs.get('session_code', None)
if session_code:
del kwargs['session_code']
session_info = kwargs.get('session_info')
if session_info:
del kwargs['session_info']
for k, v in list(session_info.items()):
if k in ['code', 'name', 'comments']:
session_info[k] = u"{}".format(v)
elif k == 'user_variables':
session_info[k] = v
if session_info.get('code'):
session_code = session_info['code']
elif session_code:
session_info['code'] = session_code
elif session_code:
session_info = dict(code=session_code)
else:
session_info = {}
if experiment_code and not session_code:
# this means we should auto_generate a session code
import datetime
dtstr = datetime.datetime.now().strftime('%d_%m_%Y_%H_%M')
session_info['code'] = session_code = u"S_{0}".format(dtstr)
datastore_name = None
if _DATA_STORE_AVAILABLE is True:
datastore_name = kwargs.get('datastore_name')
if datastore_name:
del kwargs['datastore_name']
elif session_code:
datastore_name = session_code
monitor_name = kwargs.get('psychopy_monitor_name')
if monitor_name:
del kwargs['psychopy_monitor_name']
monitor_devices_config = None
iohub_conf_file_name = kwargs.get('iohub_config_name')
if iohub_conf_file_name:
# Load the specified iohub configuration file,
# converting it to apython dict.
with open(iohub_conf_file_name, 'r') as iohub_conf_file:
_temp_conf_read = yload(iohub_conf_file, Loader=yLoader)
monitor_devices_config = _temp_conf_read.get('monitor_devices')
del kwargs['iohub_config_name']
iohub_config = None
device_dict = {}
if monitor_devices_config:
device_dict = monitor_devices_config
# iohub_config = dict(monitor_devices=monitor_devices_config)
if isinstance(device_dict,(list,tuple)):
tempdict_ = {}
for ddict in device_dict:
tempdict_[list(ddict.keys())[0]] = list(ddict.values())[0]
device_dict = tempdict_
device_dict.update(kwargs)
device_list = []
def isFunction(func):
import types
return isinstance(func, types.FunctionType)
def func2str(func):
return '%s.%s' % (func.__module__, func.__name__)
def configfuncs2str(config):
for k, v in list(config.items()):
if isinstance(v, dict):
configfuncs2str(v)
if isFunction(v):
config[k] = func2str(v)
configfuncs2str(device_dict)
# <<< WTF is this for .... ?????
# Ensure a Display Device has been defined. If not, create one.
# Insert Display device as first device in dev. list.
if 'Display' not in device_dict:
if monitor_name:
display_config = {'psychopy_monitor_name': monitor_name,
'override_using_psycho_settings': True}
else:
display_config = {'override_using_psycho_settings': False}
device_list.append(dict(Display=display_config))
else:
device_list.append(dict(Display=device_dict['Display']))
del device_dict['Display']
# Ensure a Experiment, Keyboard, and Mouse Devices have been defined.
# If not, create them.
check_for_devs = ['Experiment', 'Keyboard', 'Mouse']
for adev_name in check_for_devs:
if adev_name not in device_dict:
device_list.append({adev_name : {}})
else:
device_list.append({adev_name : device_dict[adev_name]})
del device_dict[adev_name]
iohub_config = dict()
def_ioconf = readConfig(os.path.join(IOHUB_DIRECTORY,u'default_config.yaml'))
# Add remaining defined devices to the device list.
for class_name, device_config in device_dict.items():
if class_name in def_ioconf:
# not a device, a top level iohub config param
iohub_config[class_name] = device_config
else:
#TODO: Check that class_name is valid before adding to list
device_list.append({class_name: device_config})
# Create an ioHub configuration dictionary.
iohub_config['monitor_devices'] = device_list
if _DATA_STORE_AVAILABLE and experiment_code and session_code:
# If datastore_name kwarg or experiment code has been provided,
# then enable saving of device events to the iohub datastore hdf5 file.
# If datastore_name kwarg was provided, it is used for the hdf5 file
# name, otherwise the session code is used. This avoids different
# experiments / sessions running in the same directory from using
# the same hdf5 file name.
if datastore_name is None:
datastore_name = session_code
iohub_config['data_store'] = dict(enable=True,
filename=datastore_name,
experiment_info=experiment_info,
session_info=session_info)
#import pprint
#print()
#print('ioHubConnection(iohub_config):')
#pprint.pprint(iohub_config)
return ioHubConnection(iohub_config)
| gpl-3.0 |
thesuperzapper/tensorflow | tensorflow/python/ops/partitioned_variables.py | 132 | 12318 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# ==============================================================================
"""Helper functions for creating partitioned variables.
This is a convenient abstraction to partition a large variable across
multiple smaller variables that can be assigned to different devices.
The full variable can be reconstructed by concatenating the smaller variables.
Using partitioned variables instead of a single variable is mostly a
performance choice. It however also has an impact on:
1. Random initialization, as the random number generator is called once per
slice
2. Updates, as they happen in parallel across slices
A key design goal is to allow a different graph to repartition a variable
with the same name but different slicings, including possibly no partitions.
TODO(touts): If an initializer provides a seed, the seed must be changed
deterministically for each slice, maybe by adding one to it, otherwise each
slice will use the same values. Maybe this can be done by passing the
slice offsets to the initializer functions.
Typical usage:
```python
# Create a list of partitioned variables with:
vs = create_partitioned_variables(
<shape>, <slicing>, <initializer>, name=<optional-name>)
# Pass the list as inputs to embedding_lookup for sharded, parallel lookup:
y = embedding_lookup(vs, ids, partition_strategy="div")
# Or fetch the variables in parallel to speed up large matmuls:
z = matmul(x, concat(slice_dim, vs))
```
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import tf_logging as logging
__all__ = [
"create_partitioned_variables",
"variable_axis_size_partitioner",
"min_max_variable_partitioner",
"fixed_size_partitioner",
]
def variable_axis_size_partitioner(
max_shard_bytes, axis=0, bytes_per_string_element=16, max_shards=None):
"""Get a partitioner for VariableScope to keep shards below `max_shard_bytes`.
This partitioner will shard a Variable along one axis, attempting to keep
the maximum shard size below `max_shard_bytes`. In practice, this is not
always possible when sharding along only one axis. When this happens,
this axis is sharded as much as possible (i.e., every dimension becomes
a separate shard).
If the partitioner hits the `max_shards` limit, then each shard may end up
larger than `max_shard_bytes`. By default `max_shards` equals `None` and no
limit on the number of shards is enforced.
One reasonable value for `max_shard_bytes` is `(64 << 20) - 1`, or almost
`64MB`, to keep below the protobuf byte limit.
Args:
max_shard_bytes: The maximum size any given shard is allowed to be.
axis: The axis to partition along. Default: outermost axis.
bytes_per_string_element: If the `Variable` is of type string, this provides
an estimate of how large each scalar in the `Variable` is.
max_shards: The maximum number of shards in int created taking precedence
over `max_shard_bytes`.
Returns:
A partition function usable as the `partitioner` argument to
`variable_scope`, `get_variable`, and `get_partitioned_variable_list`.
Raises:
ValueError: If any of the byte counts are non-positive.
"""
if max_shard_bytes < 1 or bytes_per_string_element < 1:
raise ValueError(
"Both max_shard_bytes and bytes_per_string_element must be positive.")
if max_shards and max_shards < 1:
raise ValueError(
"max_shards must be positive.")
def _partitioner(shape, dtype):
"""Partitioner that partitions shards to have max_shard_bytes total size.
Args:
shape: A `TensorShape`.
dtype: A `DType`.
Returns:
A tuple representing how much to slice each axis in shape.
Raises:
ValueError: If shape is not a fully defined `TensorShape` or dtype is not
a `DType`.
"""
if not isinstance(shape, tensor_shape.TensorShape):
raise ValueError("shape is not a TensorShape: %s" % shape)
if not shape.is_fully_defined():
raise ValueError("shape is not fully defined: %s" % shape)
if not isinstance(dtype, dtypes.DType):
raise ValueError("dtype is not a DType: %s" % dtype)
if dtype.base_dtype == dtypes.string:
element_size = bytes_per_string_element
else:
element_size = dtype.size
partitions = [1] * shape.ndims
bytes_per_slice = 1.0 * (
shape.num_elements() / shape[axis].value) * element_size
# How many slices can we fit on one shard of size at most max_shard_bytes?
# At least one slice is required.
slices_per_shard = max(1, math.floor(max_shard_bytes / bytes_per_slice))
# How many shards do we need for axis given that each shard fits
# slices_per_shard slices from a total of shape[axis].value slices?
axis_shards = int(math.ceil(1.0 * shape[axis].value / slices_per_shard))
if max_shards:
axis_shards = min(max_shards, axis_shards)
partitions[axis] = axis_shards
return partitions
return _partitioner
def min_max_variable_partitioner(max_partitions=1, axis=0,
min_slice_size=256 << 10,
bytes_per_string_element=16):
"""Partitioner to allocate minimum size per slice.
Returns a partitioner that partitions the variable of given shape and dtype
such that each partition has a minimum of `min_slice_size` slice of the
variable. The maximum number of such partitions (upper bound) is given by
`max_partitions`.
Args:
max_partitions: Upper bound on the number of partitions. Defaults to 1.
axis: Axis along which to partition the variable. Defaults to 0.
min_slice_size: Minimum size of the variable slice per partition. Defaults
to 256K.
bytes_per_string_element: If the `Variable` is of type string, this provides
an estimate of how large each scalar in the `Variable` is.
Returns:
A partition function usable as the `partitioner` argument to
`variable_scope`, `get_variable`, and `get_partitioned_variable_list`.
"""
def _partitioner(shape, dtype):
"""Partitioner that partitions list for a variable of given shape and type.
Ex: Consider partitioning a variable of type float32 with
shape=[1024, 1024].
If `max_partitions` >= 16, this function would return
[(1024 * 1024 * 4) / (256 * 1024), 1] = [16, 1].
If `max_partitions` < 16, this function would return
[`max_partitions`, 1].
Args:
shape: Shape of the variable.
dtype: Type of the variable.
Returns:
List of partitions for each axis (currently only one axis can be
partitioned).
Raises:
ValueError: If axis to partition along does not exist for the variable.
"""
if axis >= len(shape):
raise ValueError("Can not partition variable along axis %d when shape is "
"only %s" % (axis, shape))
if dtype.base_dtype == dtypes.string:
bytes_per_element = bytes_per_string_element
else:
bytes_per_element = dtype.size
total_size_bytes = shape.num_elements() * bytes_per_element
partitions = total_size_bytes / min_slice_size
partitions_list = [1] * len(shape)
# We can not partition the variable beyond what its shape or
# `max_partitions` allows.
partitions_list[axis] = max(1, min(shape[axis].value,
max_partitions,
int(math.ceil(partitions))))
return partitions_list
return _partitioner
def fixed_size_partitioner(num_shards, axis=0):
"""Partitioner to specify a fixed number of shards along given axis.
Args:
num_shards: `int`, number of shards to partition variable.
axis: `int`, axis to partition on.
Returns:
A partition function usable as the `partitioner` argument to
`variable_scope`, `get_variable`, and `get_partitioned_variable_list`.
"""
def _partitioner(shape, **unused_args):
partitions_list = [1] * len(shape)
partitions_list[axis] = min(num_shards, shape[axis].value)
return partitions_list
return _partitioner
def create_partitioned_variables(
shape, slicing, initializer, dtype=dtypes.float32,
trainable=True, collections=None, name=None, reuse=None):
"""Create a list of partitioned variables according to the given `slicing`.
Currently only one dimension of the full variable can be sliced, and the
full variable can be reconstructed by the concatenation of the returned
list along that dimension.
Args:
shape: List of integers. The shape of the full variable.
slicing: List of integers. How to partition the variable.
Must be of the same length as `shape`. Each value
indicate how many slices to create in the corresponding
dimension. Presently only one of the values can be more than 1;
that is, the variable can only be sliced along one dimension.
For convenience, The requested number of partitions does not have to
divide the corresponding dimension evenly. If it does not, the
shapes of the partitions are incremented by 1 starting from partition
0 until all slack is absorbed. The adjustment rules may change in the
future, but as you can save/restore these variables with different
slicing specifications this should not be a problem.
initializer: A `Tensor` of shape `shape` or a variable initializer
function. If a function, it will be called once for each slice,
passing the shape and data type of the slice as parameters. The
function must return a tensor with the same shape as the slice.
dtype: Type of the variables. Ignored if `initializer` is a `Tensor`.
trainable: If True also add all the variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`.
collections: List of graph collections keys to add the variables to.
Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
name: Optional name for the full variable. Defaults to
`"PartitionedVariable"` and gets uniquified automatically.
reuse: Boolean or `None`; if `True` and name is set, it would reuse
previously created variables. if `False` it will create new variables.
if `None`, it would inherit the parent scope reuse.
Returns:
A list of Variables corresponding to the slicing.
Raises:
ValueError: If any of the arguments is malformed.
"""
logging.warn(
"create_partitioned_variables is deprecated. Use "
"tf.get_variable with a partitioner set, or "
"tf.get_partitioned_variable_list, instead.")
if len(shape) != len(slicing):
raise ValueError("The 'shape' and 'slicing' of a partitioned Variable "
"must have the length: shape: %s, slicing: %s" %
(shape, slicing))
if len(shape) < 1:
raise ValueError("A partitioned Variable must have rank at least 1: "
"shape: %s" % shape)
# Legacy: we are provided the slicing directly, so just pass it to
# the partitioner.
partitioner = lambda **unused_kwargs: slicing
with variable_scope.variable_scope(
name, "PartitionedVariable", reuse=reuse):
# pylint: disable=protected-access
partitioned_var = variable_scope._get_partitioned_variable(
name=None,
shape=shape,
dtype=dtype,
initializer=initializer,
trainable=trainable,
partitioner=partitioner,
collections=collections)
return list(partitioned_var)
# pylint: enable=protected-access
| apache-2.0 |
lseyesl/phantomjs | src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreview_unittest.py | 122 | 2840 | # Copyright (C) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest2 as unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.tool.mocktool import MockOptions, MockTool
from webkitpy.tool.steps.updatechangelogswithreviewer import UpdateChangeLogsWithReviewer
class UpdateChangeLogsWithReviewerTest(unittest.TestCase):
def test_guess_reviewer_from_bug(self):
capture = OutputCapture()
step = UpdateChangeLogsWithReviewer(MockTool(), MockOptions())
expected_logs = "No reviewed patches on bug 50001, cannot infer reviewer.\n"
capture.assert_outputs(self, step._guess_reviewer_from_bug, [50001], expected_logs=expected_logs)
def test_guess_reviewer_from_multipatch_bug(self):
capture = OutputCapture()
step = UpdateChangeLogsWithReviewer(MockTool(), MockOptions())
expected_logs = "Guessing \"Reviewer2\" as reviewer from attachment 10001 on bug 50000.\n"
capture.assert_outputs(self, step._guess_reviewer_from_bug, [50000], expected_logs=expected_logs)
def test_empty_state(self):
capture = OutputCapture()
options = MockOptions()
options.reviewer = 'MOCK reviewer'
options.git_commit = 'MOCK git commit'
step = UpdateChangeLogsWithReviewer(MockTool(), options)
capture.assert_outputs(self, step.run, [{}])
| bsd-3-clause |
persandstrom/home-assistant | homeassistant/components/rainbird.py | 9 | 1244 | """
Support for Rain Bird Irrigation system LNK WiFi Module.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/rainbird/
"""
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (CONF_HOST, CONF_PASSWORD)
REQUIREMENTS = ['pyrainbird==0.1.6']
_LOGGER = logging.getLogger(__name__)
DATA_RAINBIRD = 'rainbird'
DOMAIN = 'rainbird'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up the Rain Bird component."""
conf = config[DOMAIN]
server = conf.get(CONF_HOST)
password = conf.get(CONF_PASSWORD)
from pyrainbird import RainbirdController
controller = RainbirdController()
controller.setConfig(server, password)
_LOGGER.debug("Rain Bird Controller set to: %s", server)
initial_status = controller.currentIrrigation()
if initial_status == -1:
_LOGGER.error("Error getting state. Possible configuration issues")
return False
hass.data[DATA_RAINBIRD] = controller
return True
| apache-2.0 |
amadu80/gtfsni | gtfsni/utils.py | 1 | 6232 |
import re
import string
import itertools
NORMALISATIONS = reversed(sorted([
('road', 'rd'),
('avenue', 'ave'),
('street', 'st'),
('place', 'pl'),
('estate', 'est'),
('pk', 'park'),
('sq', 'square'),
('stn', 'station'),
('cres', 'crescent'),
('cen', 'centre'),
('sth', 'south'),
('nth', 'north'),
('pde', 'parade'),
('drv', 'drive'),
('la', 'lane'), #Gray's Lane
('jct', 'junction'),
('fm ctr', 'farm'), #Dale farm
('mt', 'mount'),
('bus stop', ''),
('boucher rd, charles hurst', 'hursts, boucher crescent'),
("k'breda", 'knockbreda'),
('cemy', 'cemetery'),
('cemetry', 'cemetery'),
('st.james', 'st. james'),
('st.teresa', 'st. teresa'),
('st.theresa', 'st. teresa'),
('hospitals', 'hospital'), #Royal Victoria
('trossachs dr', 'trossachs'),
('kingsway park', 'kingsway'),
('george best', 'city'),
('sydenham by-pass', 'belfast'),
('skipper street', ''),
('hydebank r/bout', 'hydebank'),
('ligoniel, mountainhill', 'ligoniel'),
('mossley, glade', 'mossley(rail station)'),
('newton park, colby park', 'newton park(colby)'),
('donegall', 'donegal'),
('queens square albert clock', 'queens square'),
]))
rx_replace = re.compile(r'[^-\w\s,()/]').sub
rx_hyphenate = re.compile(r'[-\s,()/]+').sub
rx_normalise = [
(re.compile('\\b'+patt+'\\b'), repl) for patt, repl in NORMALISATIONS
]
def slugify(s):
s = str(s).strip().lower()
if not s:
return ''
for patt, repl in rx_normalise:
s = patt.sub(repl, s)
return rx_hyphenate('-', rx_replace('', s).strip()).strip('-')
direction2name = {0: 'Outbound', 1: 'Inbound'}
direction2code = {'Outbound': 0, 'Inbound': 1, 'outbound': 0, 'inbound': 1}
class MultiReplace:
def __init__(self, repl_dict):
# "compile" replacement dictionary
# assume char to char mapping
charmap = map(chr, range(256))
for k, v in repl_dict.items():
if len(k) != 1 or len(v) != 1:
self.charmap = None
break
charmap[ord(k)] = v
else:
self.charmap = string.join(charmap, "")
return
# string to string mapping; use a regular expression
keys = repl_dict.keys()
keys.sort() # lexical order
keys.reverse() # use longest match first
pattern = string.join(map(re.escape, keys), "|")
self.pattern = re.compile(pattern)
self.dict = repl_dict
def replace(self, str):
# apply replacement dictionary to string
if self.charmap:
return string.translate(str, self.charmap)
def repl(match, get=self.dict.get):
item = match.group(0)
return get(item, item)
return self.pattern.sub(repl, str)
daycodes = 'M T W TH F S SU'.split()
daynames = 'Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split()
daycode_to_name = dict(zip(daycodes, daynames))
replace_names = MultiReplace(dict(zip(daynames, daycodes))).replace
sdaycodes = ''.join(daycodes)
daycode_atomic_weights = [2**i for i in range(7, 0, -1)]
combinations = itertools.combinations
def iter_daycode_combos():
for i in xrange(1, 8):
for rng in combinations(daycodes, i):
names = [daycode_to_name[code] for code in rng]
id = ''.join(rng)
# the weight gives precedence to days that are earlier in the
# week, so that, for a given set of disjoint time periods,
# earlier periods can be displayed before later periods
# eg. Monday-Friday, Saturday, Sunday
# eg. "Monday, Wednesday, Friday" and "Tuesday, Thursday, Saturday"
weight = sum(2**(7-daycodes.index(s)) for s in rng)
if i == 1:
yield id, (weight, names[0])
else:
if len(rng) > 2 and id in sdaycodes:
# consecutive days, eg. Monday to Thursday
displayname = '%s to %s' % (names[0], names[-1])
# we output both options, eg. M-W and MTW
# this implies weight is not unique in resulting dataset
yield id, (weight, displayname)
yield '%s-%s' % (rng[0], rng[-1]), (weight, displayname)
else:
names[-2:] = ['%s and %s' % (names[-2], names[-1])]
displayname = ', '.join(names)
yield id, (weight, displayname)
timeframe_combinations = dict(iter_daycode_combos())
def get_time_period_name_and_weight(s):
"""
>>> get = get_time_period_name_and_weight
>>> name1, weight1 = get('Monday - Friday')
>>> name2, weight2 = get('M-F')
>>> name3, weight3 = get('MTWTHF')
>>> weight1 == weight2 == weight3
True
>>> name1 == name2 == name3
True
>>> name1
'Monday to Friday'
>>> get('WTHSU')
('Wednesday, Thursday and Sunday', 50)
Days can be retrieved from weight::
>>> assert 50 | (2**7) != 50
>>> assert 50 | (2**6) != 50
>>> assert 50 | (2**5) == 50 # Wednesday
>>> assert 50 | (2**4) == 50 # Thursday
>>> assert 50 | (2**3) != 50
>>> assert 50 | (2**2) != 50
>>> assert 50 | (2**1) == 50 # Sunday
Compare weights::
>>> weight1 = get('MWF')[1]
>>> weight2 = get('TTHS')[1]
>>> weight1 > weight2
True
>>> weight1 = get('M')[1]
>>> weight2 = get('T-SU')[1]
>>> weight1 > weight2
True
"""
weight, name = timeframe_combinations[''.join(replace_names(s).split()).upper()]
return name, weight
def split_timeframe(tf):
"""
>>> list(split_timeframe('M-F'))
[(0, 'M'), (1, 'T'), (2, 'W'), (3, 'TH'), (4, 'F')]
>>> list(split_timeframe('S'))
[(5, 'S')]
>>> list(split_timeframe('Th-Su'))
[(3, 'TH'), (4, 'F'), (5, 'S'), (6, 'SU')]
>>> list(split_timeframe('MFS'))
[(0, 'M'), (4, 'F'), (5, 'S')]
"""
name, weight = get_time_period_name_and_weight(tf)
for i, (w, daycode) in enumerate(zip(daycode_atomic_weights, daycodes)):
if weight & w:
yield i, daycode
if __name__ == '__main__':
import doctest
doctest.testmod()
| bsd-2-clause |
sam-m888/gramps | gramps/gui/editors/displaytabs/notemodel.py | 11 | 1708 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# GTK libraries
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
#-------------------------------------------------------------------------
#
# NoteModel
#
#-------------------------------------------------------------------------
class NoteModel(Gtk.ListStore):
def __init__(self, note_list, db):
Gtk.ListStore.__init__(self, str, str, bool, str)
self.db = db
for handle in note_list:
note = self.db.get_note_from_handle(handle)
text = note.get()[:85].replace('\n', ' ')
if len(text) > 80:
text = text[:80]+"..."
self.append(row=[
str(note.get_type()),
text,
note.get_privacy(),
handle,
])
| gpl-2.0 |
bobintetley/asm3 | src/asm3/publishers/helpinglostpets.py | 1 | 8638 |
import asm3.configuration
import asm3.i18n
import asm3.lostfound
from .base import FTPPublisher
from asm3.sitedefs import HELPINGLOSTPETS_FTP_HOST
import os
import sys
class HelpingLostPetsPublisher(FTPPublisher):
"""
Handles publishing to helpinglostpets.com
"""
def __init__(self, dbo, publishCriteria):
l = dbo.locale
publishCriteria.uploadDirectly = True
publishCriteria.thumbnails = False
publishCriteria.checkSocket = True
publishCriteria.scaleImages = 1
FTPPublisher.__init__(self, dbo, publishCriteria,
HELPINGLOSTPETS_FTP_HOST, asm3.configuration.helpinglostpets_user(dbo),
asm3.configuration.helpinglostpets_password(dbo))
self.initLog("helpinglostpets", asm3.i18n._("HelpingLostPets Publisher", l))
def hlpYesNo(self, condition):
"""
Returns a CSV entry for yes or no based on the condition
"""
if condition:
return "\"Yes\""
else:
return "\"No\""
def run(self):
if self.isPublisherExecuting(): return
self.updatePublisherProgress(0)
self.setLastError("")
self.setStartPublishing()
shelterid = asm3.configuration.helpinglostpets_orgid(self.dbo)
if shelterid == "":
self.setLastError("No helpinglostpets.com organisation ID has been set.")
return
foundanimals = asm3.lostfound.get_foundanimal_find_simple(self.dbo)
animals = self.getMatchingAnimals()
if len(animals) == 0 and len(foundanimals) == 0:
self.setLastError("No animals found to publish.")
self.cleanup()
return
if not self.openFTPSocket():
self.setLastError("Failed opening FTP socket.")
if self.logSearch("530 Login") != -1:
self.log("Found 530 Login incorrect: disabling HelpingLostPets publisher.")
asm3.configuration.publishers_enabled_disable(self.dbo, "hlp")
self.cleanup()
return
csv = []
# Found Animals
anCount = 0
for an in foundanimals:
try:
anCount += 1
self.log("Processing Found Animal: %d: %s (%d of %d)" % ( an["ID"], an["COMMENTS"], anCount, len(foundanimals)))
# If the user cancelled, stop now
if self.shouldStopPublishing():
self.log("User cancelled publish. Stopping.")
self.resetPublisherProgress()
return
csv.append( self.processFoundAnimal(an, shelterid) )
# Mark success in the log
self.logSuccess("Processed Found Animal: %d: %s (%d of %d)" % ( an["ID"], an["COMMENTS"], anCount, len(foundanimals)))
except Exception as err:
self.logError("Failed processing found animal: %s, %s" % (str(an["ID"]), err), sys.exc_info())
# Animals
anCount = 0
for an in animals:
try:
anCount += 1
self.log("Processing: %s: %s (%d of %d)" % ( an["SHELTERCODE"], an["ANIMALNAME"], anCount, len(animals)))
self.updatePublisherProgress(self.getProgress(anCount, len(animals)))
# If the user cancelled, stop now
if self.shouldStopPublishing():
self.log("User cancelled publish. Stopping.")
self.resetPublisherProgress()
return
# Upload one image for this animal
self.uploadImage(an, an["WEBSITEMEDIANAME"], an["SHELTERCODE"] + ".jpg")
csv.append( self.processAnimal(an, shelterid) )
# Mark success in the log
self.logSuccess("Processed: %s: %s (%d of %d)" % ( an["SHELTERCODE"], an["ANIMALNAME"], anCount, len(animals)))
except Exception as err:
self.logError("Failed processing animal: %s, %s" % (str(an["SHELTERCODE"]), err), sys.exc_info())
# Mark published
self.markAnimalsPublished(animals)
header = "OrgID, PetID, Status, Name, Species, Sex, PrimaryBreed, SecondaryBreed, Age, Altered, Size, ZipPostal, Description, Photo, Colour, MedicalConditions, LastUpdated\n"
filename = shelterid + ".txt"
self.saveFile(os.path.join(self.publishDir, filename), header + "\n".join(csv))
self.log("Uploading datafile %s" % filename)
self.upload(filename)
self.log("Uploaded %s" % filename)
self.log("-- FILE DATA --")
self.log(header + "\n".join(csv))
# Clean up
self.closeFTPSocket()
self.deletePublishDirectory()
self.saveLog()
self.setPublisherComplete()
def processFoundAnimal(self, an, shelterid=""):
"""
Processes a found animal and returns a CSV line
"""
line = []
# OrgID
line.append("\"%s\"" % shelterid)
# PetID
line.append("\"F%d\"" % an["ID"])
# Status
line.append("\"Found\"")
# Name
line.append("\"%d\"" % an["ID"])
# Species
line.append("\"%s\"" % an["SPECIESNAME"])
# Sex
line.append("\"%s\"" % an["SEXNAME"])
# PrimaryBreed
line.append("\"%s\"" % an["BREEDNAME"])
# SecondaryBreed
line.append("\"\"")
# Age, one of Baby, Young, Adult, Senior - just happens to match our default age groups
line.append("\"%s\"" % an["AGEGROUP"])
# Altered - don't have
line.append("\"\"")
# Size, one of Small, Medium or Large or X-Large - also don't have
line.append("\"\"")
# ZipPostal
line.append("\"%s\"" % an["AREAPOSTCODE"])
# Description
notes = str(an["DISTFEAT"]) + "\n" + str(an["COMMENTS"]) + "\n" + str(an["AREAFOUND"])
# Strip carriage returns
notes = notes.replace("\r\n", "<br />")
notes = notes.replace("\r", "<br />")
notes = notes.replace("\n", "<br />")
notes = notes.replace("\"", "“")
notes = notes.replace("\'", "‘")
notes = notes.replace("\`", "‘")
line.append("\"%s\"" % notes)
# Photo
line.append("\"\"")
# Colour
line.append("\"%s\"" % an["BASECOLOURNAME"])
# MedicalConditions
line.append("\"\"")
# LastUpdated
line.append("\"%s\"" % asm3.i18n.python2unix(an["LASTCHANGEDDATE"]))
return ",".join(line)
def processAnimal(self, an, shelterid=""):
""" Process an animal record and return a CSV line """
line = []
# OrgID
line.append("\"%s\"" % shelterid)
# PetID
line.append("\"A%d\"" % an["ID"])
# Status
line.append("\"Adoptable\"")
# Name
line.append("\"%s\"" % an["ANIMALNAME"])
# Species
line.append("\"%s\"" % an["SPECIESNAME"])
# Sex
line.append("\"%s\"" % an["SEXNAME"])
# PrimaryBreed
line.append("\"%s\"" % an["BREEDNAME1"])
# SecondaryBreed
if an["CROSSBREED"] == 1:
line.append("\"%s\"" % an["BREEDNAME2"])
else:
line.append("\"\"")
# Age, one of Baby, Young, Adult, Senior
ageinyears = asm3.i18n.date_diff_days(an["DATEOFBIRTH"], asm3.i18n.now(self.dbo.timezone))
ageinyears /= 365.0
agename = "Adult"
if ageinyears < 0.5: agename = "Baby"
elif ageinyears < 2: agename = "Young"
elif ageinyears < 9: agename = "Adult"
else: agename = "Senior"
line.append("\"%s\"" % agename)
# Altered
line.append("%s" % self.hlpYesNo(an["NEUTERED"] == 1))
# Size, one of Small, Medium or Large or X-Large
ansize = "Medium"
if an["SIZE"] == 0 : ansize = "X-Large"
elif an["SIZE"] == 1: ansize = "Large"
elif an["SIZE"] == 2: ansize = "Medium"
elif an["SIZE"] == 3: ansize = "Small"
line.append("\"%s\"" % ansize)
# ZipPostal
line.append("\"%s\"" % asm3.configuration.helpinglostpets_postal(self.dbo))
# Description
line.append("\"%s\"" % self.getDescription(an, True))
# Photo
line.append("\"%s.jpg\"" % an["SHELTERCODE"])
# Colour
line.append("\"%s\"" % an["BASECOLOURNAME"])
# MedicalConditions
line.append("\"%s\"" % an["HEALTHPROBLEMS"])
# LastUpdated
line.append("\"%s\"" % asm3.i18n.python2unix(an["LASTCHANGEDDATE"]))
return self.csvLine(line)
| gpl-3.0 |
miyakz1192/neutron | neutron/plugins/embrane/common/operation.py | 59 | 1466 | # Copyright 2013 Embrane, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Operation(object):
"""Defines a series of operations which shall be executed in order.
the operations expected are procedures, return values are discarded
"""
def __init__(self, procedure, args=(), kwargs={}, nextop=None):
self._procedure = procedure
self.args = args[:]
self.kwargs = dict(kwargs)
self.nextop = nextop
def execute(self):
args = self.args
self._procedure(*args, **self.kwargs)
return self.nextop
def execute_all(self):
nextop = self.execute()
while nextop:
nextop = self.execute_all()
def has_next(self):
return self.nextop is not None
def add_bottom_operation(self, operation):
op = self
while op.has_next():
op = op.nextop
op.nextop = operation
| apache-2.0 |
bmcculley/splinter | setup.py | 1 | 1210 | # -*- coding: utf-8 -*-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from setuptools import setup, find_packages
import codecs
README = codecs.open("README.rst", encoding="utf-8").read()
setup(
name="splinter",
version="0.9.0",
url="https://github.com/cobrateam/splinter",
description="browser abstraction for web acceptance testing",
long_description=README,
author="CobraTeam",
author_email="andrewsmedina@gmail.com",
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
]
+ [("Programming Language :: Python :: %s" % x) for x in "2.6 2.7 3.3 3.4".split()],
packages=find_packages(exclude=["docs", "tests", "samples"]),
include_package_data=True,
install_requires=["selenium>=3.14.0"],
extras_require={
"zope.testbrowser": ["zope.testbrowser>=5.2.4", "lxml>=4.2.4", "cssselect"],
"django": ["Django>=1.7.11,<1.12", "lxml>=2.3.6", "cssselect", "six"],
"flask": ["Flask>=1.0.2", "lxml>=2.3.6", "cssselect"],
},
tests_require=["coverage", "flask"],
)
| bsd-3-clause |
apexkid/Wikiapiary | apiary/tasks/website/statistics.py | 1 | 7516 | """Pull in statistics for sites."""
# pylint: disable=C0301
from apiary.tasks import BaseApiaryTask
import logging
import requests
import datetime
import re
LOGGER = logging.getLogger()
class GetStatisticsTask(BaseApiaryTask):
"""Collect statistics on usage from site."""
def run(self, site_id, site, method, api_url = None, stats_url = None):
"""Run the task."""
LOGGER.info("Retrieve get_statistics_stats for %d" % site_id)
if method == 'API':
# Go out and get the statistic information
data_url = api_url + '?action=query&meta=siteinfo&siprop=statistics&format=json'
LOGGER.info("Pulling statistics info from %s." % data_url)
status = False
try:
req = requests.get(
data_url,
timeout = 15,
verify = False,
headers = {
'User-Agent': 'Bumble Bee'
}
)
if req.status_code == requests.codes.ok:
data = req.json()
duration = req.elapsed.total_seconds()
status = True
else:
raise Exception('Did not get OK status code from API request')
except Exception, e:
raise Exception(e)
elif method == 'Statistics':
# Get stats the old fashioned way
data_url = stats_url
if "?" in data_url:
data_url += "&action=raw"
else:
data_url += "?action=raw"
LOGGER.info("Pulling statistics from %s." % data_url)
try:
# Get CSV data via raw Statistics call
req = requests.get(
data_url,
timeout = 30,
verify = False,
headers = {
'User-Agent': 'Bumble Bee'
}
)
duration = req.elapsed.total_seconds()
except Exception, e:
self.record_error(
site_id=site_id,
sitename=site,
log_message="%s" % e,
log_type='error',
log_severity='normal',
log_bot='Bumble Bee',
log_url=data_url
)
raise Exception('Invalid response from request for statistics from Statistics page')
else:
# Create an object that is the same as that returned by the API
ret_string = req.text.strip()
if re.match(r'(\w+=\d+)\;?', ret_string):
# The return value looks as we expected
status = True
data = {}
data['query'] = {}
data['query']['statistics'] = {}
items = ret_string.split(";")
for item in items:
(name, value) = item.split("=")
try:
# Convert the value to an int, if this fails we skip it
value = int(value)
if name == "total":
name = "pages"
if name == "good":
name = "articles"
LOGGER.debug("Transforming %s to %s" % (name, value))
data['query']['statistics'][name] = value
except:
LOGGER.warn("Illegal value '%s' for %s." % (value, name))
else:
status = False # The result didn't match the pattern expected
self.record_error(
site_id=site_id,
sitename=site,
log_message="Unexpected response to statistics call",
log_type='error',
log_severity='normal',
log_bot='Bumble Bee',
log_url=data_url
)
LOGGER.info("Result from statistics was not formatted as expected:\n%s" % ret_string)
ret_value = True
if status:
# Record the new data into the DB
LOGGER.info("JSON: %s" % data)
LOGGER.info("Duration: %s" % duration)
if 'query' in data:
# Record the data received to the database
sql_command = """
INSERT INTO statistics
(website_id, capture_date, response_timer, articles, jobs, users, admins, edits, activeusers, images, pages, views)
VALUES
(%s, '%s', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
data = data['query']['statistics']
if 'articles' in data:
articles = "%s" % data['articles']
else:
articles = 'null'
if 'jobs' in data:
jobs = "%s" % data['jobs']
else:
jobs = 'null'
if 'users' in data:
users = "%s" % data['users']
else:
users = 'null'
if 'admins' in data:
admins = "%s" % data['admins']
else:
admins = 'null'
if 'edits' in data:
edits = "%s" % data['edits']
else:
edits = 'null'
if 'activeusers' in data:
if data['activeusers'] < 0:
data['activeusers'] = 0
activeusers = "%s" % data['activeusers']
else:
activeusers = 'null'
if 'images' in data:
images = "%s" % data['images']
else:
images = 'null'
if 'pages' in data:
pages = "%s" % data['pages']
else:
pages = 'null'
if 'views' in data:
views = "%s" % data['views']
else:
views = 'null'
sql_command = sql_command % (
site_id,
self.sqlutcnow(),
duration,
articles,
jobs,
users,
admins,
edits,
activeusers,
images,
pages,
views)
self.runSql(sql_command)
else:
self.record_error(
site_id=site_id,
sitename=site,
log_message='Statistics returned unexpected JSON.',
log_type='info',
log_severity='normal',
log_bot='Bumble Bee',
log_url=data_url
)
raise Exception('Statistics returned unexpected JSON.')
else:
LOGGER.info("Did not receive valid data from %s" % (data_url))
raise Exception("Did not receive valid data from %s" % (data_url))
return ret_value
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.