text
stringlengths 6
947k
| repo_name
stringlengths 5
100
| path
stringlengths 4
231
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 6
947k
| score
float64 0
0.34
|
---|---|---|---|---|---|---|
# Copyright 2018 The Kubeflow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
import unittest
from kfp_component.google.dataproc import submit_pig_job
MODULE = 'kfp_component.google.dataproc._submit_pig_job'
@mock.patch(MODULE + '.submit_job')
class TestSubmitPigJob(unittest.TestCase):
def test_submit_pig_job_with_expected_payload(self, mock_submit_job):
submit_pig_job('mock-project', 'mock-region', 'mock-cluster',
job_id_output_path='/tmp/kfp/output/dataproc/job_id.txt',
queries=['select * from mock_table'],
script_variables={'var-1': 'value1'},
pig_job={ 'continueOnFailure': True },
job={ 'labels': {'key1': 'value1'}})
mock_submit_job.assert_called_with('mock-project', 'mock-region', 'mock-cluster',
{
'pigJob': {
'queryList': { 'queries': [
'select * from mock_table'
]},
'scriptVariables': {'var-1': 'value1'},
'continueOnFailure': True
},
'labels': {
'key1': 'value1'
}
}, 30, job_id_output_path='/tmp/kfp/output/dataproc/job_id.txt') | kubeflow/pipelines | components/gcp/container/component_sdk/python/tests/google/dataproc/test__submit_pig_job.py | Python | apache-2.0 | 1,768 | 0.007353 |
import json
import requests
from django.conf import settings
from website.calendar.models import WeatherTypes, Calendar
from django.conf import settings
from datetime import datetime
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Import the weather information"
def handle(self, **options):
params = {
'key':settings.APIXU_KEY,
'q':settings.APIXU_LOCATION,
'days':settings.APIXU_DAYS
}
r = requests.get('https://{0}'.format(settings.APIXU_URL), params=params)
if r.status_code == 200:
data = r.json()
for day in data['forecast']['forecastday']:
try:
date = datetime.strptime(day['date'], '%Y-%m-%d').timestamp()
sun_rise = datetime.strptime(day['astro']['sunrise'], '%I:%M %p').time()
sun_set = datetime.strptime(day['astro']['sunset'], '%I:%M %p').time()
temp = day['day']['maxtemp_c']
weath, creat = WeatherTypes.objects.get_or_create(
title=day['day']['condition']['text'],
class_code=day['day']['condition']['code'],
icon=day['day']['condition']['icon'],)
Calendar.data.addWeather(int(date),sun_rise, sun_set, temp, weath)
except Exception as exp:
print(exp)
else:
print(r.status_code)
| samsath/skeleton | src/website/calendar/management/commands/import_weather.py | Python | gpl-3.0 | 1,499 | 0.006004 |
import re
from bs4 import BeautifulSoup
from scripts.features.feature_extractor import FeatureExtractor
from scripts.data.cleaning import clean_code
def clean_html_tags(html_text):
soup = BeautifulSoup(html_text, 'html.parser')
if soup.find("h") is not None:
soup.find("h").extract()
cleaned_text = soup.get_text()
cleaned_text = ''.join(cleaned_text.splitlines())
return cleaned_text
def clean_code(html_text):
"""Qiitaのコードを取り除きます
:param html_text:
:return:
"""
soup = BeautifulSoup(html_text, 'html.parser')
[x.extract() for x in soup.findAll(class_="code-frame")]
[x.extract() for x in soup.findAll("code")]
cleaned_text = soup.get_text()
cleaned_text = ''.join(cleaned_text.splitlines())
return cleaned_text
def cleaning(text):
replaced_text = clean_code(html_text=text) # remove source code
replaced_text = clean_html_tags(html_text=replaced_text) # remove html tag
replaced_text = re.sub(r'\$.*?\$+', '', replaced_text) # remove math equation
replaced_text = re.sub(r'[@@]\w+', '', replaced_text) # remove @mention
replaced_text = re.sub(r'https?:\/\/.*?([\r\n ]|$)', '', replaced_text) # remove URL
replaced_text = re.sub(r' ', '', replaced_text) # remove zenkaku space
return replaced_text
class RenderedBodyPreprocessor():
def clean_rendered_body(self, rendered_body):
cleaned_rendered_body = cleaning(rendered_body)
return cleaned_rendered_body
class CharacterRatio():
def __init__(self, regex_text, text):
self.regex = regex_text
self.text = text
def character_ratio(self):
pattern = re.compile(self.regex)
count = len(re.findall(pattern, self.text))
ratio = 0 if len(self.text) == 0 else count / len(self.text)
return ratio
class KanjiRatioExtractor(FeatureExtractor):
def __init__(self, cleaned_rendered_body):
self.regex_text = '[一-龥]'
self.character_ratio = CharacterRatio(self.regex_text, cleaned_rendered_body)
def extract(self, post, extracted=None):
ratio = self.character_ratio.character_ratio()
return ratio
class HiraganaRatioExtractor(FeatureExtractor):
def __init__(self, cleaned_rendered_body):
self.regex_text = '[ぁ-ん]'
self.character_ratio = CharacterRatio(self.regex_text, cleaned_rendered_body)
def extract(self, post, extracted=None):
ratio = self.character_ratio.character_ratio()
return ratio
class KatakanaRatioExtractor(FeatureExtractor):
def __init__(self, cleaned_rendered_body):
self.regex_text = '[ァ-ン]'
self.character_ratio = CharacterRatio(self.regex_text, cleaned_rendered_body)
def extract(self, post, extracted=None):
ratio = self.character_ratio.character_ratio()
return ratio
class AlphabetRatioExtractor(FeatureExtractor):
def __init__(self, cleaned_rendered_body):
self.regex_text = '[a-xA-Z]'
self.character_ratio = CharacterRatio(self.regex_text, cleaned_rendered_body)
def extract(self, post, extracted=None):
ratio = self.character_ratio.character_ratio()
return ratio
class NumberRatioExtractor(FeatureExtractor):
def __init__(self, cleaned_rendered_body):
self.regex_text = '[0-9]'
self.character_ratio = CharacterRatio(self.regex_text, cleaned_rendered_body)
def extract(self, post, extracted=None):
ratio = self.character_ratio.character_ratio()
return ratio
class PunctuationRatioExtractor(FeatureExtractor):
def __init__(self, cleaned_rendered_body):
self.regex_text = '[、]'
self.character_ratio = CharacterRatio(self.regex_text, cleaned_rendered_body)
def extract(self, post, extracted=None):
ratio = self.character_ratio.character_ratio()
return ratio
| chakki-works/elephant_sense | scripts/features/charactor_extractor.py | Python | apache-2.0 | 3,901 | 0.002072 |
# TODO: let's see if we can get rid of this, it's garbage
from django.contrib.admin import options, actions, sites
from django.template import loader
import jingo
def django_to_jinja(template_name, context, **kw):
"""
We monkeypatch Django admin's render_to_response to work in our Jinja
environment. We have an admin/base_site.html template that Django's
templates inherit, but instead of rendering html, it renders the Django
pieces into a Jinja template. We get all of Django's html, but wrapped in
our normal site structure.
"""
context_instance = kw.pop('context_instance')
source = loader.render_to_string(template_name, context, context_instance)
request = context_instance['request']
return jingo.render(request, jingo.env.from_string(source))
actions.render_to_response = django_to_jinja
options.render_to_response = django_to_jinja
sites.render_to_response = django_to_jinja
def jinja_for_django(template_name, context=None, **kw):
"""
If you want to use some built in logic (or a contrib app) but need to
override the templates to work with Jinja, replace the object's
render_to_response function with this one. That will render a Jinja
template through Django's functions. An example can be found in the users
app.
"""
if context is None:
context = {}
context_instance = kw.pop('context_instance')
request = context_instance['request']
for d in context_instance.dicts:
context.update(d)
return jingo.render(request, template_name, context, **kw)
| akatsoulas/mozillians | lib/jinjautils.py | Python | bsd-3-clause | 1,577 | 0 |
import re
import sys
import struct
import codecs
class REMatcher(object):
def __init__(self, matchstring):
self.matchstring = matchstring
def match(self,regexp):
self.rematch = re.match(regexp, self.matchstring, re.IGNORECASE)
return bool(self.rematch)
def group(self,i):
return self.rematch.group(i)
def groups(self):
return self.rematch.groups()
class Assembler:
def checkInCode(self):
if not self.in_code:
print "Error in line " + str(self.line_count) + ": Instruction not in code section"
exit()
def checkInData(self):
if self.in_code:
print "Error in line " + str(self.line_count) + " Instruction not in data section"
exit()
def writefile(self, file):
with open(file, "wb") as output:
for byte in self.code:
output.write(byte)
output.close()
def push24(self, num):
b = bytearray(struct.pack('>I', num))
self.code.append(chr(b[1]))
self.code.append(chr(b[2]))
self.code.append(chr(b[3]))
def push8(self, num):
self.code.append(chr(num))
def newlabel(self, label):
if label != None:
if label in self.labels:
self.printerror("Label " + m.group(2) + ": is duplicated")
else:
self.labels[label] = self.inst_addr
def enqueuelabel(self, group, position):
# if relative:
# self.labelpass.append({ "label": group.strip("\(\)"), "position": self.inst_addr+1, "inst_address": self.inst_addr })
# else:
self.labelpass.append({ "label": group.strip("\(\)"), "position": position })
def printerror(self, text):
print "Error in line " + str(self.line_count) + ": " + text
exit()
def parse_line(self, line):
line = line.strip(" \t\n\r")
# Remove comments if not inside string
if re.match(".*?#.*", line):
if not re.match("[^']*'[^#]*#[^']*", line):
line = re.sub("\s*#.*", "", line)
m = REMatcher(line.strip(" \t\n\r"))
if line == '': # Empty line
pass
elif m.match("(\w+)\:\Z"): # Labels
if m.group(1) in self.labels:
self.printerror("Label \'" + m.group(1) + ":\'' is duplicated")
else:
self.labels[m.group(1)] = self.inst_addr
elif m.match("\.code\Z"): # Section.code
self.in_code = True
elif m.match("\.data\Z"): # Section .data
self.in_code = False
elif m.match(self.LABEL + "\.DS\s+(?:\'|\")(.+)(?:\'|\")\Z"): # Data String
self.checkInData()
self.newlabel(m.group(1))
i = 0
for char in m.group(2):
self.push8( ord(char.encode('latin-1')) )
i += 1
if i % 3 == 0:
self.inst_addr += 1
self.push8(0x00) # String terminator
i += 1
# Fix word alignment
while i % 3 != 0:
self.push8(0x00)
i += 1
self.inst_addr += 1
elif m.match(self.LABEL + "\.DW\s+(" + self.HEX + ")\Z"): # Data Word
self.checkInData()
self.newlabel(m.group(1))
self.push24(int(m.group(2), 0))
self.inst_addr += 1
elif m.match(self.LABEL + "CALL\Z" + self.sep + "(" + self.HEX + "|\(" + self.ALPHANUMERIC + "\))"):
self.newlabel(m.group(1))
self.inst_CALL(m)
elif m.match(self.LABEL + "LD" + self.spc +
"(" + self.REG + ")" + self.sep +
"(" + self.REG + "|" + self.HEX + "|" + self.INT + "|\(" + self.ALPHANUMERIC + "\))"
):
self.newlabel(m.group(1))
self.inst_LD(m)
elif m.match(self.LABEL + "DBG" + self.spc + "(" + self.REG + ")"):
self.newlabel(m.group(1))
self.inst_DBG(m)
elif m.match(self.LABEL + "HALT\Z"):
self.newlabel(m.group(1))
self.inst_HALT(m)
elif m.match(self.LABEL + "MR" + self.spc +
"(" + self.REG + ")" + self.sep +
"(\[" + self.REG + "\]|" + self.HEX + "|\(" + self.ALPHANUMERIC + "\))" +
self.OFFSET + "\Z"
):
self.newlabel(m.group(1))
self.inst_MR(m)
elif m.match(self.LABEL + "MW" + self.spc + "(\[" + self.REG + "\]|" + self.HEX + "|\(" + self.ALPHANUMERIC + "\))" + self.OFFSET + self.sep + "(" + self.REG + ")\Z"):
self.newlabel(m.group(1))
self.inst_MW(m)
elif m.match(self.LABEL + "NOP\Z"):
self.newlabel(m.group(1))
self.inst_NOP(m)
elif m.match(self.LABEL + "POP\Z" + self.sep + "(" + self.REG + ")"):
self.newlabel(m.group(1))
self.inst_POP(m)
elif m.match(self.LABEL + "PUSH\Z" + self.sep + "(" + self.REG + ")"):
self.newlabel(m.group(1))
self.inst_PUSH(m)
elif m.match(self.LABEL + "RET\Z"):
self.newlabel(m.group(1))
self.inst_RET(m)
elif m.match(self.LABEL + "VR" + self.spc + "(" + self.REG + ")" + self.sep + "(\[" + self.REG + "\]|" + self.HEX + ")" + self.OFFSET + "\Z"):
self.newlabel(m.group(1))
self.inst_VR(m)
elif m.match(self.LABEL + "VW" + self.spc + "(\[" + self.REG + "\]|" + self.HEX + ")" + self.OFFSET + self.sep + "(" + self.REG + ")\Z"):
self.newlabel(m.group(1))
self.inst_VW(m)
else:
self.printerror("Syntax error")
self.line_count += 1
if self.inst_addr > 0xffffff:
print "Error: The assembled binary will excess the maximum size of 0xffffff words"
exit()
def second_pass(self):
for item in self.labelpass:
if item['label'] not in self.labels:
print "Label '" + item['label'] + "' doesn't exist"
exit()
#if item['inst_address'] != None:
# b = bytearray(struct.pack('>I', self.labels[item['label']] - item['inst_address']))
#else:
b = bytearray(struct.pack('>I', self.labels[item['label']]))
addr = item['position']*3
self.code[addr] = chr(b[1])
self.code[addr+1] = chr(b[2])
self.code[addr+2] = chr(b[3])
def assemble(self, file):
self.line_count = 1;
self.instructions = []
self.code = []
self.labelpass = []
self.labels = dict()
self.inst_addr = 0
self.in_code = True
with codecs.open(file, 'r', encoding='utf-8') as source_file:
for line in source_file:
self.parse_line(line)
source_file.close()
self.second_pass()
| MoebiuZ/OpcodeOne | oldfiles/oldcode/tools/assemblerold/functions.py | Python | apache-2.0 | 5,835 | 0.048517 |
from __future__ import division
from pyglet.gl import gl, glu
class ModelView(object):
'''
Manage modelview matrix, performing the MVC's 'view' parts of the 'camera'
'''
def __init__(self, camera):
self.camera = camera
def set_identity(self):
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glLoadIdentity()
def set_world(self):
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glLoadIdentity()
position = self.camera.position
look_at = self.camera.look_at
glu.gluLookAt(
position.x, position.y, position.z,
look_at.x, look_at.y, look_at.z,
0, 1, -1)
| tartley/pyweek11-cube | source/view/modelview.py | Python | bsd-3-clause | 682 | 0.001466 |
"""
WSGI config for WeatherForecast project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WeatherForecast.settings")
application = get_wsgi_application()
| vinicius-ronconi/WeatherForecast | WeatherForecast/wsgi.py | Python | mit | 408 | 0 |
from argparse import ArgumentParser
import numpy as np
from mpi4py import MPI
from pySDC.helpers.stats_helper import filter_stats, sort_stats
from pySDC.implementations.collocation_classes.gauss_radau_right import CollGaussRadau_Right
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.problem_classes.AllenCahn_Temp_MPIFFT import allencahn_temp_imex
from pySDC.implementations.transfer_classes.TransferMesh_MPIFFT import fft_to_fft
from pySDC.projects.AllenCahn_Bayreuth.AllenCahn_dump import dump
def run_simulation(name=None, nprocs_space=None):
"""
A simple test program to do PFASST runs for the AC equation
"""
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
# split world communicator to create space-communicators
if nprocs_space is not None:
color = int(world_rank / nprocs_space)
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
space_size = space_comm.Get_size()
space_rank = space_comm.Get_rank()
# split world communicator to create time-communicators
if nprocs_space is not None:
color = int(world_rank % nprocs_space)
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
time_size = time_comm.Get_size()
time_rank = time_comm.Get_rank()
# initialize level parameters
level_params = dict()
level_params['restol'] = 1E-08
level_params['dt'] = 1E-03
level_params['nsweeps'] = [3, 1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['collocation_class'] = CollGaussRadau_Right
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['L'] = 16.0
problem_params['nvars'] = [(48 * 48, 48 * 48), (8 * 48, 8 * 48)]
problem_params['eps'] = [0.04]
problem_params['radius'] = 0.25
problem_params['TM'] = 1.0
problem_params['D'] = 1.0
problem_params['dw'] = [300.0]
problem_params['comm'] = space_comm
problem_params['name'] = name
problem_params['init_type'] = 'circle_rand'
problem_params['spectral'] = True
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20 if space_rank == 0 else 99 # set level depending on rank
controller_params['hook_class'] = dump
controller_params['predict_type'] = 'fine_only'
# fill description dictionary for easy step instantiation
description = dict()
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = fft_to_fft
description['problem_class'] = allencahn_temp_imex
# set time parameters
t0 = 0.0
Tend = 100 * 0.001
if space_rank == 0 and time_rank == 0:
out = f'---------> Running {name} with {time_size} process(es) in time and {space_size} process(es) in space...'
print(out)
# instantiate controller
controller = controller_MPI(controller_params=controller_params, description=description, comm=time_comm)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
if space_rank == 0:
print()
# convert filtered statistics to list of iterations count, sorted by time
iter_counts = sort_stats(filter_stats(stats, type='niter'), sortby='time')
niters = np.array([item[1] for item in iter_counts])
out = f'Mean number of iterations on rank {time_rank}: {np.mean(niters):.4f}'
print(out)
timing = sort_stats(filter_stats(stats, type='timing_setup'), sortby='time')
out = f'Setup time on rank {time_rank}: {timing[0][1]:.4f} sec.'
print(out)
timing = sort_stats(filter_stats(stats, type='timing_run'), sortby='time')
out = f'Time to solution on rank {time_rank}: {timing[0][1]:.4f} sec.'
print(out)
if __name__ == "__main__":
# Add parser to get number of processors in space and setup (have to do this here to enable automatic testing)
parser = ArgumentParser()
parser.add_argument("-n", "--nprocs_space", help='Specifies the number of processors in space', type=int)
args = parser.parse_args()
name = 'AC-bench-tempforce'
run_simulation(name=name, nprocs_space=args.nprocs_space)
| Parallel-in-Time/pySDC | pySDC/projects/AllenCahn_Bayreuth/run_temp_forcing_benchmark.py | Python | bsd-2-clause | 5,134 | 0.002922 |
################################################################################
# Copyright (C) 2014 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
"""
import numpy as np
from bayespy.utils import misc
from .node import Node, Moments
from .deterministic import Deterministic
from .categorical import CategoricalMoments
from .concatenate import Concatenate
class Gate(Deterministic):
"""
Deterministic gating of one node.
Gating is performed over one plate axis.
Note: You should not use gating for several variables which parents of a
same node if the gates use the same gate assignments. In such case, the
results will be wrong. The reason is a general one: A stochastic node may
not be a parent of another node via several paths unless at most one path
has no other stochastic nodes between them.
"""
def __init__(self, Z, X, gated_plate=-1, moments=None, **kwargs):
"""
Constructor for the gating node.
Parameters
----------
Z : Categorical-like node
A variable which chooses the index along the gated plate axis
X : node
The node whose plate axis is gated
gated_plate : int (optional)
The index of the plate axis to be gated (by default, -1, that is,
the last axis).
"""
if gated_plate >= 0:
raise ValueError("Cluster plate must be negative integer")
self.gated_plate = gated_plate
if moments is not None:
X = self._ensure_moments(
X,
moments.__class__,
**moments.get_instance_conversion_kwargs()
)
if not isinstance(X, Node):
raise ValueError("X must be a node or moments should be provided")
X_moments = X._moments
self._moments = X_moments
dims = X.dims
if len(X.plates) < abs(gated_plate):
raise ValueError("The gated node does not have a plate axis is "
"gated")
K = X.plates[gated_plate]
Z = self._ensure_moments(Z, CategoricalMoments, categories=K)
self._parent_moments = (Z._moments, X_moments)
if Z.dims != ( (K,), ):
raise ValueError("Inconsistent number of clusters")
self.K = K
super().__init__(Z, X, dims=dims, **kwargs)
def _compute_moments(self, u_Z, u_X):
"""
"""
u = []
for i in range(len(u_X)):
# Make the moments of Z and X broadcastable and move the gated plate
# to be the last axis in the moments, then sum-product over that
# axis
ndim = len(self.dims[i])
z = misc.add_trailing_axes(u_Z[0], ndim)
z = misc.moveaxis(z, -ndim-1, -1)
gated_axis = self.gated_plate - ndim
if np.ndim(u_X[i]) < abs(gated_axis):
x = misc.add_trailing_axes(u_X[i], 1)
else:
x = misc.moveaxis(u_X[i], gated_axis, -1)
ui = misc.sum_product(z, x, axes_to_sum=-1)
u.append(ui)
return u
def _compute_message_to_parent(self, index, m_child, u_Z, u_X):
"""
"""
if index == 0:
m0 = 0
# Compute Child * X, sum over variable axes and move the gated axis
# to be the last. Need to do some shape changing in order to make
# Child and X to broadcast properly.
for i in range(len(m_child)):
ndim = len(self.dims[i])
c = m_child[i][...,None]
c = misc.moveaxis(c, -1, -ndim-1)
gated_axis = self.gated_plate - ndim
x = u_X[i]
if np.ndim(x) < abs(gated_axis):
x = np.expand_dims(x, -ndim-1)
else:
x = misc.moveaxis(x, gated_axis, -ndim-1)
axes = tuple(range(-ndim, 0))
m0 = m0 + misc.sum_product(c, x, axes_to_sum=axes)
# Make sure the variable axis does not use broadcasting
m0 = m0 * np.ones(self.K)
# Send the message
m = [m0]
return m
elif index == 1:
m = []
for i in range(len(m_child)):
# Make the moments of Z and the message from children
# broadcastable. The gated plate is handled as the last axis in
# the arrays and moved to the correct position at the end.
# Add variable axes to Z moments
ndim = len(self.dims[i])
z = misc.add_trailing_axes(u_Z[0], ndim)
z = misc.moveaxis(z, -ndim-1, -1)
# Axis index of the gated plate
gated_axis = self.gated_plate - ndim
# Add the gate axis to the message from the children
c = misc.add_trailing_axes(m_child[i], 1)
# Compute the message to parent
mi = z * c
# Add extra axes if necessary
if np.ndim(mi) < abs(gated_axis):
mi = misc.add_leading_axes(mi,
abs(gated_axis) - np.ndim(mi))
# Move the axis to the correct position
mi = misc.moveaxis(mi, -1, gated_axis)
m.append(mi)
return m
else:
raise ValueError("Invalid parent index")
def _compute_weights_to_parent(self, index, weights):
"""
"""
if index == 0:
return weights
elif index == 1:
if self.gated_plate >= 0:
raise ValueError("Gated plate axis must be negative")
return (
np.expand_dims(weights, axis=self.gated_plate)
if np.ndim(weights) >= abs(self.gated_plate) else
weights
)
else:
raise ValueError("Invalid parent index")
def _compute_plates_to_parent(self, index, plates):
"""
"""
if index == 0:
return plates
elif index == 1:
plates = list(plates)
# Add the cluster plate axis
if self.gated_plate < 0:
knd = len(plates) + self.gated_plate + 1
else:
raise RuntimeError("Cluster plate axis must be negative")
plates.insert(knd, self.K)
return tuple(plates)
else:
raise ValueError("Invalid parent index")
def _compute_plates_from_parent(self, index, plates):
"""
"""
if index == 0:
return plates
elif index == 1:
plates = list(plates)
# Remove the cluster plate, if the parent has it
if len(plates) >= abs(self.gated_plate):
plates.pop(self.gated_plate)
return tuple(plates)
else:
raise ValueError("Invalid parent index")
def Choose(z, *nodes):
"""Choose plate elements from nodes based on a categorical variable.
For instance:
.. testsetup::
from bayespy.nodes import *
.. code-block:: python
>>> import bayespy as bp
>>> z = [0, 0, 2, 1]
>>> x0 = bp.nodes.GaussianARD(0, 1)
>>> x1 = bp.nodes.GaussianARD(10, 1)
>>> x2 = bp.nodes.GaussianARD(20, 1)
>>> x = bp.nodes.Choose(z, x0, x1, x2)
>>> print(x.get_moments()[0])
[ 0. 0. 20. 10.]
This is basically just a thin wrapper over applying Gate node over the
concatenation of the nodes.
"""
categories = len(nodes)
z = Deterministic._ensure_moments(
z,
CategoricalMoments,
categories=categories
)
nodes = [node[...,None] for node in nodes]
combined = Concatenate(*nodes)
return Gate(z, combined)
| bayespy/bayespy | bayespy/inference/vmp/nodes/gate.py | Python | mit | 7,980 | 0.001504 |
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QPixmap
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QWidget
import qtUtils
from utils import constants
from utils import errors
from utils import utils
class QNickInputWidget(QWidget):
def __init__(self, image, imageWidth, connectClickedSlot, nick='', parent=None):
QWidget.__init__(self, parent)
self.connectClickedSlot = connectClickedSlot
# Image
self.image = QLabel(self)
self.image.setPixmap(QPixmap(qtUtils.getAbsoluteImagePath(image)).scaledToWidth(imageWidth, Qt.SmoothTransformation))
# Nick field
self.nickLabel = QLabel("Nickname:", self)
self.nickEdit = QLineEdit(nick, self)
self.nickEdit.setMaxLength(constants.NICK_MAX_LEN)
self.nickEdit.returnPressed.connect(self.__connectClicked)
# Connect button
self.connectButton = QPushButton("Connect", self)
self.connectButton.resize(self.connectButton.sizeHint())
self.connectButton.setAutoDefault(False)
self.connectButton.clicked.connect(self.__connectClicked)
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(self.nickLabel)
hbox.addWidget(self.nickEdit)
hbox.addStretch(1)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
vbox.addWidget(self.connectButton)
vbox.addStretch(1)
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(self.image)
hbox.addSpacing(10)
hbox.addLayout(vbox)
hbox.addStretch(1)
self.setLayout(hbox)
def __connectClicked(self):
nick = str(self.nickEdit.text()).lower()
# Validate the given nick
nickStatus = utils.isValidNick(nick)
if nickStatus == errors.VALID_NICK:
self.connectClickedSlot(nick)
elif nickStatus == errors.INVALID_NICK_CONTENT:
QMessageBox.warning(self, errors.TITLE_INVALID_NICK, errors.INVALID_NICK_CONTENT)
elif nickStatus == errors.INVALID_NICK_LENGTH:
QMessageBox.warning(self, errors.TITLE_INVALID_NICK, errors.INVALID_NICK_LENGTH)
elif nickStatus == errors.INVALID_EMPTY_NICK:
QMessageBox.warning(self, errors.TITLE_EMPTY_NICK, errors.EMPTY_NICK)
| kostyll/Cryptully | cryptully/qt/qNickInputWidget.py | Python | gpl-3.0 | 2,500 | 0.0024 |
# Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import fixtures
from oslo_policy import policy as oslo_policy
from oslo_serialization import jsonutils
import six
import nova.conf
from nova.conf import paths
from nova import policies
import nova.policy
from nova.tests.unit import fake_policy
CONF = nova.conf.CONF
class RealPolicyFixture(fixtures.Fixture):
"""Load the live policy for tests.
A base policy fixture that starts with the assumption that you'd
like to load and enforce the shipped default policy in tests.
Provides interfaces to tinker with both the contents and location
of the policy file before loading to allow overrides. To do this
implement ``_prepare_policy`` in the subclass, and adjust the
``policy_file`` accordingly.
"""
def _prepare_policy(self):
"""Allow changing of the policy before we get started"""
pass
def setUp(self):
super(RealPolicyFixture, self).setUp()
# policy_file can be overridden by subclasses
self.policy_file = paths.state_path_def('etc/nova/policy.json')
self._prepare_policy()
CONF.set_override('policy_file', self.policy_file, group='oslo_policy')
nova.policy.reset()
nova.policy.init()
self.addCleanup(nova.policy.reset)
def set_rules(self, rules):
policy = nova.policy._ENFORCER
policy.set_rules(oslo_policy.Rules.from_dict(rules))
def add_missing_default_rules(self, rules):
"""Adds default rules and their values to the given rules dict.
The given rulen dict may have an incomplete set of policy rules.
This method will add the default policy rules and their values to
the dict. It will not override the existing rules.
"""
for rule in policies.list_rules():
if rule.name not in rules:
rules[rule.name] = rule.check_str
class PolicyFixture(RealPolicyFixture):
"""Load a fake policy from nova.tests.unit.fake_policy
This overrides the policy with a completely fake and synthetic
policy file.
NOTE(sdague): the use of this is deprecated, and we should unwind
the tests so that they can function with the real policy. This is
mostly legacy because our default test instances and default test
contexts don't match up. It appears that in many cases fake_policy
was just modified to whatever makes tests pass, which makes it
dangerous to be used in tree. Long term a NullPolicy fixture might
be better in those cases.
"""
def _prepare_policy(self):
self.policy_dir = self.useFixture(fixtures.TempDir())
self.policy_file = os.path.join(self.policy_dir.path,
'policy.json')
# load the fake_policy data and add the missing default rules.
policy_rules = jsonutils.loads(fake_policy.policy_data)
self.add_missing_default_rules(policy_rules)
with open(self.policy_file, 'w') as f:
jsonutils.dump(policy_rules, f)
CONF.set_override('policy_dirs', [], group='oslo_policy')
class RoleBasedPolicyFixture(RealPolicyFixture):
"""Load a modified policy which allows all actions only be a single roll.
This fixture can be used for testing role based permissions as it
provides a version of the policy which stomps over all previous
declaration and makes every action only available to a single
role.
NOTE(sdague): we could probably do this simpler by only loading a
single default rule.
"""
def __init__(self, role="admin", *args, **kwargs):
super(RoleBasedPolicyFixture, self).__init__(*args, **kwargs)
self.role = role
def _prepare_policy(self):
with open(CONF.oslo_policy.policy_file) as fp:
policy = fp.read()
policy = jsonutils.loads(policy)
self.add_missing_default_rules(policy)
# Convert all actions to require specified role
for action, rule in six.iteritems(policy):
policy[action] = 'role:%s' % self.role
self.policy_dir = self.useFixture(fixtures.TempDir())
self.policy_file = os.path.join(self.policy_dir.path,
'policy.json')
with open(self.policy_file, 'w') as f:
jsonutils.dump(policy, f)
| cloudbase/nova | nova/tests/unit/policy_fixture.py | Python | apache-2.0 | 4,908 | 0.000204 |
#-------------------------------------------------------------------------------
# Copyright 2017 Cognizant Technology Solutions
#
# 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 ....core.BaseAgent import BaseAgent
import json
import math
import datetime
from dateutil import parser
class QtestAgent (BaseAgent):
@BaseAgent.timed
def process(self):
baseUrl = self.config.get('baseUrl', '')
userName = self.getCredential('userid')
password = self.getCredential('passwd')
startFrom = self.config.get('startFrom') + '+00:00'
startFromDate = parser.parse(startFrom, ignoretz=True)
pageSize = self.config.get('responsePageSize', 100)
dynamicTemplate = self.config.get("dynamicTemplate", {})
almEntities = dynamicTemplate.get('almEntities', {})
metadata = dynamicTemplate.get("almEntityMetaData", None)
isHistoryApi = self.config.get('isHistoryApi', False)
automationType = dict()
idChunkSize = 10
if isHistoryApi:
automationConfig = dynamicTemplate.get("automationType", {})
automationType = automationConfig.get("test-cases", automationType)
idChunkSize = self.config.get('historyIdChunkSize', idChunkSize)
testRunTypes = dynamicTemplate.get('testRunsType', {})
if 'test-runs' in almEntities:
for testRunType in testRunTypes:
almEntities[testRunType] = almEntities.get('test-runs', {})
almEntities.pop('test-runs', {})
payloadConfig = dict()
for entityType in almEntities:
payloadConfig[entityType] = dict()
payload = dict()
payload['fields'] = ['*']
entity = entityType
if entityType in testRunTypes:
testRunType = testRunTypes[entityType]
payload['query'] = testRunType.get('query') + " and " + "'Last Modified Date' >= '%s'"
entity = 'test-runs'
payloadConfig[entityType]['automation'] = testRunType.get('automation')
else:
payload['query'] = "'Last Modified Date' >= '%s'"
payload['object_type'] = entity
payloadConfig[entityType]['payload'] = json.dumps(payload)
payloadConfig[entityType]['entity'] = entity
encodeKey = 'InSightsAlmAgent:'
authKey = base64.b64encode(encodeKey.encode('utf-8'))
token = self.login(baseUrl, userName, password, authKey)
bearerToken = 'bearer ' + token if token else None
apiHeaders = {'Content-Type': 'application/json', 'accept': 'application/json', 'Authorization': bearerToken}
projectData = self.getResponse(baseUrl + "/api/v3/projects?assigned=false", 'GET', None, None, None, None, apiHeaders)
injectData = dict()
try:
for project in projectData:
projectId = project.get('id', -1)
projectIdStr = str(projectId)
projectName = project.get('name', '')
projectUrl = baseUrl + '/api/v3/projects/' + projectIdStr
searchUrl = projectUrl + '/search?page={0}&pageSize={1}'
historyUrl = projectUrl + "/histories?page={0}&pageSize={1}"
if projectIdStr not in self.tracking:
self.tracking[projectIdStr] = dict()
projectTrackingDetails = self.tracking[projectIdStr]
injectData['projectId'] = projectId
injectData['projectName'] = projectName
for entity in payloadConfig:
idList = list()
toolsData = list()
responseTemplate = almEntities[entity]
if entity not in projectTrackingDetails:
lastTracked = startFrom
lastTrackedDate = startFromDate
projectTrackingDetails[entity] = dict()
else:
lastTracked = projectTrackingDetails[entity].get('lastModificationDate', startFrom)
lastTrackedDate = parser.parse(lastTracked, ignoretz=True)
nextResponse, page = True, 1
pageSetFlag, totalPage = False, 0
entityConfig = payloadConfig[entity]
payload = entityConfig['payload'] % lastTracked
injectData['almType'] = entityConfig['entity']
if 'automation' in entityConfig:
injectData['automation'] = payloadConfig[entity]['automation']
while nextResponse:
response = dict()
try:
url = searchUrl.format(page, pageSize)
response = self.getResponse(url, 'POST', None, None, payload, None, apiHeaders)
if not pageSetFlag:
total = response.get('total', 0)
totalPage = int(math.ceil(float(total) / 100))
pageSetFlag = True
except Exception as err:
self.baseLogger.error(err)
responseData = response.get('items', None)
if responseData:
for response in responseData:
lastModified = response.get('last_modified_date', None)
lastModifiedDate = parser.parse(lastModified, ignoretz=True)
if lastModifiedDate > lastTrackedDate:
lastTrackedDate = lastModifiedDate
lastTracked = lastModified
responseId = response.get('id')
idList.append(responseId)
if injectData['almType'] == 'requirements':
injectData['jiraKey'] = response.get('name', '').split(' ')[0]
for entityProperty in response.get('properties', []):
if entityProperty.get('field_name', None):
injectData[str(entityProperty.get('field_name').lower()).replace(' ', '')] = entityProperty.get('field_value_name')
toolsData += self.parseResponse(responseTemplate, response, injectData)
if totalPage == page:
pageSetFlag, nextResponse = False, False
else:
pageSetFlag, nextResponse = False, False
page = page + 1
if isHistoryApi and entity == 'test-cases' and idList:
automationData = self.automationTypeHistory(historyUrl, projectId, entity, automationType, apiHeaders, idList, idChunkSize, pageSize)
if automationData:
toolsData += automationData
if toolsData:
self.publishToolsData(toolsData, metadata)
projectTrackingDetails[entity] = {'idList': idList, 'lastModificationDate': lastTracked}
self.updateTrackingJson(self.tracking)
except Exception as err:
self.baseLogger.error(err)
finally:
self.logout(token, baseUrl)
def scheduleExtensions(self):
extensions = self.config.get('dynamicTemplate', {}).get('extensions', None)
if extensions:
linkedArtifacts = extensions.get('linkedArtifacts', None)
if linkedArtifacts:
self.registerExtension('linkedArtifacts', self.retrieveLinkedArtifacts, linkedArtifacts.get('runSchedule'))
def login(self, baseUrl, userName, password, authKey):
headers = {'accept': 'application/json', 'content-type': 'application/x-www-form-urlencoded', 'authorization': 'Basic ' + authKey}
payload = 'grant_type=password&username=' + userName + '&password=' + password
response = self.getResponse(baseUrl + '/oauth/token', 'POST', None, None, payload, None, headers)
if "error" in response:
self.baseLogger.error(response)
return response.get("access_token", None)
@BaseAgent.timed
def automationTypeHistory(self, historyUrl, projectId, entityType, automationType, headers, idList, idChunkSize, pageSize):
try:
automationData = list()
payload = json.dumps({"object_type": entityType, "fields": ["*"], "object_query": "%s"})
objectQueryChunks = self.constructHistoryObjectQuery(idList, idChunkSize)
automationTimeDict = dict()
for idChunk in objectQueryChunks:
nextResponse = True
page = 1
payloadData = payload % idChunk
pageSetFlag, totalPage = False, 0
while nextResponse:
historyResponse = dict()
try:
url = historyUrl.format(page, pageSize)
historyResponse = self.getResponse(url, "POST", None, None, payloadData, None, headers)
if not pageSetFlag:
total = historyResponse.get('total', 0)
totalPage = int(math.ceil(float(total) / 100))
pageSetFlag = True
except Exception as err:
self.baseLogger.error(err)
finally:
if 'items' in historyResponse and historyResponse['items']:
changeHistoryList = historyResponse.get('items')
for changeHistory in changeHistoryList:
changesList = changeHistory.get('changes', [])
for changedField in changesList:
if changedField.get('field', None) == automationType['field'] and changedField.get('new_value', None) == automationType['newValue']:
resId = changeHistory.get('linked_object', {}).get('object_id', -1)
automationTime = parser.parse(changeHistory['created'], ignoretz=True)
if resId not in automationTimeDict:
automationTimeDict[resId] = ""
automation = automationTimeDict[resId]
if automation == "" or automation > automationTime:
automationTimeDict[resId] = automationTime
if totalPage == page:
pageSetFlag, nextResponse = False, False
else:
pageSetFlag, nextResponse = False, False
page = page + 1
for resId in automationTimeDict:
data = dict()
data["projectId"] = projectId
data["almType"] = entityType
data["id"] = resId
data["automationTime"] = automationTimeDict[resId].strftime(self.config.get('timeStampFormat'))
automationData.append(data)
return automationData
except Exception as err:
self.baseLogger.error(err)
@staticmethod
def _ConstructHistoryObjectQuery(entityIdList):
objectQuery = str()
entityIdListLen = len(entityIdList)
for index in range(0, entityIdListLen):
entityId = entityIdList[index]
objectQuery += '\'id\' = \'' + str(entityId) + '\''
if index != entityIdListLen - 1:
objectQuery += ' or '
return objectQuery
def constructHistoryObjectQuery(self, idList, idChunkSize):
if len(idList) > idChunkSize:
objectQueryList = list()
chunks = list()
for responseId in range(0, len(idList), idChunkSize):
chunks.append(idList[responseId: responseId + idChunkSize])
for chunk in chunks:
objectQueryList.append(self._ConstructHistoryObjectQuery(chunk))
return objectQueryList
else:
return [self._ConstructHistoryObjectQuery(idList), ]
@BaseAgent.timed
def retrieveLinkedArtifacts(self):
baseUrl = self.config.get('baseUrl', '')
userName = self.config.get('username', '')
password = self.config.get('password', '')
pageSize = self.config.get('responsePageSize', 100)
dynamicTemplate = self.config.get("dynamicTemplate", {})
linkedArtifacts = dynamicTemplate.get('extensions', {}).get('linkedArtifacts', None)
encodeKey = 'InSightsAlmAgent:'
authKey = base64.b64encode(encodeKey.encode('utf-8'))
token = self.login(baseUrl, userName, password, authKey)
bearerToken = 'bearer ' + token if token else None
apiHeaders = {'Content-Type': 'application/json', 'accept': 'application/json', 'Authorization': bearerToken}
trackingDetails = self.tracking
testRunTypes = dynamicTemplate.get('testRunsType', {})
try:
for project in trackingDetails:
projectTrackingDetails = trackingDetails.get(project)
almEntities = sorted(projectTrackingDetails.keys(), reverse=True)
testCaseIds = list()
for almEntity in almEntities:
data = list()
entity = almEntity
if almEntity in linkedArtifacts.get('almEntities', None):
entityTrackingDetails = projectTrackingDetails.get(almEntity)
idList = entityTrackingDetails.get('idList', None)
if idList is None:
continue
try:
if almEntity in testRunTypes:
entity = 'test-runs'
dictIsNotEmpty = True
start = 0
end = pageSize
while dictIsNotEmpty:
idListStr = str(idList[start:end])[1: -1]
linkedArtifactUrl = "{}/api/v3/projects/{}/linked-artifacts?type={}&ids={}".format(baseUrl, str(project), entity, idListStr)
entityTypeResponse = self.getResponse(linkedArtifactUrl, 'GET', None, None, None, None, apiHeaders)
for res in entityTypeResponse:
parentId = res.get('id', None)
injectData = dict()
injectData['id'] = parentId
injectData['projectId'] = int(project)
injectData['almType'] = 'linked-objects'
current_time = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
injectDat['lastModifiedDate']= current_time
injectData['almParentType'] = entity
if len(res.get('objects', [])) > 0:
injectData['isLinked'] = True
for link in res.get('objects', None):
linkType = (link.get('self', None).split('/')[-2]).replace('-', '')
linkId = link.get('id')
if linkType == 'testcases':
testCaseIds.append(linkId)
if linkType not in injectData:
injectData[linkType] = [linkId]
else:
injectData[linkType].append(linkId)
else:
injectData['isLinked'] = False
data.append(injectData)
start = end
end = end + pageSize
if len(idList[start:end]) == 0:
dictIsNotEmpty = False
except Exception as err:
self.baseLogger.error(err)
finally:
entityTrackingDetails.pop('idList')
if data:
metadata = self.config.get("dynamicTemplate", {}).get('extensions', {}).get('linkedArtifacts', {}).get("almEntityMetaData", None)
self.publishToolsData(data, metadata)
if almEntity in testRunTypes and testCaseIds:
idData = projectTrackingDetails.get('test-cases', {}).get('idList', []) + testCaseIds
idData = list(set(idData))
if 'test-cases' in projectTrackingDetails:
testCaseConfig = projectTrackingDetails['test-cases']
testCaseConfig['idList'] = idData
else:
projectTrackingDetails['test-cases'] = dict()
projectTrackingDetails['test-cases']['idList'] = idData
self.updateTrackingJson(self.tracking)
except Exception as ex1:
self.baseLogger.error(ex1)
finally:
self.logout(token, baseUrl)
def logout(self, token, baseUrl):
headerTokenRevoke = {"Authorization": "bearer "+str(token)+""}
self.getResponse(baseUrl+"/oauth/revoke", 'POST', None, None, None, None, headerTokenRevoke)
if __name__ == '__main__':
QtestAgent()
| CognizantOneDevOps/Insights | PlatformAgents/com/cognizant/devops/platformagents/agents/alm/qtest/QtestAgent.py | Python | apache-2.0 | 18,777 | 0.002929 |
'''
Nonlinear optimization by use of Affine DualAveraging
@author: Maximilian Balandat
@date: May 13, 2015
'''
import numpy as np
from .Domains import nBox
class NLoptProblem():
""" Basic class describing a Nonlinear Optimization problem. """
def __init__(self, domain, objective):
""" Constructor for the basic problem class. Here objective is a callable that
provides val and grad methods for computing value and gradient, respectively. """
if not isinstance(domain, nBox):
raise Exception('For now only nBoxes are supported!')
self.domain, self.objective = domain, objective
def run_minimization(self, etas, N, **kwargs):
""" Runs the minimization of the objective function based on interpreting
the value/gradient at the current iterate as an affine loss function
and applying dual averaging with the Exponential Potential. """
t, T, = 1, len(etas)
A = np.zeros((N, self.domain.n))
actions = [self.domain.sample_uniform(N)]
bounds = np.array(self.domain.bounds)
while t<T:
A += self.objective.grad(actions[-1])
actions.append(quicksample(bounds, A, etas[t]))
t += 1
return actions
def quicksample(bounds, A, eta):
""" Function returning actions sampled from the solution of the Dual Averaging
update on an Box with Affine losses, Exponential Potential. """
C1, C2 = np.exp(-eta*A*bounds[:,0]), np.exp(-eta*A*bounds[:,1])
Finv = lambda U: -np.log(C1 - (C1-C2)*U)/A/eta
return Finv(np.random.rand(*A.shape))
| Balandat/cont_no_regret | old_code/NLopt.py | Python | mit | 1,667 | 0.010198 |
# 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.
# ==============================================================================
"""Module implementing RNN Cells.
This module provides a number of basic commonly used RNN cells, such as LSTM
(Long Short Term Memory) or GRU (Gated Recurrent Unit), and a number of
operators that allow adding dropouts, projections, or embeddings for inputs.
Constructing multi-layer cells is supported by the class `MultiRNNCell`, or by
calling the `rnn` ops several times.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import hashlib
import numbers
from tensorflow.python.eager import context
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.framework import tensor_util
from tensorflow.python.keras import activations
from tensorflow.python.keras import initializers
from tensorflow.python.keras.engine import input_spec
from tensorflow.python.keras.utils import tf_utils
from tensorflow.python.layers import base as base_layer
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import clip_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.ops import variables as tf_variables
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training.checkpointable import base as checkpointable
from tensorflow.python.util import nest
from tensorflow.python.util.deprecation import deprecated
from tensorflow.python.util.tf_export import tf_export
_BIAS_VARIABLE_NAME = "bias"
_WEIGHTS_VARIABLE_NAME = "kernel"
# This can be used with self.assertRaisesRegexp for assert_like_rnncell.
ASSERT_LIKE_RNNCELL_ERROR_REGEXP = "is not an RNNCell"
def assert_like_rnncell(cell_name, cell):
"""Raises a TypeError if cell is not like an RNNCell.
NOTE: Do not rely on the error message (in particular in tests) which can be
subject to change to increase readability. Use
ASSERT_LIKE_RNNCELL_ERROR_REGEXP.
Args:
cell_name: A string to give a meaningful error referencing to the name
of the functionargument.
cell: The object which should behave like an RNNCell.
Raises:
TypeError: A human-friendly exception.
"""
conditions = [
hasattr(cell, "output_size"),
hasattr(cell, "state_size"),
hasattr(cell, "get_initial_state") or hasattr(cell, "zero_state"),
callable(cell),
]
errors = [
"'output_size' property is missing",
"'state_size' property is missing",
"either 'zero_state' or 'get_initial_state' method is required",
"is not callable"
]
if not all(conditions):
errors = [error for error, cond in zip(errors, conditions) if not cond]
raise TypeError("The argument {!r} ({}) is not an RNNCell: {}.".format(
cell_name, cell, ", ".join(errors)))
def _concat(prefix, suffix, static=False):
"""Concat that enables int, Tensor, or TensorShape values.
This function takes a size specification, which can be an integer, a
TensorShape, or a Tensor, and converts it into a concatenated Tensor
(if static = False) or a list of integers (if static = True).
Args:
prefix: The prefix; usually the batch size (and/or time step size).
(TensorShape, int, or Tensor.)
suffix: TensorShape, int, or Tensor.
static: If `True`, return a python list with possibly unknown dimensions.
Otherwise return a `Tensor`.
Returns:
shape: the concatenation of prefix and suffix.
Raises:
ValueError: if `suffix` is not a scalar or vector (or TensorShape).
ValueError: if prefix or suffix was `None` and asked for dynamic
Tensors out.
"""
if isinstance(prefix, ops.Tensor):
p = prefix
p_static = tensor_util.constant_value(prefix)
if p.shape.ndims == 0:
p = array_ops.expand_dims(p, 0)
elif p.shape.ndims != 1:
raise ValueError("prefix tensor must be either a scalar or vector, "
"but saw tensor: %s" % p)
else:
p = tensor_shape.as_shape(prefix)
p_static = p.as_list() if p.ndims is not None else None
p = (constant_op.constant(p.as_list(), dtype=dtypes.int32)
if p.is_fully_defined() else None)
if isinstance(suffix, ops.Tensor):
s = suffix
s_static = tensor_util.constant_value(suffix)
if s.shape.ndims == 0:
s = array_ops.expand_dims(s, 0)
elif s.shape.ndims != 1:
raise ValueError("suffix tensor must be either a scalar or vector, "
"but saw tensor: %s" % s)
else:
s = tensor_shape.as_shape(suffix)
s_static = s.as_list() if s.ndims is not None else None
s = (constant_op.constant(s.as_list(), dtype=dtypes.int32)
if s.is_fully_defined() else None)
if static:
shape = tensor_shape.as_shape(p_static).concatenate(s_static)
shape = shape.as_list() if shape.ndims is not None else None
else:
if p is None or s is None:
raise ValueError("Provided a prefix or suffix of None: %s and %s"
% (prefix, suffix))
shape = array_ops.concat((p, s), 0)
return shape
def _zero_state_tensors(state_size, batch_size, dtype):
"""Create tensors of zeros based on state_size, batch_size, and dtype."""
def get_state_shape(s):
"""Combine s with batch_size to get a proper tensor shape."""
c = _concat(batch_size, s)
size = array_ops.zeros(c, dtype=dtype)
if not context.executing_eagerly():
c_static = _concat(batch_size, s, static=True)
size.set_shape(c_static)
return size
return nest.map_structure(get_state_shape, state_size)
@tf_export("nn.rnn_cell.RNNCell")
class RNNCell(base_layer.Layer):
"""Abstract object representing an RNN cell.
Every `RNNCell` must have the properties below and implement `call` with
the signature `(output, next_state) = call(input, state)`. The optional
third input argument, `scope`, is allowed for backwards compatibility
purposes; but should be left off for new subclasses.
This definition of cell differs from the definition used in the literature.
In the literature, 'cell' refers to an object with a single scalar output.
This definition refers to a horizontal array of such units.
An RNN cell, in the most abstract setting, is anything that has
a state and performs some operation that takes a matrix of inputs.
This operation results in an output matrix with `self.output_size` columns.
If `self.state_size` is an integer, this operation also results in a new
state matrix with `self.state_size` columns. If `self.state_size` is a
(possibly nested tuple of) TensorShape object(s), then it should return a
matching structure of Tensors having shape `[batch_size].concatenate(s)`
for each `s` in `self.batch_size`.
"""
def __init__(self, trainable=True, name=None, dtype=None, **kwargs):
super(RNNCell, self).__init__(
trainable=trainable, name=name, dtype=dtype, **kwargs)
# Attribute that indicates whether the cell is a TF RNN cell, due the slight
# difference between TF and Keras RNN cell.
self._is_tf_rnn_cell = True
def __call__(self, inputs, state, scope=None):
"""Run this RNN cell on inputs, starting from the given state.
Args:
inputs: `2-D` tensor with shape `[batch_size, input_size]`.
state: if `self.state_size` is an integer, this should be a `2-D Tensor`
with shape `[batch_size, self.state_size]`. Otherwise, if
`self.state_size` is a tuple of integers, this should be a tuple
with shapes `[batch_size, s] for s in self.state_size`.
scope: VariableScope for the created subgraph; defaults to class name.
Returns:
A pair containing:
- Output: A `2-D` tensor with shape `[batch_size, self.output_size]`.
- New state: Either a single `2-D` tensor, or a tuple of tensors matching
the arity and shapes of `state`.
"""
if scope is not None:
with vs.variable_scope(scope,
custom_getter=self._rnn_get_variable) as scope:
return super(RNNCell, self).__call__(inputs, state, scope=scope)
else:
scope_attrname = "rnncell_scope"
scope = getattr(self, scope_attrname, None)
if scope is None:
scope = vs.variable_scope(vs.get_variable_scope(),
custom_getter=self._rnn_get_variable)
setattr(self, scope_attrname, scope)
with scope:
return super(RNNCell, self).__call__(inputs, state)
def _rnn_get_variable(self, getter, *args, **kwargs):
variable = getter(*args, **kwargs)
if context.executing_eagerly():
trainable = variable._trainable # pylint: disable=protected-access
else:
trainable = (
variable in tf_variables.trainable_variables() or
(isinstance(variable, tf_variables.PartitionedVariable) and
list(variable)[0] in tf_variables.trainable_variables()))
if trainable and variable not in self._trainable_weights:
self._trainable_weights.append(variable)
elif not trainable and variable not in self._non_trainable_weights:
self._non_trainable_weights.append(variable)
return variable
@property
def state_size(self):
"""size(s) of state(s) used by this cell.
It can be represented by an Integer, a TensorShape or a tuple of Integers
or TensorShapes.
"""
raise NotImplementedError("Abstract method")
@property
def output_size(self):
"""Integer or TensorShape: size of outputs produced by this cell."""
raise NotImplementedError("Abstract method")
def build(self, _):
# This tells the parent Layer object that it's OK to call
# self.add_variable() inside the call() method.
pass
def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
if inputs is not None:
# Validate the given batch_size and dtype against inputs if provided.
inputs = ops.convert_to_tensor(inputs, name="inputs")
if batch_size is not None:
if tensor_util.is_tensor(batch_size):
static_batch_size = tensor_util.constant_value(
batch_size, partial=True)
else:
static_batch_size = batch_size
if inputs.shape.dims[0].value != static_batch_size:
raise ValueError(
"batch size from input tensor is different from the "
"input param. Input tensor batch: {}, batch_size: {}".format(
inputs.shape.dims[0].value, batch_size))
if dtype is not None and inputs.dtype != dtype:
raise ValueError(
"dtype from input tensor is different from the "
"input param. Input tensor dtype: {}, dtype: {}".format(
inputs.dtype, dtype))
batch_size = inputs.shape.dims[0].value or array_ops.shape(inputs)[0]
dtype = inputs.dtype
if None in [batch_size, dtype]:
raise ValueError(
"batch_size and dtype cannot be None while constructing initial "
"state: batch_size={}, dtype={}".format(batch_size, dtype))
return self.zero_state(batch_size, dtype)
def zero_state(self, batch_size, dtype):
"""Return zero-filled state tensor(s).
Args:
batch_size: int, float, or unit Tensor representing the batch size.
dtype: the data type to use for the state.
Returns:
If `state_size` is an int or TensorShape, then the return value is a
`N-D` tensor of shape `[batch_size, state_size]` filled with zeros.
If `state_size` is a nested list or tuple, then the return value is
a nested list or tuple (of the same structure) of `2-D` tensors with
the shapes `[batch_size, s]` for each s in `state_size`.
"""
# Try to use the last cached zero_state. This is done to avoid recreating
# zeros, especially when eager execution is enabled.
state_size = self.state_size
is_eager = context.executing_eagerly()
if is_eager and hasattr(self, "_last_zero_state"):
(last_state_size, last_batch_size, last_dtype,
last_output) = getattr(self, "_last_zero_state")
if (last_batch_size == batch_size and
last_dtype == dtype and
last_state_size == state_size):
return last_output
with ops.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]):
output = _zero_state_tensors(state_size, batch_size, dtype)
if is_eager:
self._last_zero_state = (state_size, batch_size, dtype, output)
return output
class LayerRNNCell(RNNCell):
"""Subclass of RNNCells that act like proper `tf.Layer` objects.
For backwards compatibility purposes, most `RNNCell` instances allow their
`call` methods to instantiate variables via `tf.get_variable`. The underlying
variable scope thus keeps track of any variables, and returning cached
versions. This is atypical of `tf.layer` objects, which separate this
part of layer building into a `build` method that is only called once.
Here we provide a subclass for `RNNCell` objects that act exactly as
`Layer` objects do. They must provide a `build` method and their
`call` methods do not access Variables `tf.get_variable`.
"""
def __call__(self, inputs, state, scope=None, *args, **kwargs):
"""Run this RNN cell on inputs, starting from the given state.
Args:
inputs: `2-D` tensor with shape `[batch_size, input_size]`.
state: if `self.state_size` is an integer, this should be a `2-D Tensor`
with shape `[batch_size, self.state_size]`. Otherwise, if
`self.state_size` is a tuple of integers, this should be a tuple
with shapes `[batch_size, s] for s in self.state_size`.
scope: optional cell scope.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Returns:
A pair containing:
- Output: A `2-D` tensor with shape `[batch_size, self.output_size]`.
- New state: Either a single `2-D` tensor, or a tuple of tensors matching
the arity and shapes of `state`.
"""
# Bypass RNNCell's variable capturing semantics for LayerRNNCell.
# Instead, it is up to subclasses to provide a proper build
# method. See the class docstring for more details.
return base_layer.Layer.__call__(self, inputs, state, scope=scope,
*args, **kwargs)
@tf_export(v1=["nn.rnn_cell.BasicRNNCell"])
class BasicRNNCell(LayerRNNCell):
"""The most basic RNN cell.
Note that this cell is not optimized for performance. Please use
`tf.contrib.cudnn_rnn.CudnnRNNTanh` for better performance on GPU.
Args:
num_units: int, The number of units in the RNN cell.
activation: Nonlinearity to use. Default: `tanh`. It could also be string
that is within Keras activation function names.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
name: String, the name of the layer. Layers with the same name will
share weights, but to avoid mistakes we require reuse=True in such
cases.
dtype: Default dtype of the layer (default of `None` means use the type
of the first input). Required when `build` is called before `call`.
**kwargs: Dict, keyword named properties for common layer attributes, like
`trainable` etc when constructing the cell from configs of get_config().
"""
@deprecated(None, "This class is equivalent as tf.keras.layers.SimpleRNNCell,"
" and will be replaced by that in Tensorflow 2.0.")
def __init__(self,
num_units,
activation=None,
reuse=None,
name=None,
dtype=None,
**kwargs):
super(BasicRNNCell, self).__init__(
_reuse=reuse, name=name, dtype=dtype, **kwargs)
if context.executing_eagerly() and context.num_gpus() > 0:
logging.warn("%s: Note that this cell is not optimized for performance. "
"Please use tf.contrib.cudnn_rnn.CudnnRNNTanh for better "
"performance on GPU.", self)
# Inputs must be 2-dimensional.
self.input_spec = input_spec.InputSpec(ndim=2)
self._num_units = num_units
if activation:
self._activation = activations.get(activation)
else:
self._activation = math_ops.tanh
@property
def state_size(self):
return self._num_units
@property
def output_size(self):
return self._num_units
@tf_utils.shape_type_conversion
def build(self, inputs_shape):
if inputs_shape[-1] is None:
raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s"
% str(inputs_shape))
input_depth = inputs_shape[-1]
self._kernel = self.add_variable(
_WEIGHTS_VARIABLE_NAME,
shape=[input_depth + self._num_units, self._num_units])
self._bias = self.add_variable(
_BIAS_VARIABLE_NAME,
shape=[self._num_units],
initializer=init_ops.zeros_initializer(dtype=self.dtype))
self.built = True
def call(self, inputs, state):
"""Most basic RNN: output = new_state = act(W * input + U * state + B)."""
gate_inputs = math_ops.matmul(
array_ops.concat([inputs, state], 1), self._kernel)
gate_inputs = nn_ops.bias_add(gate_inputs, self._bias)
output = self._activation(gate_inputs)
return output, output
def get_config(self):
config = {
"num_units": self._num_units,
"activation": activations.serialize(self._activation),
"reuse": self._reuse,
}
base_config = super(BasicRNNCell, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
@tf_export(v1=["nn.rnn_cell.GRUCell"])
class GRUCell(LayerRNNCell):
"""Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078).
Note that this cell is not optimized for performance. Please use
`tf.contrib.cudnn_rnn.CudnnGRU` for better performance on GPU, or
`tf.contrib.rnn.GRUBlockCellV2` for better performance on CPU.
Args:
num_units: int, The number of units in the GRU cell.
activation: Nonlinearity to use. Default: `tanh`.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
kernel_initializer: (optional) The initializer to use for the weight and
projection matrices.
bias_initializer: (optional) The initializer to use for the bias.
name: String, the name of the layer. Layers with the same name will
share weights, but to avoid mistakes we require reuse=True in such
cases.
dtype: Default dtype of the layer (default of `None` means use the type
of the first input). Required when `build` is called before `call`.
**kwargs: Dict, keyword named properties for common layer attributes, like
`trainable` etc when constructing the cell from configs of get_config().
"""
@deprecated(None, "This class is equivalent as tf.keras.layers.GRUCell,"
" and will be replaced by that in Tensorflow 2.0.")
def __init__(self,
num_units,
activation=None,
reuse=None,
kernel_initializer=None,
bias_initializer=None,
name=None,
dtype=None,
**kwargs):
super(GRUCell, self).__init__(
_reuse=reuse, name=name, dtype=dtype, **kwargs)
if context.executing_eagerly() and context.num_gpus() > 0:
logging.warn("%s: Note that this cell is not optimized for performance. "
"Please use tf.contrib.cudnn_rnn.CudnnGRU for better "
"performance on GPU.", self)
# Inputs must be 2-dimensional.
self.input_spec = input_spec.InputSpec(ndim=2)
self._num_units = num_units
if activation:
self._activation = activations.get(activation)
else:
self._activation = math_ops.tanh
self._kernel_initializer = initializers.get(kernel_initializer)
self._bias_initializer = initializers.get(bias_initializer)
@property
def state_size(self):
return self._num_units
@property
def output_size(self):
return self._num_units
@tf_utils.shape_type_conversion
def build(self, inputs_shape):
if inputs_shape[-1] is None:
raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s"
% str(inputs_shape))
input_depth = inputs_shape[-1]
self._gate_kernel = self.add_variable(
"gates/%s" % _WEIGHTS_VARIABLE_NAME,
shape=[input_depth + self._num_units, 2 * self._num_units],
initializer=self._kernel_initializer)
self._gate_bias = self.add_variable(
"gates/%s" % _BIAS_VARIABLE_NAME,
shape=[2 * self._num_units],
initializer=(
self._bias_initializer
if self._bias_initializer is not None
else init_ops.constant_initializer(1.0, dtype=self.dtype)))
self._candidate_kernel = self.add_variable(
"candidate/%s" % _WEIGHTS_VARIABLE_NAME,
shape=[input_depth + self._num_units, self._num_units],
initializer=self._kernel_initializer)
self._candidate_bias = self.add_variable(
"candidate/%s" % _BIAS_VARIABLE_NAME,
shape=[self._num_units],
initializer=(
self._bias_initializer
if self._bias_initializer is not None
else init_ops.zeros_initializer(dtype=self.dtype)))
self.built = True
def call(self, inputs, state):
"""Gated recurrent unit (GRU) with nunits cells."""
gate_inputs = math_ops.matmul(
array_ops.concat([inputs, state], 1), self._gate_kernel)
gate_inputs = nn_ops.bias_add(gate_inputs, self._gate_bias)
value = math_ops.sigmoid(gate_inputs)
r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1)
r_state = r * state
candidate = math_ops.matmul(
array_ops.concat([inputs, r_state], 1), self._candidate_kernel)
candidate = nn_ops.bias_add(candidate, self._candidate_bias)
c = self._activation(candidate)
new_h = u * state + (1 - u) * c
return new_h, new_h
def get_config(self):
config = {
"num_units": self._num_units,
"kernel_initializer": initializers.serialize(self._kernel_initializer),
"bias_initializer": initializers.serialize(self._bias_initializer),
"activation": activations.serialize(self._activation),
"reuse": self._reuse,
}
base_config = super(GRUCell, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
_LSTMStateTuple = collections.namedtuple("LSTMStateTuple", ("c", "h"))
@tf_export("nn.rnn_cell.LSTMStateTuple")
class LSTMStateTuple(_LSTMStateTuple):
"""Tuple used by LSTM Cells for `state_size`, `zero_state`, and output state.
Stores two elements: `(c, h)`, in that order. Where `c` is the hidden state
and `h` is the output.
Only used when `state_is_tuple=True`.
"""
__slots__ = ()
@property
def dtype(self):
(c, h) = self
if c.dtype != h.dtype:
raise TypeError("Inconsistent internal state: %s vs %s" %
(str(c.dtype), str(h.dtype)))
return c.dtype
@tf_export(v1=["nn.rnn_cell.BasicLSTMCell"])
class BasicLSTMCell(LayerRNNCell):
"""DEPRECATED: Please use `tf.nn.rnn_cell.LSTMCell` instead.
Basic LSTM recurrent network cell.
The implementation is based on: http://arxiv.org/abs/1409.2329.
We add forget_bias (default: 1) to the biases of the forget gate in order to
reduce the scale of forgetting in the beginning of the training.
It does not allow cell clipping, a projection layer, and does not
use peep-hole connections: it is the basic baseline.
For advanced models, please use the full `tf.nn.rnn_cell.LSTMCell`
that follows.
Note that this cell is not optimized for performance. Please use
`tf.contrib.cudnn_rnn.CudnnLSTM` for better performance on GPU, or
`tf.contrib.rnn.LSTMBlockCell` and `tf.contrib.rnn.LSTMBlockFusedCell` for
better performance on CPU.
"""
@deprecated(None, "This class is equivalent as tf.keras.layers.LSTMCell,"
" and will be replaced by that in Tensorflow 2.0.")
def __init__(self,
num_units,
forget_bias=1.0,
state_is_tuple=True,
activation=None,
reuse=None,
name=None,
dtype=None,
**kwargs):
"""Initialize the basic LSTM cell.
Args:
num_units: int, The number of units in the LSTM cell.
forget_bias: float, The bias added to forget gates (see above).
Must set to `0.0` manually when restoring from CudnnLSTM-trained
checkpoints.
state_is_tuple: If True, accepted and returned states are 2-tuples of
the `c_state` and `m_state`. If False, they are concatenated
along the column axis. The latter behavior will soon be deprecated.
activation: Activation function of the inner states. Default: `tanh`. It
could also be string that is within Keras activation function names.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
name: String, the name of the layer. Layers with the same name will
share weights, but to avoid mistakes we require reuse=True in such
cases.
dtype: Default dtype of the layer (default of `None` means use the type
of the first input). Required when `build` is called before `call`.
**kwargs: Dict, keyword named properties for common layer attributes, like
`trainable` etc when constructing the cell from configs of get_config().
When restoring from CudnnLSTM-trained checkpoints, must use
`CudnnCompatibleLSTMCell` instead.
"""
super(BasicLSTMCell, self).__init__(
_reuse=reuse, name=name, dtype=dtype, **kwargs)
if not state_is_tuple:
logging.warn("%s: Using a concatenated state is slower and will soon be "
"deprecated. Use state_is_tuple=True.", self)
if context.executing_eagerly() and context.num_gpus() > 0:
logging.warn("%s: Note that this cell is not optimized for performance. "
"Please use tf.contrib.cudnn_rnn.CudnnLSTM for better "
"performance on GPU.", self)
# Inputs must be 2-dimensional.
self.input_spec = input_spec.InputSpec(ndim=2)
self._num_units = num_units
self._forget_bias = forget_bias
self._state_is_tuple = state_is_tuple
if activation:
self._activation = activations.get(activation)
else:
self._activation = math_ops.tanh
@property
def state_size(self):
return (LSTMStateTuple(self._num_units, self._num_units)
if self._state_is_tuple else 2 * self._num_units)
@property
def output_size(self):
return self._num_units
@tf_utils.shape_type_conversion
def build(self, inputs_shape):
if inputs_shape[-1] is None:
raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s"
% str(inputs_shape))
input_depth = inputs_shape[-1]
h_depth = self._num_units
self._kernel = self.add_variable(
_WEIGHTS_VARIABLE_NAME,
shape=[input_depth + h_depth, 4 * self._num_units])
self._bias = self.add_variable(
_BIAS_VARIABLE_NAME,
shape=[4 * self._num_units],
initializer=init_ops.zeros_initializer(dtype=self.dtype))
self.built = True
def call(self, inputs, state):
"""Long short-term memory cell (LSTM).
Args:
inputs: `2-D` tensor with shape `[batch_size, input_size]`.
state: An `LSTMStateTuple` of state tensors, each shaped
`[batch_size, num_units]`, if `state_is_tuple` has been set to
`True`. Otherwise, a `Tensor` shaped
`[batch_size, 2 * num_units]`.
Returns:
A pair containing the new hidden state, and the new state (either a
`LSTMStateTuple` or a concatenated state, depending on
`state_is_tuple`).
"""
sigmoid = math_ops.sigmoid
one = constant_op.constant(1, dtype=dtypes.int32)
# Parameters of gates are concatenated into one multiply for efficiency.
if self._state_is_tuple:
c, h = state
else:
c, h = array_ops.split(value=state, num_or_size_splits=2, axis=one)
gate_inputs = math_ops.matmul(
array_ops.concat([inputs, h], 1), self._kernel)
gate_inputs = nn_ops.bias_add(gate_inputs, self._bias)
# i = input_gate, j = new_input, f = forget_gate, o = output_gate
i, j, f, o = array_ops.split(
value=gate_inputs, num_or_size_splits=4, axis=one)
forget_bias_tensor = constant_op.constant(self._forget_bias, dtype=f.dtype)
# Note that using `add` and `multiply` instead of `+` and `*` gives a
# performance improvement. So using those at the cost of readability.
add = math_ops.add
multiply = math_ops.multiply
new_c = add(multiply(c, sigmoid(add(f, forget_bias_tensor))),
multiply(sigmoid(i), self._activation(j)))
new_h = multiply(self._activation(new_c), sigmoid(o))
if self._state_is_tuple:
new_state = LSTMStateTuple(new_c, new_h)
else:
new_state = array_ops.concat([new_c, new_h], 1)
return new_h, new_state
def get_config(self):
config = {
"num_units": self._num_units,
"forget_bias": self._forget_bias,
"state_is_tuple": self._state_is_tuple,
"activation": activations.serialize(self._activation),
"reuse": self._reuse,
}
base_config = super(BasicLSTMCell, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
@tf_export(v1=["nn.rnn_cell.LSTMCell"])
class LSTMCell(LayerRNNCell):
"""Long short-term memory unit (LSTM) recurrent network cell.
The default non-peephole implementation is based on:
https://pdfs.semanticscholar.org/1154/0131eae85b2e11d53df7f1360eeb6476e7f4.pdf
Felix Gers, Jurgen Schmidhuber, and Fred Cummins.
"Learning to forget: Continual prediction with LSTM." IET, 850-855, 1999.
The peephole implementation is based on:
https://research.google.com/pubs/archive/43905.pdf
Hasim Sak, Andrew Senior, and Francoise Beaufays.
"Long short-term memory recurrent neural network architectures for
large scale acoustic modeling." INTERSPEECH, 2014.
The class uses optional peep-hole connections, optional cell clipping, and
an optional projection layer.
Note that this cell is not optimized for performance. Please use
`tf.contrib.cudnn_rnn.CudnnLSTM` for better performance on GPU, or
`tf.contrib.rnn.LSTMBlockCell` and `tf.contrib.rnn.LSTMBlockFusedCell` for
better performance on CPU.
"""
@deprecated(None, "This class is equivalent as tf.keras.layers.LSTMCell,"
" and will be replaced by that in Tensorflow 2.0.")
def __init__(self, num_units,
use_peepholes=False, cell_clip=None,
initializer=None, num_proj=None, proj_clip=None,
num_unit_shards=None, num_proj_shards=None,
forget_bias=1.0, state_is_tuple=True,
activation=None, reuse=None, name=None, dtype=None, **kwargs):
"""Initialize the parameters for an LSTM cell.
Args:
num_units: int, The number of units in the LSTM cell.
use_peepholes: bool, set True to enable diagonal/peephole connections.
cell_clip: (optional) A float value, if provided the cell state is clipped
by this value prior to the cell output activation.
initializer: (optional) The initializer to use for the weight and
projection matrices.
num_proj: (optional) int, The output dimensionality for the projection
matrices. If None, no projection is performed.
proj_clip: (optional) A float value. If `num_proj > 0` and `proj_clip` is
provided, then the projected values are clipped elementwise to within
`[-proj_clip, proj_clip]`.
num_unit_shards: Deprecated, will be removed by Jan. 2017.
Use a variable_scope partitioner instead.
num_proj_shards: Deprecated, will be removed by Jan. 2017.
Use a variable_scope partitioner instead.
forget_bias: Biases of the forget gate are initialized by default to 1
in order to reduce the scale of forgetting at the beginning of
the training. Must set it manually to `0.0` when restoring from
CudnnLSTM trained checkpoints.
state_is_tuple: If True, accepted and returned states are 2-tuples of
the `c_state` and `m_state`. If False, they are concatenated
along the column axis. This latter behavior will soon be deprecated.
activation: Activation function of the inner states. Default: `tanh`. It
could also be string that is within Keras activation function names.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
name: String, the name of the layer. Layers with the same name will
share weights, but to avoid mistakes we require reuse=True in such
cases.
dtype: Default dtype of the layer (default of `None` means use the type
of the first input). Required when `build` is called before `call`.
**kwargs: Dict, keyword named properties for common layer attributes, like
`trainable` etc when constructing the cell from configs of get_config().
When restoring from CudnnLSTM-trained checkpoints, use
`CudnnCompatibleLSTMCell` instead.
"""
super(LSTMCell, self).__init__(
_reuse=reuse, name=name, dtype=dtype, **kwargs)
if not state_is_tuple:
logging.warn("%s: Using a concatenated state is slower and will soon be "
"deprecated. Use state_is_tuple=True.", self)
if num_unit_shards is not None or num_proj_shards is not None:
logging.warn(
"%s: The num_unit_shards and proj_unit_shards parameters are "
"deprecated and will be removed in Jan 2017. "
"Use a variable scope with a partitioner instead.", self)
if context.executing_eagerly() and context.num_gpus() > 0:
logging.warn("%s: Note that this cell is not optimized for performance. "
"Please use tf.contrib.cudnn_rnn.CudnnLSTM for better "
"performance on GPU.", self)
# Inputs must be 2-dimensional.
self.input_spec = input_spec.InputSpec(ndim=2)
self._num_units = num_units
self._use_peepholes = use_peepholes
self._cell_clip = cell_clip
self._initializer = initializers.get(initializer)
self._num_proj = num_proj
self._proj_clip = proj_clip
self._num_unit_shards = num_unit_shards
self._num_proj_shards = num_proj_shards
self._forget_bias = forget_bias
self._state_is_tuple = state_is_tuple
if activation:
self._activation = activations.get(activation)
else:
self._activation = math_ops.tanh
if num_proj:
self._state_size = (
LSTMStateTuple(num_units, num_proj)
if state_is_tuple else num_units + num_proj)
self._output_size = num_proj
else:
self._state_size = (
LSTMStateTuple(num_units, num_units)
if state_is_tuple else 2 * num_units)
self._output_size = num_units
@property
def state_size(self):
return self._state_size
@property
def output_size(self):
return self._output_size
@tf_utils.shape_type_conversion
def build(self, inputs_shape):
if inputs_shape[-1] is None:
raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s"
% str(inputs_shape))
input_depth = inputs_shape[-1]
h_depth = self._num_units if self._num_proj is None else self._num_proj
maybe_partitioner = (
partitioned_variables.fixed_size_partitioner(self._num_unit_shards)
if self._num_unit_shards is not None
else None)
self._kernel = self.add_variable(
_WEIGHTS_VARIABLE_NAME,
shape=[input_depth + h_depth, 4 * self._num_units],
initializer=self._initializer,
partitioner=maybe_partitioner)
if self.dtype is None:
initializer = init_ops.zeros_initializer
else:
initializer = init_ops.zeros_initializer(dtype=self.dtype)
self._bias = self.add_variable(
_BIAS_VARIABLE_NAME,
shape=[4 * self._num_units],
initializer=initializer)
if self._use_peepholes:
self._w_f_diag = self.add_variable("w_f_diag", shape=[self._num_units],
initializer=self._initializer)
self._w_i_diag = self.add_variable("w_i_diag", shape=[self._num_units],
initializer=self._initializer)
self._w_o_diag = self.add_variable("w_o_diag", shape=[self._num_units],
initializer=self._initializer)
if self._num_proj is not None:
maybe_proj_partitioner = (
partitioned_variables.fixed_size_partitioner(self._num_proj_shards)
if self._num_proj_shards is not None
else None)
self._proj_kernel = self.add_variable(
"projection/%s" % _WEIGHTS_VARIABLE_NAME,
shape=[self._num_units, self._num_proj],
initializer=self._initializer,
partitioner=maybe_proj_partitioner)
self.built = True
def call(self, inputs, state):
"""Run one step of LSTM.
Args:
inputs: input Tensor, must be 2-D, `[batch, input_size]`.
state: if `state_is_tuple` is False, this must be a state Tensor,
`2-D, [batch, state_size]`. If `state_is_tuple` is True, this must be a
tuple of state Tensors, both `2-D`, with column sizes `c_state` and
`m_state`.
Returns:
A tuple containing:
- A `2-D, [batch, output_dim]`, Tensor representing the output of the
LSTM after reading `inputs` when previous state was `state`.
Here output_dim is:
num_proj if num_proj was set,
num_units otherwise.
- Tensor(s) representing the new state of LSTM after reading `inputs` when
the previous state was `state`. Same type and shape(s) as `state`.
Raises:
ValueError: If input size cannot be inferred from inputs via
static shape inference.
"""
num_proj = self._num_units if self._num_proj is None else self._num_proj
sigmoid = math_ops.sigmoid
if self._state_is_tuple:
(c_prev, m_prev) = state
else:
c_prev = array_ops.slice(state, [0, 0], [-1, self._num_units])
m_prev = array_ops.slice(state, [0, self._num_units], [-1, num_proj])
input_size = inputs.get_shape().with_rank(2).dims[1].value
if input_size is None:
raise ValueError("Could not infer input size from inputs.get_shape()[-1]")
# i = input_gate, j = new_input, f = forget_gate, o = output_gate
lstm_matrix = math_ops.matmul(
array_ops.concat([inputs, m_prev], 1), self._kernel)
lstm_matrix = nn_ops.bias_add(lstm_matrix, self._bias)
i, j, f, o = array_ops.split(
value=lstm_matrix, num_or_size_splits=4, axis=1)
# Diagonal connections
if self._use_peepholes:
c = (sigmoid(f + self._forget_bias + self._w_f_diag * c_prev) * c_prev +
sigmoid(i + self._w_i_diag * c_prev) * self._activation(j))
else:
c = (sigmoid(f + self._forget_bias) * c_prev + sigmoid(i) *
self._activation(j))
if self._cell_clip is not None:
# pylint: disable=invalid-unary-operand-type
c = clip_ops.clip_by_value(c, -self._cell_clip, self._cell_clip)
# pylint: enable=invalid-unary-operand-type
if self._use_peepholes:
m = sigmoid(o + self._w_o_diag * c) * self._activation(c)
else:
m = sigmoid(o) * self._activation(c)
if self._num_proj is not None:
m = math_ops.matmul(m, self._proj_kernel)
if self._proj_clip is not None:
# pylint: disable=invalid-unary-operand-type
m = clip_ops.clip_by_value(m, -self._proj_clip, self._proj_clip)
# pylint: enable=invalid-unary-operand-type
new_state = (LSTMStateTuple(c, m) if self._state_is_tuple else
array_ops.concat([c, m], 1))
return m, new_state
def get_config(self):
config = {
"num_units": self._num_units,
"use_peepholes": self._use_peepholes,
"cell_clip": self._cell_clip,
"initializer": initializers.serialize(self._initializer),
"num_proj": self._num_proj,
"proj_clip": self._proj_clip,
"num_unit_shards": self._num_unit_shards,
"num_proj_shards": self._num_proj_shards,
"forget_bias": self._forget_bias,
"state_is_tuple": self._state_is_tuple,
"activation": activations.serialize(self._activation),
"reuse": self._reuse,
}
base_config = super(LSTMCell, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
def _enumerated_map_structure_up_to(shallow_structure, map_fn, *args, **kwargs):
ix = [0]
def enumerated_fn(*inner_args, **inner_kwargs):
r = map_fn(ix[0], *inner_args, **inner_kwargs)
ix[0] += 1
return r
return nest.map_structure_up_to(shallow_structure,
enumerated_fn, *args, **kwargs)
def _default_dropout_state_filter_visitor(substate):
if isinstance(substate, LSTMStateTuple):
# Do not perform dropout on the memory state.
return LSTMStateTuple(c=False, h=True)
elif isinstance(substate, tensor_array_ops.TensorArray):
return False
return True
@tf_export("nn.rnn_cell.DropoutWrapper")
class DropoutWrapper(RNNCell):
"""Operator adding dropout to inputs and outputs of the given cell."""
def __init__(self, cell, input_keep_prob=1.0, output_keep_prob=1.0,
state_keep_prob=1.0, variational_recurrent=False,
input_size=None, dtype=None, seed=None,
dropout_state_filter_visitor=None):
"""Create a cell with added input, state, and/or output dropout.
If `variational_recurrent` is set to `True` (**NOT** the default behavior),
then the same dropout mask is applied at every step, as described in:
Y. Gal, Z Ghahramani. "A Theoretically Grounded Application of Dropout in
Recurrent Neural Networks". https://arxiv.org/abs/1512.05287
Otherwise a different dropout mask is applied at every time step.
Note, by default (unless a custom `dropout_state_filter` is provided),
the memory state (`c` component of any `LSTMStateTuple`) passing through
a `DropoutWrapper` is never modified. This behavior is described in the
above article.
Args:
cell: an RNNCell, a projection to output_size is added to it.
input_keep_prob: unit Tensor or float between 0 and 1, input keep
probability; if it is constant and 1, no input dropout will be added.
output_keep_prob: unit Tensor or float between 0 and 1, output keep
probability; if it is constant and 1, no output dropout will be added.
state_keep_prob: unit Tensor or float between 0 and 1, output keep
probability; if it is constant and 1, no output dropout will be added.
State dropout is performed on the outgoing states of the cell.
**Note** the state components to which dropout is applied when
`state_keep_prob` is in `(0, 1)` are also determined by
the argument `dropout_state_filter_visitor` (e.g. by default dropout
is never applied to the `c` component of an `LSTMStateTuple`).
variational_recurrent: Python bool. If `True`, then the same
dropout pattern is applied across all time steps per run call.
If this parameter is set, `input_size` **must** be provided.
input_size: (optional) (possibly nested tuple of) `TensorShape` objects
containing the depth(s) of the input tensors expected to be passed in to
the `DropoutWrapper`. Required and used **iff**
`variational_recurrent = True` and `input_keep_prob < 1`.
dtype: (optional) The `dtype` of the input, state, and output tensors.
Required and used **iff** `variational_recurrent = True`.
seed: (optional) integer, the randomness seed.
dropout_state_filter_visitor: (optional), default: (see below). Function
that takes any hierarchical level of the state and returns
a scalar or depth=1 structure of Python booleans describing
which terms in the state should be dropped out. In addition, if the
function returns `True`, dropout is applied across this sublevel. If
the function returns `False`, dropout is not applied across this entire
sublevel.
Default behavior: perform dropout on all terms except the memory (`c`)
state of `LSTMCellState` objects, and don't try to apply dropout to
`TensorArray` objects:
```
def dropout_state_filter_visitor(s):
if isinstance(s, LSTMCellState):
# Never perform dropout on the c state.
return LSTMCellState(c=False, h=True)
elif isinstance(s, TensorArray):
return False
return True
```
Raises:
TypeError: if `cell` is not an `RNNCell`, or `keep_state_fn` is provided
but not `callable`.
ValueError: if any of the keep_probs are not between 0 and 1.
"""
super(DropoutWrapper, self).__init__()
assert_like_rnncell("cell", cell)
if (dropout_state_filter_visitor is not None
and not callable(dropout_state_filter_visitor)):
raise TypeError("dropout_state_filter_visitor must be callable")
self._dropout_state_filter = (
dropout_state_filter_visitor or _default_dropout_state_filter_visitor)
with ops.name_scope("DropoutWrapperInit"):
def tensor_and_const_value(v):
tensor_value = ops.convert_to_tensor(v)
const_value = tensor_util.constant_value(tensor_value)
return (tensor_value, const_value)
for prob, attr in [(input_keep_prob, "input_keep_prob"),
(state_keep_prob, "state_keep_prob"),
(output_keep_prob, "output_keep_prob")]:
tensor_prob, const_prob = tensor_and_const_value(prob)
if const_prob is not None:
if const_prob < 0 or const_prob > 1:
raise ValueError("Parameter %s must be between 0 and 1: %d"
% (attr, const_prob))
setattr(self, "_%s" % attr, float(const_prob))
else:
setattr(self, "_%s" % attr, tensor_prob)
# Set cell, variational_recurrent, seed before running the code below
self._cell = cell
if isinstance(cell, checkpointable.CheckpointableBase):
self._track_checkpointable(self._cell, name="cell")
self._variational_recurrent = variational_recurrent
self._seed = seed
self._recurrent_input_noise = None
self._recurrent_state_noise = None
self._recurrent_output_noise = None
if variational_recurrent:
if dtype is None:
raise ValueError(
"When variational_recurrent=True, dtype must be provided")
def convert_to_batch_shape(s):
# Prepend a 1 for the batch dimension; for recurrent
# variational dropout we use the same dropout mask for all
# batch elements.
return array_ops.concat(
([1], tensor_shape.TensorShape(s).as_list()), 0)
def batch_noise(s, inner_seed):
shape = convert_to_batch_shape(s)
return random_ops.random_uniform(shape, seed=inner_seed, dtype=dtype)
if (not isinstance(self._input_keep_prob, numbers.Real) or
self._input_keep_prob < 1.0):
if input_size is None:
raise ValueError(
"When variational_recurrent=True and input_keep_prob < 1.0 or "
"is unknown, input_size must be provided")
self._recurrent_input_noise = _enumerated_map_structure_up_to(
input_size,
lambda i, s: batch_noise(s, inner_seed=self._gen_seed("input", i)),
input_size)
self._recurrent_state_noise = _enumerated_map_structure_up_to(
cell.state_size,
lambda i, s: batch_noise(s, inner_seed=self._gen_seed("state", i)),
cell.state_size)
self._recurrent_output_noise = _enumerated_map_structure_up_to(
cell.output_size,
lambda i, s: batch_noise(s, inner_seed=self._gen_seed("output", i)),
cell.output_size)
def _gen_seed(self, salt_prefix, index):
if self._seed is None:
return None
salt = "%s_%d" % (salt_prefix, index)
string = (str(self._seed) + salt).encode("utf-8")
return int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF
@property
def wrapped_cell(self):
return self._cell
@property
def state_size(self):
return self._cell.state_size
@property
def output_size(self):
return self._cell.output_size
def zero_state(self, batch_size, dtype):
with ops.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]):
return self._cell.zero_state(batch_size, dtype)
def _variational_recurrent_dropout_value(
self, index, value, noise, keep_prob):
"""Performs dropout given the pre-calculated noise tensor."""
# uniform [keep_prob, 1.0 + keep_prob)
random_tensor = keep_prob + noise
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
binary_tensor = math_ops.floor(random_tensor)
ret = math_ops.div(value, keep_prob) * binary_tensor
ret.set_shape(value.get_shape())
return ret
def _dropout(self, values, salt_prefix, recurrent_noise, keep_prob,
shallow_filtered_substructure=None):
"""Decides whether to perform standard dropout or recurrent dropout."""
if shallow_filtered_substructure is None:
# Put something so we traverse the entire structure; inside the
# dropout function we check to see if leafs of this are bool or not.
shallow_filtered_substructure = values
if not self._variational_recurrent:
def dropout(i, do_dropout, v):
if not isinstance(do_dropout, bool) or do_dropout:
return nn_ops.dropout(
v, keep_prob=keep_prob, seed=self._gen_seed(salt_prefix, i))
else:
return v
return _enumerated_map_structure_up_to(
shallow_filtered_substructure, dropout,
*[shallow_filtered_substructure, values])
else:
def dropout(i, do_dropout, v, n):
if not isinstance(do_dropout, bool) or do_dropout:
return self._variational_recurrent_dropout_value(i, v, n, keep_prob)
else:
return v
return _enumerated_map_structure_up_to(
shallow_filtered_substructure, dropout,
*[shallow_filtered_substructure, values, recurrent_noise])
def __call__(self, inputs, state, scope=None):
"""Run the cell with the declared dropouts."""
def _should_dropout(p):
return (not isinstance(p, float)) or p < 1
if _should_dropout(self._input_keep_prob):
inputs = self._dropout(inputs, "input",
self._recurrent_input_noise,
self._input_keep_prob)
output, new_state = self._cell(inputs, state, scope=scope)
if _should_dropout(self._state_keep_prob):
# Identify which subsets of the state to perform dropout on and
# which ones to keep.
shallow_filtered_substructure = nest.get_traverse_shallow_structure(
self._dropout_state_filter, new_state)
new_state = self._dropout(new_state, "state",
self._recurrent_state_noise,
self._state_keep_prob,
shallow_filtered_substructure)
if _should_dropout(self._output_keep_prob):
output = self._dropout(output, "output",
self._recurrent_output_noise,
self._output_keep_prob)
return output, new_state
@tf_export("nn.rnn_cell.ResidualWrapper")
class ResidualWrapper(RNNCell):
"""RNNCell wrapper that ensures cell inputs are added to the outputs."""
def __init__(self, cell, residual_fn=None):
"""Constructs a `ResidualWrapper` for `cell`.
Args:
cell: An instance of `RNNCell`.
residual_fn: (Optional) The function to map raw cell inputs and raw cell
outputs to the actual cell outputs of the residual network.
Defaults to calling nest.map_structure on (lambda i, o: i + o), inputs
and outputs.
"""
super(ResidualWrapper, self).__init__()
self._cell = cell
if isinstance(cell, checkpointable.CheckpointableBase):
self._track_checkpointable(self._cell, name="cell")
self._residual_fn = residual_fn
@property
def state_size(self):
return self._cell.state_size
@property
def output_size(self):
return self._cell.output_size
def zero_state(self, batch_size, dtype):
with ops.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]):
return self._cell.zero_state(batch_size, dtype)
def __call__(self, inputs, state, scope=None):
"""Run the cell and then apply the residual_fn on its inputs to its outputs.
Args:
inputs: cell inputs.
state: cell state.
scope: optional cell scope.
Returns:
Tuple of cell outputs and new state.
Raises:
TypeError: If cell inputs and outputs have different structure (type).
ValueError: If cell inputs and outputs have different structure (value).
"""
outputs, new_state = self._cell(inputs, state, scope=scope)
# Ensure shapes match
def assert_shape_match(inp, out):
inp.get_shape().assert_is_compatible_with(out.get_shape())
def default_residual_fn(inputs, outputs):
nest.assert_same_structure(inputs, outputs)
nest.map_structure(assert_shape_match, inputs, outputs)
return nest.map_structure(lambda inp, out: inp + out, inputs, outputs)
res_outputs = (self._residual_fn or default_residual_fn)(inputs, outputs)
return (res_outputs, new_state)
@tf_export("nn.rnn_cell.DeviceWrapper")
class DeviceWrapper(RNNCell):
"""Operator that ensures an RNNCell runs on a particular device."""
def __init__(self, cell, device):
"""Construct a `DeviceWrapper` for `cell` with device `device`.
Ensures the wrapped `cell` is called with `tf.device(device)`.
Args:
cell: An instance of `RNNCell`.
device: A device string or function, for passing to `tf.device`.
"""
super(DeviceWrapper, self).__init__()
self._cell = cell
if isinstance(cell, checkpointable.CheckpointableBase):
self._track_checkpointable(self._cell, name="cell")
self._device = device
@property
def state_size(self):
return self._cell.state_size
@property
def output_size(self):
return self._cell.output_size
def zero_state(self, batch_size, dtype):
with ops.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]):
with ops.device(self._device):
return self._cell.zero_state(batch_size, dtype)
def __call__(self, inputs, state, scope=None):
"""Run the cell on specified device."""
with ops.device(self._device):
return self._cell(inputs, state, scope=scope)
@tf_export(v1=["nn.rnn_cell.MultiRNNCell"])
class MultiRNNCell(RNNCell):
"""RNN cell composed sequentially of multiple simple cells.
Example:
```python
num_units = [128, 64]
cells = [BasicLSTMCell(num_units=n) for n in num_units]
stacked_rnn_cell = MultiRNNCell(cells)
```
"""
@deprecated(None, "This class is equivalent as "
"tf.keras.layers.StackedRNNCells, and will be replaced by "
"that in Tensorflow 2.0.")
def __init__(self, cells, state_is_tuple=True):
"""Create a RNN cell composed sequentially of a number of RNNCells.
Args:
cells: list of RNNCells that will be composed in this order.
state_is_tuple: If True, accepted and returned states are n-tuples, where
`n = len(cells)`. If False, the states are all
concatenated along the column axis. This latter behavior will soon be
deprecated.
Raises:
ValueError: if cells is empty (not allowed), or at least one of the cells
returns a state tuple but the flag `state_is_tuple` is `False`.
"""
super(MultiRNNCell, self).__init__()
if not cells:
raise ValueError("Must specify at least one cell for MultiRNNCell.")
if not nest.is_sequence(cells):
raise TypeError(
"cells must be a list or tuple, but saw: %s." % cells)
if len(set([id(cell) for cell in cells])) < len(cells):
logging.log_first_n(logging.WARN,
"At least two cells provided to MultiRNNCell "
"are the same object and will share weights.", 1)
self._cells = cells
for cell_number, cell in enumerate(self._cells):
# Add Checkpointable dependencies on these cells so their variables get
# saved with this object when using object-based saving.
if isinstance(cell, checkpointable.CheckpointableBase):
# TODO(allenl): Track down non-Checkpointable callers.
self._track_checkpointable(cell, name="cell-%d" % (cell_number,))
self._state_is_tuple = state_is_tuple
if not state_is_tuple:
if any(nest.is_sequence(c.state_size) for c in self._cells):
raise ValueError("Some cells return tuples of states, but the flag "
"state_is_tuple is not set. State sizes are: %s"
% str([c.state_size for c in self._cells]))
@property
def state_size(self):
if self._state_is_tuple:
return tuple(cell.state_size for cell in self._cells)
else:
return sum(cell.state_size for cell in self._cells)
@property
def output_size(self):
return self._cells[-1].output_size
def zero_state(self, batch_size, dtype):
with ops.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]):
if self._state_is_tuple:
return tuple(cell.zero_state(batch_size, dtype) for cell in self._cells)
else:
# We know here that state_size of each cell is not a tuple and
# presumably does not contain TensorArrays or anything else fancy
return super(MultiRNNCell, self).zero_state(batch_size, dtype)
@property
def trainable_weights(self):
if not self.trainable:
return []
weights = []
for cell in self._cells:
if isinstance(cell, base_layer.Layer):
weights += cell.trainable_weights
return weights
@property
def non_trainable_weights(self):
weights = []
for cell in self._cells:
if isinstance(cell, base_layer.Layer):
weights += cell.non_trainable_weights
if not self.trainable:
trainable_weights = []
for cell in self._cells:
if isinstance(cell, base_layer.Layer):
trainable_weights += cell.trainable_weights
return trainable_weights + weights
return weights
def call(self, inputs, state):
"""Run this multi-layer cell on inputs, starting from state."""
cur_state_pos = 0
cur_inp = inputs
new_states = []
for i, cell in enumerate(self._cells):
with vs.variable_scope("cell_%d" % i):
if self._state_is_tuple:
if not nest.is_sequence(state):
raise ValueError(
"Expected state to be a tuple of length %d, but received: %s" %
(len(self.state_size), state))
cur_state = state[i]
else:
cur_state = array_ops.slice(state, [0, cur_state_pos],
[-1, cell.state_size])
cur_state_pos += cell.state_size
cur_inp, new_state = cell(cur_inp, cur_state)
new_states.append(new_state)
new_states = (tuple(new_states) if self._state_is_tuple else
array_ops.concat(new_states, 1))
return cur_inp, new_states
| asimshankar/tensorflow | tensorflow/python/ops/rnn_cell_impl.py | Python | apache-2.0 | 61,366 | 0.004856 |
"""
A sub-package for efficiently dealing with polynomials.
Within the documentation for this sub-package, a "finite power series,"
i.e., a polynomial (also referred to simply as a "series") is represented
by a 1-D numpy array of the polynomial's coefficients, ordered from lowest
order term to highest. For example, array([1,2,3]) represents
``P_0 + 2*P_1 + 3*P_2``, where P_n is the n-th order basis polynomial
applicable to the specific module in question, e.g., `polynomial` (which
"wraps" the "standard" basis) or `chebyshev`. For optimal performance,
all operations on polynomials, including evaluation at an argument, are
implemented as operations on the coefficients. Additional (module-specific)
information can be found in the docstring for the module of interest.
This package provides *convenience classes* for each of six different kinds
of polynomials:
======================== ================
**Name** **Provides**
======================== ================
`~polynomial.Polynomial` Power series
`~chebyshev.Chebyshev` Chebyshev series
`~legendre.Legendre` Legendre series
`~laguerre.Laguerre` Laguerre series
`~hermite.Hermite` Hermite series
`~hermite_e.HermiteE` HermiteE series
======================== ================
These *convenience classes* provide a consistent interface for creating,
manipulating, and fitting data with polynomials of different bases.
The convenience classes are the preferred interface for the `~numpy.polynomial`
package, and are available from the ``numpy.polynomial`` namespace.
This eliminates the need to navigate to the corresponding submodules, e.g.
``np.polynomial.Polynomial`` or ``np.polynomial.Chebyshev`` instead of
``np.polynomial.polynomial.Polynomial`` or
``np.polynomial.chebyshev.Chebyshev``, respectively.
The classes provide a more consistent and concise interface than the
type-specific functions defined in the submodules for each type of polynomial.
For example, to fit a Chebyshev polynomial with degree ``1`` to data given
by arrays ``xdata`` and ``ydata``, the
`~chebyshev.Chebyshev.fit` class method::
>>> from numpy.polynomial import Chebyshev
>>> c = Chebyshev.fit(xdata, ydata, deg=1)
is preferred over the `chebyshev.chebfit` function from the
``np.polynomial.chebyshev`` module::
>>> from numpy.polynomial.chebyshev import chebfit
>>> c = chebfit(xdata, ydata, deg=1)
See :doc:`routines.polynomials.classes` for more details.
Convenience Classes
===================
The following lists the various constants and methods common to all of
the classes representing the various kinds of polynomials. In the following,
the term ``Poly`` represents any one of the convenience classes (e.g.
`~polynomial.Polynomial`, `~chebyshev.Chebyshev`, `~hermite.Hermite`, etc.)
while the lowercase ``p`` represents an **instance** of a polynomial class.
Constants
---------
- ``Poly.domain`` -- Default domain
- ``Poly.window`` -- Default window
- ``Poly.basis_name`` -- String used to represent the basis
- ``Poly.maxpower`` -- Maximum value ``n`` such that ``p**n`` is allowed
- ``Poly.nickname`` -- String used in printing
Creation
--------
Methods for creating polynomial instances.
- ``Poly.basis(degree)`` -- Basis polynomial of given degree
- ``Poly.identity()`` -- ``p`` where ``p(x) = x`` for all ``x``
- ``Poly.fit(x, y, deg)`` -- ``p`` of degree ``deg`` with coefficients
determined by the least-squares fit to the data ``x``, ``y``
- ``Poly.fromroots(roots)`` -- ``p`` with specified roots
- ``p.copy()`` -- Create a copy of ``p``
Conversion
----------
Methods for converting a polynomial instance of one kind to another.
- ``p.cast(Poly)`` -- Convert ``p`` to instance of kind ``Poly``
- ``p.convert(Poly)`` -- Convert ``p`` to instance of kind ``Poly`` or map
between ``domain`` and ``window``
Calculus
--------
- ``p.deriv()`` -- Take the derivative of ``p``
- ``p.integ()`` -- Integrate ``p``
Validation
----------
- ``Poly.has_samecoef(p1, p2)`` -- Check if coefficients match
- ``Poly.has_samedomain(p1, p2)`` -- Check if domains match
- ``Poly.has_sametype(p1, p2)`` -- Check if types match
- ``Poly.has_samewindow(p1, p2)`` -- Check if windows match
Misc
----
- ``p.linspace()`` -- Return ``x, p(x)`` at equally-spaced points in ``domain``
- ``p.mapparms()`` -- Return the parameters for the linear mapping between
``domain`` and ``window``.
- ``p.roots()`` -- Return the roots of `p`.
- ``p.trim()`` -- Remove trailing coefficients.
- ``p.cutdeg(degree)`` -- Truncate p to given degree
- ``p.truncate(size)`` -- Truncate p to given size
"""
from .polynomial import Polynomial
from .chebyshev import Chebyshev
from .legendre import Legendre
from .hermite import Hermite
from .hermite_e import HermiteE
from .laguerre import Laguerre
__all__ = [
"set_default_printstyle",
"polynomial", "Polynomial",
"chebyshev", "Chebyshev",
"legendre", "Legendre",
"hermite", "Hermite",
"hermite_e", "HermiteE",
"laguerre", "Laguerre",
]
def set_default_printstyle(style):
"""
Set the default format for the string representation of polynomials.
Values for ``style`` must be valid inputs to ``__format__``, i.e. 'ascii'
or 'unicode'.
Parameters
----------
style : str
Format string for default printing style. Must be either 'ascii' or
'unicode'.
Notes
-----
The default format depends on the platform: 'unicode' is used on
Unix-based systems and 'ascii' on Windows. This determination is based on
default font support for the unicode superscript and subscript ranges.
Examples
--------
>>> p = np.polynomial.Polynomial([1, 2, 3])
>>> c = np.polynomial.Chebyshev([1, 2, 3])
>>> np.polynomial.set_default_printstyle('unicode')
>>> print(p)
1.0 + 2.0·x¹ + 3.0·x²
>>> print(c)
1.0 + 2.0·T₁(x) + 3.0·T₂(x)
>>> np.polynomial.set_default_printstyle('ascii')
>>> print(p)
1.0 + 2.0 x**1 + 3.0 x**2
>>> print(c)
1.0 + 2.0 T_1(x) + 3.0 T_2(x)
>>> # Formatting supersedes all class/package-level defaults
>>> print(f"{p:unicode}")
1.0 + 2.0·x¹ + 3.0·x²
"""
if style not in ('unicode', 'ascii'):
raise ValueError(
f"Unsupported format string '{style}'. Valid options are 'ascii' "
f"and 'unicode'"
)
_use_unicode = True
if style == 'ascii':
_use_unicode = False
from ._polybase import ABCPolyBase
ABCPolyBase._use_unicode = _use_unicode
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
| simongibbons/numpy | numpy/polynomial/__init__.py | Python | bsd-3-clause | 6,788 | 0.000148 |
import subprocess
import os
import dialog
class RDP():
def __init__(self):
self.d = dialog.Dialog(dialog="dialog")
self.storage_path = os.path.expanduser("~/LidskjalvData")
def show_rdp_menu(self, site, host):
# """ """
# FIXME
# print("FIXME: rdp_menu")
# sys.exit(1)
while True:
choices = []
choices.append(["", " "])
choices.append(["Q", "Quit"])
sz = os.get_terminal_size()
# width = sz.columns
# height = sz.lines
code, tag = self.d.menu(
"Choose an action",
height=sz.lines - 5,
width=sz.columns - 8,
menu_height=sz.lines - 15,
choices=choices)
if code == self.d.OK:
if tag == "Q":
return None
if tag == "F":
subprocess.Popen(["rdesktop", host])
if tag == "90":
subprocess.Popen(["rdesktop", host])
if tag == "75":
subprocess.Popen(["rdesktop", host])
if tag == "50":
subprocess.Popen(["rdesktop", host])
if tag == "25":
subprocess.Popen(["rdesktop", host])
"""
rdesktop
-g 1824x1026
-k da
-u USER: adusername
-d DOMAIN: myad
-p PASSWORD: password
-T 'NetworkAdmin'
-a 15
192.168.7.31
"""
| berserkerbernhard/Lidskjalv | code/networkmonitor/modules/serviceutilities/rdp.py | Python | gpl-3.0 | 1,463 | 0 |
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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 ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
| sparkslabs/kamaelia_ | Sketches/JT/Jam/library/trunk/Axon/SchedulingComponent.py | Python | apache-2.0 | 3,988 | 0.003761 |
#!/usr/bin/env python
from __future__ import print_function, division
import unittest
import sys
try:
import efuse_table_gen
except ImportError:
sys.path.append("..")
import efuse_table_gen
'''
To run the test on local PC:
cd ~/esp/esp-idf/components/efuse/test_efuse_host/
./efuse_tests.py
'''
class Py23TestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(Py23TestCase, self).__init__(*args, **kwargs)
try:
self.assertRaisesRegex
except AttributeError:
# assertRaisesRegexp is deprecated in Python3 but assertRaisesRegex doesn't exist in Python2
# This fix is used in order to avoid using the alias from the six library
self.assertRaisesRegex = self.assertRaisesRegexp
class CSVParserTests(Py23TestCase):
def test_general(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, 0, 5, Use for test name 1
name2, EFUSE_BLK3, 5, 4, Use for test name 2
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
t.verify()
self.assertEqual(t[0].field_name, 'name1')
self.assertEqual(t[0].efuse_block, 'EFUSE_BLK3')
self.assertEqual(t[0].bit_start, 0)
self.assertEqual(t[0].bit_count, 5)
self.assertEqual(t[0].comment, 'Use for test name 1')
self.assertEqual(t[1].field_name, 'name2')
self.assertEqual(t[1].efuse_block, 'EFUSE_BLK3')
self.assertEqual(t[1].bit_start, 5)
self.assertEqual(t[1].bit_count, 4)
self.assertEqual(t[1].comment, 'Use for test name 2')
def test_seq_bit_start1_fill(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, , 5,
name2, EFUSE_BLK3, , 4,
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
t.verify()
self.assertEqual(t[0].field_name, 'name1')
self.assertEqual(t[0].bit_start, 0)
self.assertEqual(t[0].bit_count, 5)
self.assertEqual(t[1].field_name, 'name2')
self.assertEqual(t[1].bit_start, 5)
self.assertEqual(t[1].bit_count, 4)
def test_seq_bit_start2_fill(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, , 5,
name2, EFUSE_BLK2, , 4,
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
t.verify()
self.assertEqual(t[0].field_name, 'name1')
self.assertEqual(t[0].bit_start, 0)
self.assertEqual(t[0].bit_count, 5)
self.assertEqual(t[1].field_name, 'name2')
self.assertEqual(t[1].bit_start, 0)
self.assertEqual(t[1].bit_count, 4)
def test_seq_bit_start3_fill(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, , 5,
name2, EFUSE_BLK2, , 4,
name3, EFUSE_BLK2, 5, 4,
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
t.verify()
self.assertEqual(t[0].field_name, 'name1')
self.assertEqual(t[0].bit_start, 0)
self.assertEqual(t[0].bit_count, 5)
self.assertEqual(t[1].field_name, 'name2')
self.assertEqual(t[1].bit_start, 0)
self.assertEqual(t[1].bit_count, 4)
self.assertEqual(t[2].field_name, 'name3')
self.assertEqual(t[2].bit_start, 5)
self.assertEqual(t[2].bit_count, 4)
def test_seq_bit_start4_fill(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, , 5,
name2, EFUSE_BLK2, , 4,
, EFUSE_BLK2, , 4,
name1, EFUSE_BLK3, , 5,
"""
with self.assertRaisesRegex(efuse_table_gen.InputError, "Field names must be unique"):
efuse_table_gen.FuseTable.from_csv(csv)
def test_seq_bit_start5_fill(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, , 5,
name2, EFUSE_BLK2, , 4,
, EFUSE_BLK2, , 4,
name3, EFUSE_BLK3, 5, 5,
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
t.verify()
self.assertEqual(t[0].field_name, 'name1')
self.assertEqual(t[0].bit_start, 0)
self.assertEqual(t[0].bit_count, 5)
self.assertEqual(t[1].field_name, 'name2')
self.assertEqual(t[1].bit_start, 0)
self.assertEqual(t[1].bit_count, 4)
self.assertEqual(t[2].field_name, 'name2')
self.assertEqual(t[2].bit_start, 4)
self.assertEqual(t[2].bit_count, 4)
self.assertEqual(t[3].field_name, 'name3')
self.assertEqual(t[3].bit_start, 5)
self.assertEqual(t[3].bit_count, 5)
def test_overlapping_bit_start_fail(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, 1, 5, Use for test name 1
name2, EFUSE_BLK3, 5, 4, Use for test name 2
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
with self.assertRaisesRegex(efuse_table_gen.InputError, "overlap"):
t.verify()
def test_empty_field_name_fail(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
, EFUSE_BLK3, , 5,
name2, EFUSE_BLK2, , 4,
"""
with self.assertRaisesRegex(efuse_table_gen.InputError, "missing field name"):
efuse_table_gen.FuseTable.from_csv(csv)
def test_unique_field_name_fail(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, 0, 5, Use for test name 1
name1, EFUSE_BLK3, 5, 4, Use for test name 2
"""
with self.assertRaisesRegex(efuse_table_gen.InputError, "Field names must be unique"):
efuse_table_gen.FuseTable.from_csv(csv)
def test_bit_count_empty_fail(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, 0, , Use for test name 1
name2, EFUSE_BLK3, 5, 4, Use for test name 2
"""
with self.assertRaisesRegex(efuse_table_gen.InputError, "empty"):
efuse_table_gen.FuseTable.from_csv(csv)
def test_bit_start_num_fail(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, k, 5, Use for test name 1
name2, EFUSE_BLK3, 5, 4, Use for test name 2
"""
with self.assertRaisesRegex(efuse_table_gen.InputError, "Invalid field value"):
efuse_table_gen.FuseTable.from_csv(csv)
def test_join_entry(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK2, 0, 6, Use for test name 1
name2, EFUSE_BLK2, 6, 5, Use for test name 2
name3, EFUSE_BLK3, 20, 5, Use for test name 3
, EFUSE_BLK3, 30, 5, Use for test name 3
name4, EFUSE_BLK2, 30, 5, Use for test name 4
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
t.verify()
self.assertEqual(t[0].field_name, 'name1')
self.assertEqual(t[0].efuse_block, 'EFUSE_BLK2')
self.assertEqual(t[0].bit_start, 0)
self.assertEqual(t[0].bit_count, 6)
self.assertEqual(t[1].field_name, 'name2')
self.assertEqual(t[1].efuse_block, 'EFUSE_BLK2')
self.assertEqual(t[1].bit_start, 6)
self.assertEqual(t[1].bit_count, 5)
self.assertEqual(t[2].field_name, 'name3')
self.assertEqual(t[2].efuse_block, 'EFUSE_BLK3')
self.assertEqual(t[2].bit_start, 20)
self.assertEqual(t[2].bit_count, 5)
self.assertEqual(t[3].field_name, 'name3')
self.assertEqual(t[3].efuse_block, 'EFUSE_BLK3')
self.assertEqual(t[3].bit_start, 30)
self.assertEqual(t[3].bit_count, 5)
self.assertEqual(t[4].field_name, 'name4')
self.assertEqual(t[4].efuse_block, 'EFUSE_BLK2')
self.assertEqual(t[4].bit_start, 30)
self.assertEqual(t[4].bit_count, 5)
def test_block_fail(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK5, 0, 5, Use for test name 1
name2, EFUSE_BLK3, 5, 4, Use for test name 2
"""
with self.assertRaisesRegex(efuse_table_gen.InputError, "'efuse_block' should consist from EFUSE_BLK0..EFUSE_BLK3"):
efuse_table_gen.FuseTable.from_csv(csv)
def test_field_size_is_ok(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK0, 0, 224, Use for test name 1
name2, EFUSE_BLK1, 0, 256, Use for test name 2
"""
efuse_table_gen.max_blk_len = 256
t = efuse_table_gen.FuseTable.from_csv(csv)
t.verify()
def test_field_blk3_size_is_more(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, 190, 1, Use for test name 1
name2, EFUSE_BLK3, 191, 5, Use for test name 2
"""
efuse_table_gen.max_blk_len = 192
t = efuse_table_gen.FuseTable.from_csv(csv)
with self.assertRaisesRegex(efuse_table_gen.InputError, "The field is outside the boundaries"):
t.verify()
def test_field_blk1_size_is_more(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK0, 0, 224, Use for test name 1
name2, EFUSE_BLK1, 1, 256, Use for test name 2
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
with self.assertRaisesRegex(efuse_table_gen.InputError, "The field is outside the boundaries"):
t.verify()
class VerificationTests(Py23TestCase):
def test_general(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, 0, 5, Use for test name 1
name2, EFUSE_BLK3, 5, 4, Use for test name 2
name1_1, EFUSE_BLK2, 0, 5, Use for test name 1_1
name2_1, EFUSE_BLK2, 5, 4, Use for test name 2_1
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
t.verify()
self.assertEqual(t[0].field_name, 'name1')
self.assertEqual(t[0].efuse_block, 'EFUSE_BLK3')
self.assertEqual(t[0].bit_start, 0)
self.assertEqual(t[0].bit_count, 5)
self.assertEqual(t[1].field_name, 'name2')
self.assertEqual(t[1].efuse_block, 'EFUSE_BLK3')
self.assertEqual(t[1].bit_start, 5)
self.assertEqual(t[1].bit_count, 4)
self.assertEqual(t[2].field_name, 'name1_1')
self.assertEqual(t[2].efuse_block, 'EFUSE_BLK2')
self.assertEqual(t[2].bit_start, 0)
self.assertEqual(t[2].bit_count, 5)
self.assertEqual(t[3].field_name, 'name2_1')
self.assertEqual(t[3].efuse_block, 'EFUSE_BLK2')
self.assertEqual(t[3].bit_start, 5)
self.assertEqual(t[3].bit_count, 4)
def test_custom_use_only_BLK3(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, 0, 5, Use for test name 1
name2, EFUSE_BLK2, 5, 4, Use for test name 2
"""
t = efuse_table_gen.FuseTable.from_csv(csv)
with self.assertRaisesRegex(efuse_table_gen.ValidationError, "custom_table should use only EFUSE_BLK3"):
t.verify("custom_table")
def test_common_and_custom_table_use_the_same_bits(self):
csv_common = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name1, EFUSE_BLK3, 0, 5, Use for test name 1
name2, EFUSE_BLK2, 5, 4, Use for test name 2
"""
common_table = efuse_table_gen.FuseTable.from_csv(csv_common)
common_table.verify("common_table")
two_tables = common_table
csv_custom = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
name3, EFUSE_BLK3, 20, 5, Use for test name 1
name4, EFUSE_BLK3, 4, 1, Use for test name 2
"""
custom_table = efuse_table_gen.FuseTable.from_csv(csv_custom)
custom_table.verify("custom_table")
two_tables += custom_table
with self.assertRaisesRegex(efuse_table_gen.InputError, "overlaps"):
two_tables.verify()
if __name__ == "__main__":
unittest.main()
| krzychb/rtd-test-bed | components/efuse/test_efuse_host/efuse_tests.py | Python | apache-2.0 | 16,074 | 0.004977 |
# -*- coding: utf-8 -*-
#
# Bottle documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 18 18:09:50 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os, time
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
bottle_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'../'))
sys.path.insert(0, bottle_dir)
import bottle
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Bottle'
copyright = unicode('2009-%s, %s' % (time.strftime('%Y'), bottle.__author__))
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
# The short X.Y version.
version = ".".join(bottle.__version__.split(".")[:2])
# The full version, including alpha/beta/rc tags.
release = bottle.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'en'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "_static/logo_nav.png"
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = "favicon.ico"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_style="bottle.css"
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'index': ['sidebar-intro.html', 'sourcelink.html', 'donation.html', 'searchbox.html'],
'**': ['localtoc.html', 'relations.html', 'sourcelink.html', 'donation.html', 'searchbox.html']
}
html_context = {
'releases': [('dev', 'development'),
('0.10', 'stable'),
('0.9', 'old stable')
]
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'Bottledoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Bottle.tex', u'Bottle Documentation',
bottle.__author__, 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
latex_logo = "_static/logo_nav.png"
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'python': ('http://docs.python.org/', None),
'werkzeug': ('http://werkzeug.pocoo.org/docs/', None)}
autodoc_member_order = 'bysource'
locale_dirs = ['./locale']
| ironexmaiden/csd_post_sw | docs/conf.py | Python | mit | 7,270 | 0.005227 |
from marshmallow import fields
from ._resource_io import ResourceSchema
class ImmutableTypeResourceSchema(ResourceSchema):
label = fields.String()
doc = fields.String()
| artPlusPlus/elemental-backend | elemental_backend/serialization/_immutable_type_resource_io.py | Python | mpl-2.0 | 180 | 0 |
#!/usr/bin/env python
r"""A simple, fast, extensible JSON encoder and decoder
JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
simplejson exposes an API familiar to uses of the standard library
marshal and pickle modules.
Encoding basic Python object hierarchies::
>>> import simplejson
>>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print simplejson.dumps("\"foo\bar")
"\"foo\bar"
>>> print simplejson.dumps(u'\u1234')
"\u1234"
>>> print simplejson.dumps('\\')
"\\"
>>> print simplejson.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> simplejson.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
Compact encoding::
>>> import simplejson
>>> compact = simplejson.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
>>> # Can't assume dict ordering
>>> compact in ('[1,2,3,{"4":5,"6":7}]', '[1,2,3,{"6":7,"4":5}]')
True
Pretty printing (using repr() because of extraneous whitespace in the output)::
>>> import simplejson
>>> print repr(simplejson.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
'{\n "4": 5, \n "6": 7\n}'
Decoding JSON::
>>> import simplejson
>>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == ["foo", {"bar":["baz", None, 1.0, 2]}]
True
>>> simplejson.loads('"\\"foo\\bar"') == '"foo\x08ar'
True
>>> from StringIO import StringIO
>>> io = StringIO('["streaming API"]')
>>> simplejson.load(io) == ["streaming API"]
True
Specializing JSON object decoding::
>>> import simplejson
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
>>> from decimal import Decimal
>>> simplejson.loads('1.1', parse_float=Decimal) == Decimal("1.1")
True
Extending JSONEncoder::
>>> import simplejson
>>> class ComplexEncoder(simplejson.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... return simplejson.JSONEncoder.default(self, obj)
...
>>> dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> ''.join(ComplexEncoder().iterencode(2 + 1j))
'[2.0, 1.0]'
Using simplejson from the shell to validate and
pretty-print::
$ echo '{"json":"obj"}' | python -msimplejson.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -msimplejson.tool
Expecting property name: line 1 column 2 (char 2)
"""
__version__ = '2.0.5'
__all__ = [
'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONEncoder',
]
from decoder import JSONDecoder
from encoder import JSONEncoder
_default_encoder = JSONEncoder(
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
encoding='utf-8',
default=None,
)
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and object
members will be pretty-printed with that indent level. An indent level
of 0 will only insert newlines. ``None`` is the most compact representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (skipkeys is False and ensure_ascii is True and
check_circular is True and allow_nan is True and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
iterable = _default_encoder.iterencode(obj)
else:
if cls is None:
cls = JSONEncoder
iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding,
default=default, **kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
for chunk in iterable:
fp.write(chunk)
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the return value will be a
``unicode`` instance subject to normal Python ``str`` to ``unicode``
coercion rules instead of being escaped to an ASCII ``str``.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (skipkeys is False and ensure_ascii is True and
check_circular is True and allow_nan is True and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding, default=default,
**kw).encode(obj)
_default_decoder = JSONDecoder(encoding=None, object_hook=None)
def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
If the contents of ``fp`` is encoded with an ASCII based encoding other
than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
be specified. Encodings that are not ASCII based (such as UCS-2) are
not allowed, and should be wrapped with
``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
object and passed to ``loads()``
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
return loads(fp.read(),
encoding=encoding, cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, **kw)
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if (cls is None and encoding is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
return cls(encoding=encoding, **kw).decode(s)
| fernandalavalle/mlab-ns | server/mapreduce/lib/simplejson/__init__.py | Python | apache-2.0 | 12,383 | 0.001615 |
from django.conf.urls import url
from admin.nodes import views
app_name = 'admin'
urlpatterns = [
url(r'^$', views.NodeFormView.as_view(),
name='search'),
url(r'^flagged_spam$', views.NodeFlaggedSpamList.as_view(),
name='flagged-spam'),
url(r'^known_spam$', views.NodeKnownSpamList.as_view(),
name='known-spam'),
url(r'^known_ham$', views.NodeKnownHamList.as_view(),
name='known-ham'),
url(r'^(?P<guid>[a-z0-9]+)/$', views.NodeView.as_view(),
name='node'),
url(r'^(?P<guid>[a-z0-9]+)/logs/$', views.AdminNodeLogView.as_view(),
name='node-logs'),
url(r'^registration_list/$', views.RegistrationListView.as_view(),
name='registrations'),
url(r'^stuck_registration_list/$', views.StuckRegistrationListView.as_view(),
name='stuck-registrations'),
url(r'^(?P<guid>[a-z0-9]+)/update_embargo/$',
views.RegistrationUpdateEmbargoView.as_view(), name='update_embargo'),
url(r'^(?P<guid>[a-z0-9]+)/remove/$', views.NodeDeleteView.as_view(),
name='remove'),
url(r'^(?P<guid>[a-z0-9]+)/restore/$', views.NodeDeleteView.as_view(),
name='restore'),
url(r'^(?P<guid>[a-z0-9]+)/confirm_spam/$', views.NodeConfirmSpamView.as_view(),
name='confirm-spam'),
url(r'^(?P<guid>[a-z0-9]+)/confirm_ham/$', views.NodeConfirmHamView.as_view(),
name='confirm-ham'),
url(r'^(?P<guid>[a-z0-9]+)/reindex_share_node/$', views.NodeReindexShare.as_view(),
name='reindex-share-node'),
url(r'^(?P<guid>[a-z0-9]+)/reindex_elastic_node/$', views.NodeReindexElastic.as_view(),
name='reindex-elastic-node'),
url(r'^(?P<guid>[a-z0-9]+)/restart_stuck_registrations/$', views.RestartStuckRegistrationsView.as_view(),
name='restart-stuck-registrations'),
url(r'^(?P<guid>[a-z0-9]+)/remove_stuck_registrations/$', views.RemoveStuckRegistrationsView.as_view(),
name='remove-stuck-registrations'),
url(r'^(?P<guid>[a-z0-9]+)/remove_user/(?P<user_id>[a-z0-9]+)/$',
views.NodeRemoveContributorView.as_view(), name='remove_user'),
]
| pattisdr/osf.io | admin/nodes/urls.py | Python | apache-2.0 | 2,100 | 0.003333 |
# 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 contrib.seq2seq.python.seq2seq.decoder."""
# pylint: disable=unused-import,g-bad-import-order
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: enable=unused-import
import numpy as np
from tensorflow.contrib.rnn import core_rnn_cell
from tensorflow.contrib.seq2seq.python.ops import decoder
from tensorflow.contrib.seq2seq.python.ops import helper as helper_py
from tensorflow.contrib.seq2seq.python.ops import basic_decoder
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import rnn
from tensorflow.python.ops import variables
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.platform import test
# pylint: enable=g-import-not-at-top
class DynamicDecodeRNNTest(test.TestCase):
def _testDynamicDecodeRNN(self, time_major, maximum_iterations=None):
sequence_length = [3, 4, 3, 1, 0]
batch_size = 5
max_time = 8
input_depth = 7
cell_depth = 10
max_out = max(sequence_length)
with self.test_session(use_gpu=True) as sess:
if time_major:
inputs = np.random.randn(max_time, batch_size,
input_depth).astype(np.float32)
else:
inputs = np.random.randn(batch_size, max_time,
input_depth).astype(np.float32)
cell = core_rnn_cell.LSTMCell(cell_depth)
helper = helper_py.TrainingHelper(
inputs, sequence_length, time_major=time_major)
my_decoder = basic_decoder.BasicDecoder(
cell=cell,
helper=helper,
initial_state=cell.zero_state(
dtype=dtypes.float32, batch_size=batch_size))
final_outputs, final_state, final_sequence_length = (
decoder.dynamic_decode(my_decoder, output_time_major=time_major,
maximum_iterations=maximum_iterations))
def _t(shape):
if time_major:
return (shape[1], shape[0]) + shape[2:]
return shape
self.assertTrue(
isinstance(final_outputs, basic_decoder.BasicDecoderOutput))
self.assertTrue(isinstance(final_state, core_rnn_cell.LSTMStateTuple))
self.assertEqual(
(batch_size,),
tuple(final_sequence_length.get_shape().as_list()))
self.assertEqual(
_t((batch_size, None, cell_depth)),
tuple(final_outputs.rnn_output.get_shape().as_list()))
self.assertEqual(
_t((batch_size, None)),
tuple(final_outputs.sample_id.get_shape().as_list()))
sess.run(variables.global_variables_initializer())
sess_results = sess.run({
"final_outputs": final_outputs,
"final_state": final_state,
"final_sequence_length": final_sequence_length,
})
# Mostly a smoke test
time_steps = max_out
if maximum_iterations is not None:
time_steps = min(max_out, maximum_iterations)
self.assertEqual(
_t((batch_size, time_steps, cell_depth)),
sess_results["final_outputs"].rnn_output.shape)
self.assertEqual(
_t((batch_size, time_steps)),
sess_results["final_outputs"].sample_id.shape)
def testDynamicDecodeRNNBatchMajor(self):
self._testDynamicDecodeRNN(time_major=False)
def testDynamicDecodeRNNTimeMajor(self):
self._testDynamicDecodeRNN(time_major=True)
def testDynamicDecodeRNNZeroMaxIters(self):
self._testDynamicDecodeRNN(time_major=True, maximum_iterations=0)
def testDynamicDecodeRNNOneMaxIter(self):
self._testDynamicDecodeRNN(time_major=True, maximum_iterations=1)
def _testDynamicDecodeRNNWithTrainingHelperMatchesDynamicRNN(
self, use_sequence_length):
sequence_length = [3, 4, 3, 1, 0]
batch_size = 5
max_time = 8
input_depth = 7
cell_depth = 10
max_out = max(sequence_length)
with self.test_session(use_gpu=True) as sess:
inputs = np.random.randn(batch_size, max_time,
input_depth).astype(np.float32)
cell = core_rnn_cell.LSTMCell(cell_depth)
zero_state = cell.zero_state(dtype=dtypes.float32, batch_size=batch_size)
helper = helper_py.TrainingHelper(inputs, sequence_length)
my_decoder = basic_decoder.BasicDecoder(
cell=cell, helper=helper, initial_state=zero_state)
# Match the variable scope of dynamic_rnn below so we end up
# using the same variables
with vs.variable_scope("root") as scope:
final_decoder_outputs, final_decoder_state, _ = decoder.dynamic_decode(
my_decoder,
# impute_finished=True ensures outputs and final state
# match those of dynamic_rnn called with sequence_length not None
impute_finished=use_sequence_length,
scope=scope)
with vs.variable_scope(scope, reuse=True) as scope:
final_rnn_outputs, final_rnn_state = rnn.dynamic_rnn(
cell,
inputs,
sequence_length=sequence_length if use_sequence_length else None,
initial_state=zero_state,
scope=scope)
sess.run(variables.global_variables_initializer())
sess_results = sess.run({
"final_decoder_outputs": final_decoder_outputs,
"final_decoder_state": final_decoder_state,
"final_rnn_outputs": final_rnn_outputs,
"final_rnn_state": final_rnn_state
})
# Decoder only runs out to max_out; ensure values are identical
# to dynamic_rnn, which also zeros out outputs and passes along state.
self.assertAllClose(sess_results["final_decoder_outputs"].rnn_output,
sess_results["final_rnn_outputs"][:, 0:max_out, :])
if use_sequence_length:
self.assertAllClose(sess_results["final_decoder_state"],
sess_results["final_rnn_state"])
def testDynamicDecodeRNNWithTrainingHelperMatchesDynamicRNNWithSeqLen(self):
self._testDynamicDecodeRNNWithTrainingHelperMatchesDynamicRNN(
use_sequence_length=True)
def testDynamicDecodeRNNWithTrainingHelperMatchesDynamicRNNNoSeqLen(self):
self._testDynamicDecodeRNNWithTrainingHelperMatchesDynamicRNN(
use_sequence_length=False)
if __name__ == "__main__":
test.main()
| wangyum/tensorflow | tensorflow/contrib/seq2seq/python/kernel_tests/decoder_test.py | Python | apache-2.0 | 6,979 | 0.006591 |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import errno
import logging
import os
import signal
import socket
import sys
from pants.java.nailgun_io import NailgunStreamWriter
from pants.java.nailgun_protocol import ChunkType, NailgunProtocol
from pants.util.socket import RecvBufferedSocket
logger = logging.getLogger(__name__)
class NailgunClientSession(NailgunProtocol):
"""Handles a single nailgun client session."""
def __init__(self, sock, in_fd, out_fd, err_fd, exit_on_broken_pipe=False):
self._sock = sock
if in_fd:
self._input_writer = NailgunStreamWriter(in_fd, self._sock,
ChunkType.STDIN, ChunkType.STDIN_EOF)
else:
self._input_writer = None
self._stdout = out_fd
self._stderr = err_fd
self._exit_on_broken_pipe = exit_on_broken_pipe
self.remote_pid = None
def _maybe_start_input_writer(self):
if self._input_writer:
self._input_writer.start()
def _maybe_stop_input_writer(self):
if self._input_writer:
self._input_writer.stop()
def _write_flush(self, fd, payload=None):
"""Write a payload to a given fd (if provided) and flush the fd."""
try:
if payload:
fd.write(payload)
fd.flush()
except (IOError, OSError) as e:
# If a `Broken Pipe` is encountered during a stdio fd write, we're headless - bail.
if e.errno == errno.EPIPE and self._exit_on_broken_pipe:
sys.exit()
# Otherwise, re-raise.
raise
def _process_session(self):
"""Process the outputs of the nailgun session."""
try:
for chunk_type, payload in self.iter_chunks(self._sock, return_bytes=True):
if chunk_type == ChunkType.STDOUT:
self._write_flush(self._stdout, payload)
elif chunk_type == ChunkType.STDERR:
self._write_flush(self._stderr, payload)
elif chunk_type == ChunkType.EXIT:
self._write_flush(self._stdout)
self._write_flush(self._stderr)
return int(payload)
elif chunk_type == ChunkType.PID:
self.remote_pid = int(payload)
elif chunk_type == ChunkType.START_READING_INPUT:
self._maybe_start_input_writer()
else:
raise self.ProtocolError('received unexpected chunk {} -> {}'.format(chunk_type, payload))
finally:
# Bad chunk types received from the server can throw NailgunProtocol.ProtocolError in
# NailgunProtocol.iter_chunks(). This ensures the NailgunStreamWriter is always stopped.
self._maybe_stop_input_writer()
def execute(self, working_dir, main_class, *arguments, **environment):
# Send the nailgun request.
self.send_request(self._sock, working_dir, main_class, *arguments, **environment)
# Process the remainder of the nailgun session.
return self._process_session()
class NailgunClient(object):
"""A python nailgun client (see http://martiansoftware.com/nailgun for more info)."""
class NailgunError(Exception):
"""Indicates an error interacting with a nailgun server."""
class NailgunConnectionError(NailgunError):
"""Indicates an error upon initial connect to the nailgun server."""
# For backwards compatibility with nails expecting the ng c client special env vars.
ENV_DEFAULTS = dict(NAILGUN_FILESEPARATOR=os.sep, NAILGUN_PATHSEPARATOR=os.pathsep)
DEFAULT_NG_HOST = '127.0.0.1'
DEFAULT_NG_PORT = 2113
def __init__(self, host=DEFAULT_NG_HOST, port=DEFAULT_NG_PORT, ins=sys.stdin, out=None, err=None,
workdir=None, exit_on_broken_pipe=False):
"""Creates a nailgun client that can be used to issue zero or more nailgun commands.
:param string host: the nailgun server to contact (defaults to '127.0.0.1')
:param int port: the port the nailgun server is listening on (defaults to the default nailgun
port: 2113)
:param file ins: a file to read command standard input from (defaults to stdin) - can be None
in which case no input is read
:param file out: a stream to write command standard output to (defaults to stdout)
:param file err: a stream to write command standard error to (defaults to stderr)
:param string workdir: the default working directory for all nailgun commands (defaults to CWD)
:param bool exit_on_broken_pipe: whether or not to exit when `Broken Pipe` errors are encountered.
"""
self._host = host
self._port = port
self._stdin = ins
self._stdout = out or sys.stdout
self._stderr = err or sys.stderr
self._workdir = workdir or os.path.abspath(os.path.curdir)
self._exit_on_broken_pipe = exit_on_broken_pipe
self._session = None
def try_connect(self):
"""Creates a socket, connects it to the nailgun and returns the connected socket.
:returns: a connected `socket.socket`.
:raises: `NailgunClient.NailgunConnectionError` on failure to connect.
"""
sock = RecvBufferedSocket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
try:
sock.connect((self._host, self._port))
except (socket.error, socket.gaierror) as e:
logger.debug('Encountered socket exception {!r} when attempting connect to nailgun'.format(e))
sock.close()
raise self.NailgunConnectionError(
'Problem connecting to nailgun server at {}:{}: {!r}'.format(self._host, self._port, e))
else:
return sock
def send_control_c(self):
"""Sends SIGINT to a nailgun server using pid information from the active session."""
if self._session and self._session.remote_pid is not None:
os.kill(self._session.remote_pid, signal.SIGINT)
def execute(self, main_class, cwd=None, *args, **environment):
"""Executes the given main_class with any supplied args in the given environment.
:param string main_class: the fully qualified class name of the main entrypoint
:param string cwd: Set the working directory for this command
:param list args: any arguments to pass to the main entrypoint
:param dict environment: an env mapping made available to native nails via the nail context
:returns: the exit code of the main_class.
"""
environment = dict(self.ENV_DEFAULTS.items() + environment.items())
cwd = cwd or self._workdir
# N.B. This can throw NailgunConnectionError (catchable via NailgunError).
sock = self.try_connect()
self._session = NailgunClientSession(sock,
self._stdin,
self._stdout,
self._stderr,
self._exit_on_broken_pipe)
try:
return self._session.execute(cwd, main_class, *args, **environment)
except socket.error as e:
raise self.NailgunError('Problem communicating with nailgun server at {}:{}: {!r}'
.format(self._host, self._port, e))
except NailgunProtocol.ProtocolError as e:
raise self.NailgunError('Problem in nailgun protocol with nailgun server at {}:{}: {!r}'
.format(self._host, self._port, e))
finally:
sock.close()
self._session = None
def __repr__(self):
return 'NailgunClient(host={!r}, port={!r}, workdir={!r})'.format(self._host,
self._port,
self._workdir)
| fkorotkov/pants | src/python/pants/java/nailgun_client.py | Python | apache-2.0 | 7,704 | 0.010903 |
import tensorflow as tf
def f():
with tf.variable_scope('A') as scope:
print scope.reuse
f()
| b29308188/cs598vqa | src/CBP/reuse_test.py | Python | mit | 98 | 0.040816 |
from . import unittest, numpy, test_int_types
from .test_multi import MultiGeometryTestCase
from shapely.geos import lgeos
from shapely.geometry import LineString, MultiLineString, asMultiLineString
from shapely.geometry.base import dump_coords
class MultiLineStringTestCase(MultiGeometryTestCase):
def test_multilinestring(self):
# From coordinate tuples
geom = MultiLineString((((1.0, 2.0), (3.0, 4.0)),))
self.assertIsInstance(geom, MultiLineString)
self.assertEqual(len(geom.geoms), 1)
self.assertEqual(dump_coords(geom), [[(1.0, 2.0), (3.0, 4.0)]])
# From lines
a = LineString(((1.0, 2.0), (3.0, 4.0)))
ml = MultiLineString([a])
self.assertEqual(len(ml.geoms), 1)
self.assertEqual(dump_coords(ml), [[(1.0, 2.0), (3.0, 4.0)]])
# From another multi-line
ml2 = MultiLineString(ml)
self.assertEqual(len(ml2.geoms), 1)
self.assertEqual(dump_coords(ml2), [[(1.0, 2.0), (3.0, 4.0)]])
# Sub-geometry Access
geom = MultiLineString([(((0.0, 0.0), (1.0, 2.0)))])
self.assertIsInstance(geom[0], LineString)
self.assertEqual(dump_coords(geom[0]), [(0.0, 0.0), (1.0, 2.0)])
with self.assertRaises(IndexError): # index out of range
geom.geoms[1]
# Geo interface
self.assertEqual(geom.__geo_interface__,
{'type': 'MultiLineString',
'coordinates': (((0.0, 0.0), (1.0, 2.0)),)})
def test_from_multilinestring_z(self):
coords1 = [(0.0, 1.0, 2.0), (3.0, 4.0, 5.0)]
coords2 = [(6.0, 7.0, 8.0), (9.0, 10.0, 11.0)]
# From coordinate tuples
ml = MultiLineString([coords1, coords2])
copy = MultiLineString(ml)
self.assertIsInstance(copy, MultiLineString)
self.assertEqual('MultiLineString',
lgeos.GEOSGeomType(copy._geom).decode('ascii'))
self.assertEqual(len(copy.geoms), 2)
self.assertEqual(dump_coords(copy.geoms[0]), coords1)
self.assertEqual(dump_coords(copy.geoms[1]), coords2)
@unittest.skipIf(not numpy, 'Numpy required')
def test_numpy(self):
from numpy import array
from numpy.testing import assert_array_equal
# Construct from a numpy array
geom = MultiLineString([array(((0.0, 0.0), (1.0, 2.0)))])
self.assertIsInstance(geom, MultiLineString)
self.assertEqual(len(geom.geoms), 1)
self.assertEqual(dump_coords(geom), [[(0.0, 0.0), (1.0, 2.0)]])
# Adapt a sequence of Numpy arrays to a multilinestring
a = [array(((1.0, 2.0), (3.0, 4.0)))]
geoma = asMultiLineString(a)
assert_array_equal(geoma.context, [array([[1., 2.], [3., 4.]])])
self.assertEqual(dump_coords(geoma), [[(1.0, 2.0), (3.0, 4.0)]])
# TODO: is there an inverse?
def test_subgeom_access(self):
line0 = LineString([(0.0, 1.0), (2.0, 3.0)])
line1 = LineString([(4.0, 5.0), (6.0, 7.0)])
self.subgeom_access_test(MultiLineString, [line0, line1])
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(MultiLineStringTestCase)
| jdmcbr/Shapely | tests/test_multilinestring.py | Python | bsd-3-clause | 3,200 | 0.000625 |
# -*- coding: utf-8 -*-
"""hamming.py: Return the Hamming distance between two integers (bitwise)."""
__author__ = "Russell J. Funk"
__date__ = "February 7, 2013"
__copyright__ = "Copyright (C) 2013"
__reference__ = ["http://wiki.python.org/moin/BitManipulation",
"http://en.wikipedia.org/wiki/Hamming_distance"]
__status__ = "Prototype"
def hamming(a, b):
"""Calculate the Hamming distance between two integers (bitwise).
Args:
a: a list of 1s and 0s
b: a list of 1s and 0s
Returns:
The hamming distance between two integers.
Raises:
Value Error: Inputs must have the same bit length.
"""
if len(a) != len(b):
raise ValueError("Inputs must have same bit length.")
else:
distance = 0
for i in range(len(a)):
if a[i] != b[i]:
distance += 1
return distance
def hamming_ratio(a, b, bits = 384):
"""Calculates the hamming ratio between two integers
represented as a list of bits.
Args:
a and b must be lists of 1s and 0s; the calculation
is relative to the number of bits.
Returns:
The hamming ratio between two integers.
"""
return float((bits - hamming(a,b)))/bits
| jkatzsam/matchtools | matchtools/hamming.py | Python | bsd-3-clause | 1,270 | 0.040157 |
# Copyright © 2017 Collabora Ltd.
#
# This file is part of pfg.
#
# pfg 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.
#
# pfg 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 pfg. If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
# Alexandros Frantzis <alexandros.frantzis@collabora.com>
| afrantzis/pixel-format-guide | tests/__init__.py | Python | lgpl-2.1 | 768 | 0 |
"""
For multi-component systems, the configurational space can be highly complicated.
One may want to use different hyper-parameters and cutoffs for different interactions,
or do constraint optimisation for hyper-parameters.
To use more hyper-parameters, we need special kernel function that can differentiate different
pairs, triplets and other descriptors and determine which number to use for what interaction.
This kernel can be enabled by using the ``hyps_mask`` argument of the GaussianProcess class.
It contains multiple arrays to describe how to break down the array of hyper-parameters and
apply them when computing the kernel. Detail descriptions of this argument can be seen in
kernel/mc_sephyps.py.
The ParameterHelper class is to generate the hyps_mask with a more human readable interface.
Example:
>>> pm = ParameterHelper(species=['C', 'H', 'O'],
... kernels={'twobody':[['*', '*'], ['O','O']],
... 'threebody':[['*', '*', '*'],
... ['O','O', 'O']]},
... parameters={'twobody0':[1, 0.5, 1], 'twobody1':[2, 0.2, 2],
... 'threebody0':[1, 0.5], 'threebody1':[2, 0.2],
... 'cutoff_threebody':1},
... constraints={'twobody0':[False, True]})
>>> hm = pm.as_dict()
>>> kernels = hm['kernels']
>>> gp_model = GaussianProcess(kernels=kernels,
... hyps=hyps, hyps_mask=hm)
In this example, four atomic species are involved. There are many kinds
of twobodys and threebodys. But we only want to use eight different signal variance
and length-scales.
In order to do so, we first define all the twobodys to be group "twobody0", by
listing "*-*" as the first element in the twobody argument. The second
element O-O is then defined to be group "twobody1". Note that the order
matters here. The later element overrides the ealier one. If
twobodys=[['O', 'O'], ['*', '*']], then all twobodys belong to group "twobody1".
Similarly, O-O-O is defined as threebody1, while all remaining ones
are left as threebody0.
The hyperpameters for each group is listed in the order of
[sig, ls, cutoff] in the parameters argument. So in this example,
O-O interaction will use [2, 0.2, 2] as its sigma, length scale, and
cutoff.
For threebody, the parameter arrays only come with two elements. So there
is no cutoff associated with threebody0 or threebody1; instead, a universal
cutoff is used, which is defined as 'cutoff_threebody'.
The constraints argument define which hyper-parameters will be optimized.
True for optimized and false for being fixed.
Here are a couple more simple examples.
Define a 5-parameter 2+3 kernel (1, 0.5, 1, 0.5, 0.05)
>>> pm = ParameterHelper(kernels=['twobody', 'threebody'],
... parameters={'sigma': 1,
... 'lengthscale': 0.5,
... 'cutoff_twobody': 2,
... 'cutoff_threebody': 1,
... 'noise': 0.05})
Define a 5-parameter 2+3 kernel (1, 1, 1, 1, 0.05)
>>> pm = ParameterHelper(kernels=['twobody', 'threebody'],
... parameters={'cutoff_twobody': 2,
... 'cutoff_threebody': 1,
... 'noise': 0.05},
... ones=ones,
... random=not ones)
Define a 9-parameter 2+3 kernel
>>> pm = ParameterHelper()
>>> pm.define_group('specie', 'O', ['O'])
>>> pm.define_group('specie', 'rest', ['C', 'H'])
>>> pm.define_group('twobody', '**', ['*', '*'])
>>> pm.define_group('twobody', 'OO', ['O', 'O'])
>>> pm.define_group('threebody', '***', ['*', '*', '*'])
>>> pm.define_group('threebody', 'Oall', ['O', 'O', 'O'])
>>> pm.set_parameters('**', [1, 0.5])
>>> pm.set_parameters('OO', [1, 0.5])
>>> pm.set_parameters('Oall', [1, 0.5])
>>> pm.set_parameters('***', [1, 0.5])
>>> pm.set_parameters('cutoff_twobody', 5)
>>> pm.set_parameters('cutoff_threebody', 4)
See more examples in functions ``ParameterHelper.define_group`` , ``ParameterHelper.set_parameters``,
and in the tests ``tests/test_parameters.py``
If you want to add in a new hyperparameter set to an already-existing GP, you can perform the
following steps:
>> hyps_mask = pm.as_dict()
>> hyps = hyps_mask['hyps']
>> kernels = hyps_mask['kernels']
>> gp_model.update_kernel(kernels, 'mc', hyps_mask)
>> gp_model.hyps = hyps
"""
import inspect
import json
import logging
import math
import numpy as np
import pickle
import time
from copy import deepcopy
from itertools import combinations_with_replacement, permutations
from numpy import array as nparray
from numpy import max as npmax
from numpy.random import random as nprandom
from typing import List, Callable, Union
from flare.output import set_logger
from flare.parameters import Parameters
from flare.utils.element_coder import element_to_Z, Z_to_element
class ParameterHelper:
"""
A helper class to construct the hyps_mask dictionary for AtomicEnvironment
, GaussianProcess and MappedGaussianProcess
Args:
hyps_mask (dict): Not implemented yet
species (dict, list): Define specie groups
kernels (dict, list): Define kernels and groups for the kernels
cutoff_groups (dict): Define different cutoffs for different species
parameters (dict): Define signal variance, length scales, and cutoffs
constraints (dict): If listed as False, the cooresponding hyperparmeters
will not be trained
allseparate (bool): If True, define each type pair/triplet into a
separate group.
random (bool): If True, randomized all signal variances and lengthscales
one (bool): If True, set all signal variances and lengthscales to one
verbose (str): Level to print with "ERROR", "WARNING", "INFO", "DEBUG"
* the ``species`` is an optional input. It can be left as None if the user only wants
to set up one group of hyper-parameters for each kernel.
* the ``kernels`` can be defined along with or without groups. But the later mode
is not compatible with the ``allseparate`` flag.
>>> kernels=['twobody', 'threebody'],
or
>>> kernels={'twobody':[['*', '*'], ['O','O']],
... 'threebody':[['*', '*', '*'],
... ['O','O', 'O']]},
Current options for the kernels are twobody, threebody and manybody (based on coordination number).
* See format of ``species``, ``kernels`` (dict), and ``cutoff_groups`` in ``list_groups()`` function.
* See format of ``parameters`` and ``constraints`` in ``list_parameters()`` function.
"""
# TO DO, sync it to kernel class
# need to be synced with kernel class
# name of the kernels
all_kernel_types = ["twobody", "threebody", "manybody"]
cutoff_types = {"cut3b": "threebody"}
cutoff_types_keys = list(cutoff_types.keys())
cutoff_types_values = list(cutoff_types.values())
additional_groups = []
# dimension of the kernels
ndim = {"twobody": 2, "threebody": 3, "manybody": 2, "cut3b": 2}
n_kernel_parameters = {"twobody": 2, "threebody": 2, "manybody": 2, "cut3b": 0}
def __init__(
self,
hyps_mask=None,
species=None,
kernels={},
cutoff_groups={},
parameters=None,
constraints={},
allseparate=False,
random=False,
ones=False,
verbose="WARNING",
):
self.logger = set_logger(
"ParameterHelper", stream=True, fileout_name=None, verbose=verbose
)
self.all_group_types = (
ParameterHelper.all_kernel_types
+ self.cutoff_types_keys
+ self.additional_groups
)
self.all_types = ["specie"] + self.all_group_types
# number of groups {'twobody': 1, 'threebody': 2}
self.n = {}
# definition of groups {'specie': [['C', 'H'], ['O']],
# 'twobody': [[['*', '*']], [[ele1, ele2]]]}
self.groups = {}
# joint values of the groups {'specie': ['C', 'H', 'O'],
# 'twobody': [['*', '*'], [ele1, ele2]]}
self.all_members = {}
# names of each group {'specie': ['group1', 'group2'], 'twobody':
# ['twobody0', 'twobody1']}
self.all_group_names = {}
# joint list of all the keys in self.all_group_names
self.all_names = []
# set up empty container
for group_type in self.all_types:
self.n[group_type] = 0
self.groups[group_type] = []
self.all_members[group_type] = []
self.all_group_names[group_type] = []
# store parameters, key should be the one used in
# all_group_names or kernel_name
self.sigma = {}
self.ls = {}
self.noise = 0.05
self.energy_noise = 0.1
self.opt = {"noise": True}
# key should be sigma, lengthscale
# cutoff_kernel_name
self.universal = {}
# key should be in all_group_names
self.all_cutoff = {}
# used for as_dict
self.hyps_sig = {}
self.hyps_ls = {}
self.hyps_opt = {}
self.cutoff_list = {}
self.mask = {}
self.hyps = None
if isinstance(kernels, dict):
self.kernel_dict = kernels
self.kernels = list(kernels.keys())
assert not allseparate
elif isinstance(kernels, list):
self.kernels = kernels
# by default, there is only one group of hyperparameters
# for each type of the kernel
# unless allseparate is defined
self.kernel_dict = {}
for ktype in kernels:
self.kernel_dict[ktype] = [["*"] * ParameterHelper.ndim[ktype]]
if species is not None:
self.list_groups("specie", species)
# define groups
if allseparate:
for ktype in self.kernels:
self.all_separate_groups(ktype)
else:
for ktype in self.kernels:
self.list_groups(ktype, self.kernel_dict[ktype])
# check for cut3b
for group in cutoff_groups:
self.list_groups(group, cutoff_groups[group])
# define parameters
if parameters is not None:
self.list_parameters(parameters, constraints)
if "lengthscale" in self.universal or "sigma" in self.universal:
universal = True
else:
universal = False
if (random + ones + universal) > 1:
raise RuntimeError("random and ones cannot be simultaneously True")
elif random or ones or universal:
for ktype in self.kernels:
self.fill_in_parameters(
ktype, random=random, ones=ones, universal=universal
)
elif len(self.kernels) > 0:
self.list_groups("specie", ["*"])
# define groups
for ktype in self.kernels:
self.list_groups(ktype, self.kernel_dict[ktype])
# check for cut3b
for group in cutoff_groups:
self.list_groups(group, cutoff_groups[group])
# define parameters
if parameters is not None:
self.list_parameters(parameters, constraints)
if "lengthscale" in self.universal or "sigma" in self.universal:
universal = True
else:
universal = False
if (random + ones + universal) > 1:
raise RuntimeError("random and ones cannot be simultaneously True")
elif random or ones or universal:
for ktype in self.kernels:
self.fill_in_parameters(
ktype, random=random, ones=ones, universal=universal
)
def list_parameters(self, parameter_dict: dict, constraints: dict = {}):
"""Define many groups of parameters
Args:
parameter_dict (dict): dictionary of all parameters
constraints (dict): dictionary of all constraints
Example:
>>> parameter_dict={"group_name":[sig, ls, cutoffs], ...}
>>> constraints={"group_name":[True, False, False], ...}
The name of parameters can be the group name previously defined in
define_group or list_groups function. Aside from the group name,
``noise``, ``cutoff_twobody``, ``cutoff_threebody``, and
``cutoff_manybody`` are reserved for noise parmater
and universal cutoffs, while ``sigma`` and ``lengthscale`` are
reserved for universal signal variances and length scales.
For non-reserved keys, the value should be a list of 2 to 3 elements,
corresponding to the sigma, lengthscale and cutoff (if the third one
is defined). For reserved keys, the value should be a float number.
The parameter_dict and constraints should use the same set of keys.
If a key in constraints is not used in parameter_dict, it will be ignored.
The value in the constraints can be either a single bool, which apply
to all parameters, or list of bools that apply to each parameter.
"""
for name in parameter_dict:
self.set_parameters(name, parameter_dict[name], constraints.get(name, True))
for name in constraints:
if name not in parameter_dict:
self.set_constraints(name, constraints[name])
def list_groups(self, group_type, definition_list):
"""define groups in batches.
Args:
group_type (str): "specie", "twobody", "threebody", "cut3b", "manybody"
definition_list (list, dict): list of elements
This function runs define_group in batch. Please first read
the manual of define_group.
If the definition_list is a list, it is equivalent to
executing define_group through the definition_list.
>>> for all terms in the list:
>>> define_group(group_type, group_type+'n', the nth term in the list)
So the first twobody defined will be group twobody0, second one will be
group twobody1. For specie, it will define all the listed elements as
groups with only one element with their original name.
If the definition_list is a dictionary, it is equivalent to
>>> for k, v in the dict:
>>> define_group(group_type, k, v)
It is not recommended to use the dictionary mode, especially when
the group definitions are conflicting with each other. There is no
guarantee that the priority order is the same as you want.
Unlike ParameterHelper.define_group(), it can only be called once for each
group_type, and not after any ParameterHelper.define_group() calls.
"""
if group_type == "specie":
if len(self.all_group_names["specie"]) > 0:
raise RuntimeError(
"this function has to be run before any define_group"
)
if isinstance(definition_list, list):
for ele in definition_list:
if isinstance(ele, list):
self.define_group("specie", ele, ele)
else:
self.define_group("specie", ele, [ele])
elif isinstance(definition_list, dict):
for ele in definition_list:
self.define_group("specie", ele, definition_list[ele])
else:
raise RuntimeError("type unknown")
else:
if self.n["specie"] == 0:
raise RuntimeError(
"this function has to be run before any define_group"
)
if isinstance(definition_list, list):
ngroup = len(definition_list)
for idg in range(ngroup):
self.define_group(
group_type, f"{group_type}{idg}", definition_list[idg]
)
elif isinstance(definition_list, dict):
for name in definition_list:
if isinstance(definition_list[name][0], list):
for ele in definition_list[name]:
self.define_group(group_type, name, ele)
else:
self.define_group(group_type, name, definition_list[name])
def all_separate_groups(self, group_type):
"""Separate all possible types of twobodys, threebodys, manybody.
One type per group.
Args:
group_type (str): "specie", "twobody", "threebody", "cut3b", "manybody"
"""
nspec = len(self.all_group_names["specie"])
if nspec < 1:
raise RuntimeError("the specie group has to be defined in advance")
if group_type in self.all_group_types:
# TO DO: the two blocks below can be replace by some upper triangle operation
# generate all possible combination of group
ele_grid = self.all_group_names["specie"]
grid = np.meshgrid(*[ele_grid] * ParameterHelper.ndim[group_type])
grid = np.array(grid).T.reshape(-1, ParameterHelper.ndim[group_type])
# remove the redundant groups
allgroup = []
for group in grid:
exist = False
set_list_group = set(list(group))
for prev_group in allgroup:
if set(prev_group) == set_list_group:
exist = True
if not exist:
allgroup += [list(group)]
# define the group
tid = 0
for group in allgroup:
self.define_group(group_type, f"{group_type}{tid}", group)
tid += 1
else:
self.logger.info(f"{group_type} will be ignored")
def fill_in_parameters(self, group_type, random=False, ones=False, universal=False):
"""Separate all possible types of twobodys, threebodys, manybody.
One type per group. And fill in either universal ls and sigma from
pre-defined parameters from set_parameters("sigma", ..) and set_parameters("ls", ..)
or random parameters if random is True.
Args:
group_type (str): "specie", "twobody", "threebody", "cut3b", "manybody"
definition_list (list, dict): list of elements
"""
nspec = len(self.all_group_names["specie"])
if nspec < 1:
raise RuntimeError("the specie group has to be defined in advance")
if random:
for group_name in self.all_group_names[group_type]:
self.set_parameters(group_name, parameters=nprandom(2))
elif ones:
for group_name in self.all_group_names[group_type]:
self.set_parameters(group_name, parameters=np.ones(2))
elif universal:
for group_name in self.all_group_names[group_type]:
self.set_parameters(
group_name,
parameters=[self.universal["sigma"], self.universal["lengthscale"]],
)
def define_group(
self, group_type, name, element_list, parameters=None, atomic_str=False
):
"""Define specie/twobody/threebody/3b cutoff/manybody group
Args:
group_type (str): "specie", "twobody", "threebody", "cut3b", "manybody"
name (str): the name use for indexing. can be anything but "*"
element_list (list): list of elements
parameters (list): corresponding parameters for this group
atomic_str (bool): whether the elements in element_list are
specified by group names or periodic table element names.
The function is helped to define different groups for specie/twobody/threebody
/3b cutoff/manybody terms. This function can be used for many times.
The later one always overrides the former one.
The name of the group has to be unique string (but not "*"), that
define a group of species or twobodys, etc. If the same name is used,
in two function calls, the definitions of the group will be merged.
Both calls will be effective.
element_list has to be a list of atomic elements, or a list of
specie group names (which should be defined in previous calls), or "*".
"*" will loop the function over all previously defined species.
It has to be two elements for twobody/3b cutoff/manybody term, or
three elements for threebody. For specie group definition, it can be
as many elements as you want.
If multiple define_group calls have conflict with element, the later one
has higher priority. For example, twobody 1-2 are defined as group1 in
the first call, and as group2 in the second call. In the end, the twobody
will be left as group2.
Example 1:
>>> define_group('specie', 'water', ['H', 'O'])
>>> define_group('specie', 'salt', ['Cl', 'Na'])
They define H and O to be group water, and Na and Cl to be group salt.
Example 2.1:
>>> define_group('twobody', 'in-water', ['H', 'H'], atomic_str=True)
>>> define_group('twobody', 'in-water', ['H', 'O'], atomic_str=True)
>>> define_group('twobody', 'in-water', ['O', 'O'], atomic_str=True)
Example 2.2:
>>> define_group('twobody', 'in-water', ['water', 'water'])
The 2.1 is equivalent to 2.2.
Example 3.1:
>>> define_group('specie', '1', ['H'])
>>> define_group('specie', '2', ['O'])
>>> define_group('twobody', 'Hgroup', ['H', 'H'], atomic_str=True)
>>> define_group('twobody', 'Hgroup', ['H', 'O'], atomic_str=True)
>>> define_group('twobody', 'OO', ['O', 'O'], atomic_str=True)
Example 3.2:
>>> define_group('specie', '1', ['H'])
>>> define_group('specie', '2', ['O'])
>>> define_group('twobody', 'Hgroup', ['H', '*'], atomic_str=True)
>>> define_group('twobody', 'OO', ['O', 'O'], atomic_str=True)
Example 3.3:
>>> list_groups('specie', ['H', 'O'])
>>> define_group('twobody', 'Hgroup', ['H', '*'])
>>> define_group('twobody', 'OO', ['O', 'O'])
Example 3.4:
>>> list_groups('specie', ['H', 'O'])
>>> define_group('twobody', 'OO', ['*', '*'])
>>> define_group('twobody', 'Hgroup', ['H', '*'])
3.1 to 3.4 are all equivalent.
"""
if name == "*" and group_type == "specie":
name = "allspecie"
element_list = ["H"]
elif name == "*":
raise ValueError(
"* is reserved for substitution, cannot be used as a group name"
)
if group_type != "specie":
assert len(element_list) == ParameterHelper.ndim[group_type]
# Check all the other group_type to
exclude_list = deepcopy(self.all_types)
ide = exclude_list.index(group_type)
exclude_list.pop(ide)
for gt in exclude_list:
if name in self.all_group_names[gt]:
raise ValueError(
"group name has to be unique across all types. "
f"{name} is found in type {gt}"
)
if name in self.all_group_names[group_type]:
groupid = self.all_group_names[group_type].index(name)
else:
groupid = self.n[group_type]
self.all_group_names[group_type].append(name)
self.groups[group_type].append([])
self.n[group_type] += 1
if group_type == "specie":
for ele in element_list:
assert (
ele not in self.all_members["specie"]
), "The element has already been defined"
self.groups["specie"][groupid].append(ele)
self.all_members["specie"].append(ele)
self.logger.debug(f"Element {ele} will be defined as group {name}")
else:
if len(self.all_group_names["specie"]) == 0:
raise RuntimeError("The atomic species have to bedefined in advance")
# first translate element/group name to group name
group_name_list = []
if atomic_str:
for ele_name in element_list:
if ele_name == "*":
gid += ["*"]
else:
for idx in range(self.n["specie"]):
group_name = self.all_group_names["specie"][idx]
if ele_name in self.groups["specie"][idx]:
group_name_list += [group_name]
self.logger.debug(
f"Element {ele_name} is used for "
"definition, but the whole group "
f"{group_name} is affected"
)
else:
group_name_list = element_list
if "*" not in group_name_list:
gid = []
for ele_name in group_name_list:
gid += [self.all_group_names["specie"].index(ele_name)]
for ele in self.all_members[group_type]:
if set(gid) == set(ele):
self.logger.debug(
f"the definition of {group_type} {ele} will be overriden"
)
self.groups[group_type][groupid].append(gid)
self.all_members[group_type].append(gid)
self.logger.debug(f"{group_type} {gid} will be defined as group {name}")
if parameters is not None:
self.set_parameters(name, parameters)
else:
one_star_less = deepcopy(group_name_list)
idstar = group_name_list.index("*")
one_star_less.pop(idstar)
for sub in self.all_group_names["specie"]:
self.logger.debug(f"{sub}, {one_star_less}")
self.define_group(
group_type,
name,
one_star_less + [sub],
parameters=parameters,
atomic_str=False,
)
def find_group(self, group_type, element_list, atomic_str=False):
"""find the group that contains the input pair
Args:
group_type (str): species, twobody, threebody, cut3b, manybody
element_list (list): list of elements for a pair/triplet/coordination-pair
atomic_str (bool): whether the elements in element_list are
specified by group names or periodic table element names.
Return:
name (str):
"""
# remember the later command override the earlier ones
if group_type == "specie":
if not isinstance(element_list, str):
self.logger.debug("for element, it has to be a string")
return None
name = None
for igroup in range(self.n["specie"]):
gname = self.all_group_names[group_type][igroup]
allspec = self.groups[group_type][igroup]
if element_list in allspec:
name = gname
if name is None:
self.logger.debug("cannot find the group")
return name
else:
if "*" in element_list:
self.logger.debug("* cannot be used for find")
return None
gid = []
for ele_name in element_list:
gid += [self.all_group_names["specie"].index(ele_name)]
name = None
for igroup in range(self.n[group_type]):
gname = self.all_group_names[group_type][igroup]
for ele in self.groups[group_type][igroup]:
if set(gid) == set(ele):
name = gname
self.logger.debug(f"find the group {name}")
return name
def set_parameters(self, name, parameters, opt=True):
"""Set the parameters for certain group
Args:
name (str): name of the patermeters
parameters (list): the sigma, lengthscale, and cutoff of each group.
opt (bool, list): whether to optimize the parameter or not
The name of parameters can be the group name previously defined in
define_group or list_groups function. Aside from the group name,
``noise``, ``cutoff_twobody``, ``cutoff_threebody``, and
``cutoff_manybody`` are reserved for noise parmater
and universal cutoffs, while ``sigma`` and ``lengthscale`` are
reserved for universal signal variances and length scales.
The parameter should be a list of 2-3 elements, for sigma,
lengthscale (and cutoff if the third one is defined).
The optimization flag can be a single bool, which apply to all
parameters, or list of bools that apply to each parameter.
"""
if name == "noise":
self.noise = parameters
self.opt["noise"] = opt
self.logger.debug(f"noise will be set as {parameters} and opt {opt}")
return
elif name == "energy_noise":
self.energy_noise = parameters
self.opt["energy_noise"] = opt
self.logger.debug(f"energy_noise will be set as {parameters} and opt {opt}")
return
elif "cutoff" in name:
self.universal[name] = parameters
self.logger.debug(f"universal cutoff {name} will be set as {parameters}")
return
elif name in ["sigma", "lengthscale"]:
self.universal[name] = parameters
self.opt[name] = opt
self.logger.debug(
f"universal {name} will be set as {parameters} and optimized {opt}"
)
return
if isinstance(opt, bool):
opt = [opt] * 2
for cut_name in self.cutoff_types:
if cut_name in name:
self.all_cutoff[name] = float(parameters)
self.logger.debug(
f"Cutoff for group {name} will be set as {parameters}"
)
return
if name in self.sigma:
self.logger.debug(f"the sig, ls of group {name} is overriden")
self.sigma[name] = parameters[0]
self.ls[name] = parameters[1]
self.opt[name + "sig"] = opt[0]
self.opt[name + "ls"] = opt[1]
self.logger.debug(
f"ParameterHelper for group {name} will be set as "
f"sig={parameters[0]} ({opt[0]}) "
f"ls={parameters[1]} ({opt[1]})"
)
if len(parameters) > 2:
if name in self.all_cutoff:
self.logger.debug(f"the cutoff of group {name} is overriden")
self.all_cutoff[name] = parameters[2]
self.logger.debug(f"Cutoff for group {name} will be set as {parameters[2]}")
def set_constraints(self, name, opt):
"""Set the parameters for certain group
Args:
name (str): name of the patermeters
opt (bool, list): whether to optimize the parameter or not
The name of parameters can be the group name previously defined in
define_group or list_groups function. Aside from the group name,
``noise``, ``cutoff_twobody``, ``cutoff_threebody``, and
``cutoff_manybody`` are reserved for noise parmater
and universal cutoffs, while ``sigma`` and ``lengthscale`` are
reserved for universal signal variances and length scales.
The optimization flag can be a single bool, which apply to all
parameters under that name, or list of bools that apply to each
parameter.
"""
if name == "noise":
self.opt["noise"] = opt
self.logger.debug(f"noise opt is set to{opt}")
return
if isinstance(opt, bool):
opt = [opt, opt, opt]
for cutname in self.cutoff_types:
if cutname in name:
return
if name in self.sigma:
self.logger.debug(f"the opt setting of group {name} is overriden")
self.opt[name + "sig"] = opt[0]
self.opt[name + "ls"] = opt[1]
self.logger.debug(
f"ParameterHelper for group {name} will be set as sig {opt[0]} ls {opt[1]}"
)
def summarize_group(self, group_type):
"""Sort and combine all the previous definition to internal varialbes
Args:
group_type (str): species, twobody, threebody, cut3b, manybody
"""
aeg = self.all_group_names[group_type]
nspecie = self.n["specie"]
# specie need special sorting
if group_type == "specie":
self.nspecie = nspecie
self.species_mask = np.ones(118, dtype=int) * (nspecie - 1)
# mark the species_mask with atom type
# default is nspecie-1
for idt in range(self.nspecie):
for ele in self.groups["specie"][idt]:
atom_n = element_to_Z(ele)
if atom_n >= len(self.species_mask):
new_mask = np.ones(atom_n, dtype=np.int) * (nspecie - 1)
new_mask[: len(self.species_mask)] = self.species_mask
self.species_mask = new_mask
self.species_mask[atom_n] = idt
self.logger.debug(
f"elemtn {ele} is defined as type {idt} with name {aeg[idt]}"
)
self.logger.debug(f"All the remaining elements are left as type {idt}")
elif group_type in self.all_group_types:
if self.n[group_type] == 0:
self.logger.debug(f"{group_type} is not defined. Skipped")
return
if (group_type not in self.kernels) and (
group_type in ParameterHelper.all_kernel_types
):
self.kernels.append(group_type)
self.mask[group_type] = np.ones(
nspecie ** ParameterHelper.ndim[group_type], dtype=int
) * (self.n[group_type] - 1)
self.hyps_sig[group_type] = []
self.hyps_ls[group_type] = []
all_opt_sig = []
all_opt_ls = []
for idt in range(self.n[group_type]):
name = aeg[idt]
for ele_list in self.groups[group_type][idt]:
# generate all possible permutation
perms = list(permutations(ele_list))
for ele_list in perms:
mask_id = 0
for ele in ele_list:
mask_id += ele
mask_id *= nspecie
mask_id = mask_id // nspecie
self.mask[group_type][mask_id] = idt
def_str = "-".join(map(str, self.groups["specie"]))
self.logger.debug(
f"{group_type} {def_str} is defined as type {idt} "
f"with name {name}"
)
if group_type not in self.cutoff_types:
sig = self.sigma.get(name, -1)
opt_sig = self.opt.get(name + "sig", True)
if sig == -1:
sig = self.sigma.get(group_type, -1)
opt_sig = self.opt.get(group_type + "sig", True)
if sig == -1:
sig = self.universal.get("sigma", -1)
opt_sig = self.opt.get("sigma", True)
ls = self.ls.get(name, -1)
opt_ls = self.opt.get(name + "ls", True)
if ls == -1:
ls = self.ls.get(group_type, -1)
opt_ls = self.opt.get(group_type + "ls", True)
if ls == -1:
ls = self.universal.get("lengthscale", -1)
opt_ls = self.opt.get("lengthscale", True)
if sig < 0 or ls < 0:
self.logger.error(
f"hyper parameters for group {name} is not defined"
)
raise RuntimeError
self.hyps_sig[group_type] += [sig]
self.hyps_ls[group_type] += [ls]
all_opt_sig += [opt_sig]
all_opt_ls += [opt_ls]
self.logger.debug(
f" using hyper-parameters of {sig:6.2g} "
f"{ls:6.2g} {opt_sig} {opt_ls}"
)
self.hyps_opt[group_type] = all_opt_sig + all_opt_ls
self.logger.debug(f"All the remaining elements are left as type {idt}")
# sort out the cutoffs
if group_type in self.cutoff_types:
universal_cutoff = self.universal.get(
"cutoff_" + self.cutoff_types[group_type], 0
)
else:
universal_cutoff = self.universal.get("cutoff_" + group_type, 0)
allcut = []
alldefine = True
for idt in range(self.n[group_type]):
if aeg[idt] in self.all_cutoff:
allcut += [self.all_cutoff[aeg[idt]]]
else:
alldefine = False
self.logger.info(
f"{aeg[idt]} cutoff is not defined. "
"it's going to use the universal cutoff."
)
if group_type not in self.cutoff_types_values:
if len(allcut) > 0:
if universal_cutoff <= 0:
universal_cutoff = np.max(allcut)
self.logger.info(
f"universal cutoff for {group_type} is defined as zero!"
f" reset it to {universal_cutoff}"
)
self.cutoff_list[group_type] = []
for idt in range(self.n[group_type]):
self.cutoff_list[group_type] += [
self.all_cutoff.get(aeg[idt], universal_cutoff)
]
self.cutoff_list[group_type] = np.array(
self.cutoff_list[group_type], dtype=float
)
max_cutoff = np.max(self.cutoff_list[group_type])
# update the universal cutoff to make it higher than
if alldefine:
universal_cutoff = max_cutoff
self.logger.info(
f"universal cutoff is updated to {universal_cutoff}"
)
elif not np.any(self.cutoff_list[group_type] - max_cutoff):
# if not all the cutoffs are defined separately
# and they are all the same value
del self.cutoff_list[group_type]
universal_cutoff = max_cutoff
if group_type in self.cutoff_types:
self.n[group_type] = 0
self.logger.info(
f"universal cutoff is updated to {universal_cutoff}"
)
else:
if universal_cutoff <= 0 and len(allcut) > 0:
universal_cutoff = np.max(allcut)
self.logger.info(
"threebody universal cutoff is updated to"
f"{universal_cutoff}, but the separate definitions will"
"be ignored"
)
if universal_cutoff > 0:
if group_type in self.cutoff_types:
keyname = "cutoff_" + self.cutoff_types[group_type]
else:
keyname = "cutoff_" + group_type
self.universal[keyname] = universal_cutoff
else:
self.logger.error(f"cutoffs for {group_type} is undefined")
raise RuntimeError
else:
pass
def as_dict(self):
"""Dictionary representation of the mask. The output can be used for AtomicEnvironment
or the GaussianProcess
"""
# sort out all the definitions and resolve conflicts
# cut3b has to be summarize before threebody
# because the universal threebody cutoff is checked
# at the end of threebody search
self.summarize_group("specie")
for ktype in self.cutoff_types:
self.summarize_group(ktype)
for ktype in ParameterHelper.additional_groups:
self.summarize_group(ktype)
for ktype in ParameterHelper.all_kernel_types:
self.summarize_group(ktype)
hyps_mask = {}
cutoff_dict = {}
hyps_mask["nspecie"] = self.n["specie"]
if self.n["specie"] > 1:
hyps_mask["species_mask"] = self.species_mask
hyps = []
hyp_labels = []
opt = []
for group in self.kernels:
hyps_mask["n" + group] = self.n[group]
hyps_mask[group + "_start"] = len(hyps)
hyps += [self.hyps_sig[group]]
hyps += [self.hyps_ls[group]]
hyps = list(np.hstack(hyps))
opt += [self.hyps_opt[group]]
cutoff_dict[group] = self.universal["cutoff_" + group]
if self.n[group] > 1:
hyps_mask[group + "_mask"] = self.mask[group]
# check parameters
aeg = self.all_group_names[group]
for idt in range(self.n[group]):
hyp_labels += ["Signal Std " + aeg[idt]]
for idt in range(self.n[group]):
hyp_labels += ["Length Scale " + aeg[idt]]
else:
hyp_labels += ["Signal Std " + group]
hyp_labels += ["Length Scale " + group]
if group in self.cutoff_list:
hyps_mask[group + "_cutoff_list"] = self.cutoff_list[group]
for cutoff_name in self.cutoff_types:
if self.n.get(cutoff_name, 0) >= 1:
hyps_mask["n" + cutoff_name] = self.n[cutoff_name]
hyps_mask[cutoff_name + "_mask"] = self.mask[cutoff_name]
hyps_mask[
self.cutoff_types[cutoff_name] + "_cutoff_list"
] = self.cutoff_list[cutoff_name]
hyps_mask["train_noise"] = self.opt["noise"]
hyps_mask["energy_noise"] = self.energy_noise
opt += [self.opt["noise"]]
hyp_labels += ["Noise std"]
hyps += [self.noise]
hyps = np.hstack(hyps)
opt = np.hstack(opt)
# handle partial optimization if any constraints are defined
if not opt.all():
nhyps = len(hyps)
hyps_mask["original_hyps"] = hyps
hyps_mask["original_labels"] = hyp_labels
mapping = []
new_labels = []
for i in range(nhyps):
if opt[i]:
mapping += [i]
new_labels += [hyp_labels[i]]
newhyps = hyps[mapping]
hyps_mask["map"] = np.array(mapping, dtype=int)
elif opt.any():
newhyps = hyps
new_labels = hyp_labels
else:
raise RuntimeError(
"hyps has length zero."
"at least one component of the hyper-parameters"
"should be allowed to be optimized. \n"
)
if self.n["specie"] < 2:
self.logger.debug(
"only one type of elements was defined. Please use multihyps=False"
)
hyps_mask["kernels"] = self.kernels
hyps_mask["kernel_name"] = "+".join(hyps_mask["kernels"])
hyps_mask["cutoffs"] = cutoff_dict
hyps_mask["hyps"] = newhyps
hyps_mask["hyp_labels"] = new_labels
logging.debug(str(hyps_mask))
return hyps_mask
@staticmethod
def from_dict(hyps_mask, verbose=False, init_spec=[]):
"""convert dictionary mask to HM instance
This function is not tested yet
"""
Parameters.check_instantiation(
hyps_mask["hyps"], hyps_mask["cutoffs"], hyps_mask["kernels"], hyps_mask
)
pm = ParameterHelper(verbose=verbose)
nspecie = hyps_mask["nspecie"]
if nspecie > 1:
max_species = np.max(hyps_mask["species_mask"])
species_mask = hyps_mask["species_mask"]
for i in range(max_species + 1):
elelist = np.where(species_mask == i)[0]
if len(elelist) > 0:
for ele in elelist:
if ele != 0:
elename = Z_to_element(ele)
if len(init_spec) > 0:
if elename in init_spec:
pm.define_group("specie", i, [elename])
else:
pm.define_group("specie", i, [elename])
else:
pm.define_group("specie", i, ["*"])
for kernel in hyps_mask["kernels"] + ParameterHelper.cutoff_types_keys:
n = hyps_mask.get("n" + kernel, 0)
if n >= 0:
if kernel not in ParameterHelper.cutoff_types:
chyps, copt = Parameters.get_component_hyps(
hyps_mask, kernel, constraint=True, noise=False
)
sig = chyps[0]
ls = chyps[1]
csig = copt[0]
cls = copt[1]
cutoff = hyps_mask["cutoffs"][kernel]
pm.set_parameters("cutoff_" + kernel, cutoff)
cutoff_list = hyps_mask.get(
f"{kernel}_cutoff_list", np.ones(len(sig)) * cutoff
)
elif kernel in ParameterHelper.cutoff_types and n > 1:
cutoff_list = hyps_mask[
ParameterHelper.cutoff_types[kernel] + "_cutoff_list"
]
if n > 1:
all_specie = np.arange(nspecie)
all_comb = combinations_with_replacement(
all_specie, ParameterHelper.ndim[kernel]
)
for comb in all_comb:
mask_id = 0
for ele in comb:
mask_id += ele
mask_id *= nspecie
mask_id = mask_id // nspecie
ttype = hyps_mask[f"{kernel}_mask"][mask_id]
pm.define_group(f"{kernel}", f"{kernel}{ttype}", comb)
if (kernel not in ParameterHelper.cutoff_types) and (
kernel not in ParameterHelper.cutoff_types_values
):
pm.set_parameters(
f"{kernel}{ttype}",
[sig[ttype], ls[ttype], cutoff_list[ttype]],
opt=[csig[ttype], cls[ttype]],
)
elif kernel in ParameterHelper.cutoff_types_values:
pm.set_parameters(
f"{kernel}{ttype}",
[sig[ttype], ls[ttype]],
opt=[csig[ttype], cls[ttype]],
)
else:
pm.set_parameters(f"{kernel}{ttype}", cutoff_list[ttype])
else:
pm.define_group(
kernel, kernel, ["*"] * ParameterHelper.ndim[kernel]
)
if kernel not in ParameterHelper.cutoff_types_keys:
pm.set_parameters(
kernel, parameters=np.hstack([sig, ls, cutoff]), opt=copt
)
else:
pm.set_parameters(kernel, parameters=cutoff)
hyps = Parameters.get_hyps(hyps_mask)
pm.set_parameters("noise", hyps[-1])
if "cutoffs" in hyps_mask:
cutoffs = hyps_mask["cutoffs"]
for k in cutoffs:
pm.set_parameters(f"cutoff_{k}", cutoffs[k])
return pm
| mir-group/flare | flare/utils/parameter_helper.py | Python | mit | 49,237 | 0.001361 |
from .check import assert_type
from .predicates import (
eq,
is_predicate,
Predicate,
AndPredicate,
OrPredicate,
NotPredicate,
)
from .relations import (
is_relation,
Main,
Relation,
AndRelation,
OrRelation,
NotRelation
)
from .rule import (
is_rule,
Production,
Rule,
OrRule,
EmptyRule,
ForwardRule,
)
__all__ = [
'rule',
'empty',
'forward',
'and_',
'or_',
'not_',
]
def prepare_production_item(item):
if not isinstance(item, (Predicate, Rule, Main)):
return eq(item)
else:
return item
def rule(*items):
production = Production([prepare_production_item(_) for _ in items])
return Rule([production])
empty = EmptyRule
forward = ForwardRule
def and_(*items):
if all(is_predicate(_) for _ in items):
return AndPredicate(items)
elif all(is_relation(_) for _ in items):
return AndRelation(items)
else:
types = [type(_) for _ in items]
raise TypeError('mixed types: %r' % types)
def or_(*items):
if all(is_predicate(_) for _ in items):
return OrPredicate(items)
elif all(is_relation(_) for _ in items):
return OrRelation(items)
elif all(is_rule(_) for _ in items):
return OrRule(items)
else:
types = [type(_) for _ in items]
raise TypeError('mixed types: %r' % types)
def not_(item):
assert_type(item, (Predicate, Relation))
if is_predicate(item):
return NotPredicate(item)
elif is_relation(item):
return NotRelation(item)
| bureaucratic-labs/yargy | yargy/api.py | Python | mit | 1,590 | 0 |
# Copyright 2018 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.
# ==============================================================================
"""Monitor is responsible for training, checkpointing and recovery."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import context
from tensorflow.python.framework import errors
from tensorflow.python.ops import variables
class Monitor(object):
"""Executes training steps, recovers and checkpoints.
Note that this class is particularly preliminary, experimental, and
expected to change.
"""
# TODO(isaprykin): Support step functions that need multiple session calls.
# TODO(isaprykin): Support extra arguments to the step function.
# TODO(isaprykin): Support recovery, checkpointing and summaries.
def __init__(self, step_callable, session=None):
"""Initialize the Monitor with components for executing training steps.
Args:
step_callable: a training `Step` that's capable of signaling when done.
session: a `Session` instance that's needed for graph mode.
Raises:
ValueError: if `session` was provided for eager mode or not provided for
graph mode.
"""
if context.executing_eagerly():
if session is not None:
raise ValueError("Should not provide a `session` in Eager mode.")
self._run_step = step_callable
else:
if session is None:
raise ValueError("Should provide a `session` in Graph mode.")
session.run(step_callable.initialize())
self._run_step = session.make_callable(step_callable())
session.run(variables.global_variables_initializer())
def run_steps(self, num_steps=None):
step = 0
while num_steps is None or step < num_steps:
try:
self._run_step()
step += 1
except errors.OutOfRangeError:
break
| ghchinoy/tensorflow | tensorflow/contrib/distribute/python/monitor.py | Python | apache-2.0 | 2,460 | 0.005691 |
"""A tool for monitoring webpages for updates
urlwatch is intended to help you watch changes in webpages and get notified
(via email, in your terminal or with a custom-written reporter class) of any
changes. The change notification will include the URL that has changed and
a unified diff of what has changed.
"""
pkgname = 'urlwatch'
__copyright__ = 'Copyright 2008-2016 Thomas Perl'
__author__ = 'Thomas Perl <m@thp.io>'
__license__ = 'BSD'
__url__ = 'http://thp.io/2008/urlwatch/'
__version__ = '2.5'
__user_agent__ = '%s/%s (+http://thp.io/2008/urlwatch/info.html)' % (pkgname, __version__)
| lechuckcaptain/urlwatch | lib/urlwatch/__init__.py | Python | bsd-3-clause | 598 | 0.001672 |
# 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.
"""oslo.i18n integration module.
See http://docs.openstack.org/developer/oslo.i18n/usage.html
"""
try:
import oslo.i18n
# NOTE(dhellmann): This reference to o-s-l-o will be replaced by the
# application name when this module is synced into the separate
# repository. It is OK to have more than one translation function
# using the same domain, since there will still only be one message
# catalog.
_translators = oslo.i18n.TranslatorFactory(domain='glanceclient')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
except ImportError:
# NOTE(dims): Support for cases where a project wants to use
# code from oslo-incubator, but is not ready to be internationalized
# (like tempest)
_ = _LI = _LW = _LE = _LC = lambda x: x
| OpenDaisy/daisy-client | daisyclient/openstack/common/_i18n.py | Python | apache-2.0 | 1,733 | 0 |
import datetime
from Tkinter import *
import tkMessageBox
import tkFileDialog
import random
import time
import share
class App(object):
'''Controls the running of the app'''
def __init__(self, master = None):
'''A controller class that runs the app
Constructor: Controller(object)'''
## Graphics
#TOP WINDOW
self._master = master
self._master.resizable(FALSE, FALSE)
self._height = 300
self._width = 900
self._master.minsize(self._width, self._height)
self._master.title("Project Capital")
self._canvas_height = self._height - 50
self._canvas_width = self._width
self.options = OptionsFrame(master, self)
self.options.pack(side = TOP, fill = X)
self.canvas = Canvas(master, bg = "black", height = self._canvas_height, width = self._canvas_width)
self.canvas.pack(side = TOP, fill = BOTH, expand = False)
#File Button
# create a toplevel menu
menubar = Menu(master)
menubar.add_command(label="Hello!")
menubar.add_command(label="Quit!")
# display the menu
master.config(menu=menubar)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open File")
filemenu.add_command(label="Save File")
filemenu.add_separator()
filemenu.add_command(label="Exit")
menubar.add_cascade(label="File", menu=filemenu)
## Ops
self._drawlist = []
self.draw_example_graph()
self.draw()
def clear(self):
self._drawlist = []
def draw(self):
self.canvas.delete(ALL)
for draw in self._drawlist:
self.canvas.create_line(draw.x0, draw.y0, draw.x1, draw.y1, fill = draw.get_fill())
self.canvas.pack()
def add_line(self, x0, y0, x1, y1, fill = None):
new_line = Draw_line(x0, y0, x1, y1)
if fill != None:
new_line.set_fill(fill)
else:
new_line.set_fill("blue")
self._drawlist.append(new_line)
def draw_rect(self):
self.add_line(-10,10,10,100)
self.add_line(10,100,100,100)
self.add_line(100,100,100,10)
self.add_line(100,10,10,10)
def draw_example_graph(self):
r = random.randrange(0,self._canvas_height)
randsum = 0
for i in range(0, self._canvas_width):
randnum = random.randrange(-1000,1000)
r = r + randnum/100.00 - ((self._canvas_height + r/2)/self._canvas_height) + 1
if r < 0: r = 0
self.add_line(i,self._canvas_height,i,self._canvas_height - r)
def load_historic(self, share_temp, share_historic):
self.clear()
print share_temp.get_name()
i = 0
max_value = float(0.0)
firstvalue = 0
for day in share_historic:
if float(day["Close"]) > max_value: max_value = float(day["Close"])
print "Max Value: " + str(max_value)
multiplyer = (self._canvas_height - 10)/max_value
print "Multipler: " + str(multiplyer)
for day in reversed(share_historic):
#print "n: " + str(self._canvas_height - float(day["Close"]))
#print float(day["Close"])
if i != 0:
if float(day["Close"]) < firstvalue:
self.add_line(i,self._canvas_height,i,self._canvas_height - float(day["Close"])*multiplyer, "red")
else:
self.add_line(i,self._canvas_height,i,self._canvas_height - float(day["Close"])*multiplyer, "green")
else:
self.add_line(i,self._canvas_height,i,self._canvas_height - float(day["Close"])*multiplyer)
firstvalue = float(day["Close"])
i += 1
class Draw_line(object):
def __init__(self, x0, y0, x1, y1):
self.x0 = x0
self.x1 = x1
self.y0 = y0
self.y1 = y1
self.fill = "black"
def set_fill(self, fill):
self.fill = fill
return
def get_fill(self):
return self.fill
class OptionsFrame(Frame):
"""Lower level GUI interface responsible for the interface to
interact with the user.
"""
def __init__ (self, master, boss):
self._master = master
self._boss = boss
Frame.__init__(self, master)
data = Frame(master)
#ENTER LABEL
symbol = Label(data,text = "Enter Symbol:").pack(side=LEFT)
#ENTER ENTRY
self.date_entry = Entry(data)
self.date_entry.pack(side=LEFT, fill = BOTH, expand = True)
#ENTER BUTTON
Button(data,text = "Enter", command = self.update_now).pack(side=LEFT)
self.t_symbol = StringVar()
self.t_close = StringVar()
self.t_change = StringVar()
self.share_change_color = StringVar()
self.share_change_color.set("black")
self.share_name = Label(data, textvariable = self.t_symbol)
self.share_close = Label(data, textvariable = self.t_close)
self.share_change = Label(data, textvariable = self.t_change, fg = self.share_change_color.get())
self.share_name.pack(side=LEFT, padx = 5)
self.share_close.pack(side=LEFT, padx = 5)
self.share_change.pack(side=LEFT, padx = 5)
data.pack(anchor = 'sw', padx = 5, pady = 5)
def update_now(self):
print "updating"
share_string = str(self.date_entry.get()) + ".AX"
share_temp = share.Stock_Info(share_string)
p_date = '2013-01-01'
t_date = time.strftime("%Y-%m-%d")
share_historic = share_temp.get_historical1(p_date,t_date)
self._boss.clear()
self._boss.load_historic(share_temp, share_historic)
self._boss.draw()
share_temp.update_quote()
self.t_symbol.set(share_temp.get_symbol())
print share_temp.get_name()
self.t_close.set(share_temp.get_quote())
print share_temp.get_quote()
self.t_change.set(share_temp.get_change() + "%")
print share_temp.get_change()
change = float(share_temp.get_change())
if change < 0:
self.share_change.config(fg = "red")
elif change > 0:
self.share_change.config(fg = "green")
else:
self.share_change.config(fg = "black")
self.share_change.pack()
def main():
root = Tk()
app = App(root)
root.mainloop()
if __name__ == '__main__':
main()
| jaric-thorning/ProjectCapital | GUI.py | Python | mit | 6,637 | 0.02019 |
from datetime import datetime
from xml.etree import ElementTree
import pkgutil
from json import loads as base_loads
from random import choice
import logging
import re
import urlparse
from sleekxmpp import ClientXMPP
from redis import Redis, ConnectionPool
import requests
from humanize import intcomma, naturaltime, intword
from pyzkb import ZKillboard
from eveapi import EVEAPIConnection
from dropbot.map import Map, base_range, ship_class_to_range
from dropbot.utils import EVEAPIRedisCache
from dropbot.stomp_listener import ZKillboardStompListener
urlparse.uses_netloc.append("redis")
zkillboard_regex = re.compile(r'http(s|):\/\/(?P<host>.*)\/kill\/(?P<killID>\d+)\/')
class UnknownCommandException(Exception):
pass
class DropBot(ClientXMPP):
def __init__(self, *args, **kwargs):
self.rooms = kwargs.pop('rooms', [])
self.nickname = kwargs.pop('nickname', 'Dropbot')
self.cmd_prefix = kwargs.pop('cmd_prefix', '!')
self.kos_url = kwargs.pop('kos_url', 'http://kos.cva-eve.org/api/')
self.hidden_commands = ['cmd_prefix']
self.last_killdate = datetime.utcnow()
self.kill_corps = [int(x) for x in kwargs.pop('kill_corps', [])]
self.kills_disabled = kwargs.pop('kills_disabled', '0') == '1'
self.kills_muted = False
self.office_api_key_keyid = kwargs.pop('office_api_keyid', None)
self.office_api_key_vcode = kwargs.pop('office_api_vcode', None)
self.market_systems = kwargs.pop('market_systems', ['Jita', 'Amarr', 'Rens', 'Dodixie', 'Hek'])
if 'redis_url' in kwargs:
self.redis_pool = ConnectionPool.from_url(kwargs.pop('redis_url', 'redis://localhost:6379/0'))
self.redis = Redis(connection_pool=self.redis_pool)
else:
logging.warning('No DROPBOT_REDIS_URL defined, EVE API calls will not be cached!')
self.redis = None
self.map = Map.from_json(pkgutil.get_data('dropbot', 'data/map.json'))
jid = kwargs.pop('jid', None)
password = kwargs.pop('password', None)
super(DropBot, self).__init__(jid, password)
self.register_plugin('xep_0030') # Service Discovery
self.register_plugin('xep_0045') # Multi-User Chat
self.register_plugin('xep_0199') # XMPP Ping
# Basic bot auto config
self.auto_subscribe = False
self.auto_authorize = True
# Handlers
self.add_event_handler('session_start', self.handle_session_start)
self.add_event_handler('message', self.handle_message)
# Reference Data
@property
def types(self):
if not hasattr(self, '_types'):
data = pkgutil.get_data('dropbot', 'data/types.json')
self._types = base_loads(data)
return self._types
@property
def stations(self):
if not hasattr(self, '_stations'):
data = pkgutil.get_data('dropbot', 'data/stations.json')
self._stations = base_loads(data)
logging.debug('Getting ConquerableStationList')
for x in self.get_eveapi().eve.ConquerableStationList().outposts:
self._stations[unicode(x.stationID)] = x.solarSystemID
return self._stations
# Command / Connection Handling
def handle_session_start(self, event):
self.get_roster()
self.send_presence()
# Join the defined MUC rooms
for room in self.rooms:
self.plugin['xep_0045'].joinMUC(room, self.nickname, wait=True)
# Start the killchecker if we have corps to monitor
if len(self.kill_corps) > 0 and not self.kills_disabled:
logging.info('Starting ZKB Stomp monitor for corps: {}'.format(', '.join(self.kill_corps)))
self.stomp = ZKillboardStompListener(self)
self.stomp.connect('tcp://eve-kill.net:61613')
else:
logging.info('Kill monitoring disabled.')
def call_command(self, command, *args, **kwargs):
if hasattr(self, 'cmd_%s' % command):
try:
resp = getattr(self, 'cmd_%s' % command)(*args, **kwargs)
except:
resp = 'Oops, something went wrong...'
logging.getLogger(__name__).exception('Error handling command')
if resp:
if isinstance(resp, tuple) and len(resp) == 2:
return resp
else:
return resp, None
else:
return None, None
else:
raise UnknownCommandException
def handle_message(self, msg):
args = msg['body'].split(' ')
cmd = args[0].lower()
args.pop(0)
if msg['type'] == 'groupchat':
if msg['mucnick'] == self.nickname:
return
if msg['body'][0] != self.cmd_prefix:
# If its not a command, check for ZKB urls
seen = set([])
response_lines = []
for match in zkillboard_regex.finditer(msg['body']):
kill_id = match.groupdict()['killID']
host = match.groupdict()['host']
logging.info('Found Kill ID {}'.format(kill_id))
if kill_id in seen:
continue
body, html = self.call_command('kill', [kill_id], msg, no_url=True, host=host)
response_lines.append(body)
seen.add(kill_id)
response_lines = [x for x in response_lines if x]
if len(response_lines):
msg.reply('\n'.join(response_lines)).send()
return
# Strip the cmd_prefix
cmd = cmd[1:]
# Call the command
try:
body, html = self.call_command(cmd, args, msg)
except UnknownCommandException:
if msg['type'] != 'groupchat':
msg.reply('Unknown command, use "help" to list all commands available').send()
pass
else:
if body:
msg.reply(body).send()
# Helpers
def _system_picker(self, name):
systems = self.map.get_systems(name)
if len(systems) > 1:
if len(systems) > 10:
return 'More than 10 systems match {}, please provide a more complete name'.format(name)
return 'Did you mean: {}?'.format(', '.join([self.map.get_system_name(x) for x in systems]))
elif len(systems) == 0:
return 'No systems found matching {}'.format(name)
else:
return systems[0]
def _item_picker(self, item):
if item.strip() == '':
return 'Usage: !price <item>'
if item.lower() == 'plex':
return (u"29668", u"30 Day Pilot's License Extension (PLEX)")
types = dict([(i, v) for i, v in self.types.iteritems() if item.lower() in v.lower()])
if len(types) == 0:
return "No items named {} found".format(item)
elif len(types) > 1:
for i, v in types.iteritems():
if item.lower() == v.lower():
return (i, v)
else:
if len(types) > 10:
return "More than 10 items found, please narrow down what you want."
return "Did you mean: {}?".format(
', '.join(types.itervalues())
)
return types.popitem()
def _get_evecentral_price(self, type_id, system_id):
try:
resp = requests.get('http://api.eve-central.com/api/marketstat?typeid={}&usesystem={}'.format(type_id, system_id))
root = ElementTree.fromstring(resp.content)
except:
return None
return (float(root.findall("./marketstat/type[@id='{}']/sell/min".format(type_id))[0].text),
float(root.findall("./marketstat/type[@id='{}']/buy/max".format(type_id))[0].text))
def _system_price(self, args, msg, system, system_id):
item = ' '.join(args)
res = self._item_picker(item)
if isinstance(res, basestring):
return res
type_id, type_name = res
try:
resp = requests.get('http://api.eve-central.com/api/marketstat?typeid={}&usesystem={}'.format(type_id, system_id))
root = ElementTree.fromstring(resp.content)
except:
return "An error occurred tying to get the price for {}".format(type_name)
return "{} @ {} | Sell: {} | Buy: {}".format(
type_name,
system,
intcomma(float(root.findall("./marketstat/type[@id='{}']/sell/min".format(type_id))[0].text)),
intcomma(float(root.findall("./marketstat/type[@id='{}']/buy/max".format(type_id))[0].text)),
)
def _get_offices(self, keyid, vcode):
"""Returns a list of offices from a Corp API key"""
logging.debug('Retreving offices for {}/{}'.format(keyid, vcode))
if not keyid or not vcode:
return []
try:
assets = self.get_eveapi_auth(keyid, vcode).corp.AssetList()
except RuntimeError:
logging.exception('Unable to retrieve asset listing for {}/{}'.format(keyid, vcode))
return []
def location_to_station(location_id):
if location_id >= 67000000:
return location_id - 6000000
if location_id >= 66000000:
return location_id - 6000001
return location_id
return [self.stations[unicode(location_to_station(x.locationID))] for x in assets.assets if x.typeID == 27]
def get_eveapi(self):
if self.redis:
return EVEAPIConnection(cacheHandler=EVEAPIRedisCache(self.redis))
return EVEAPIConnection()
def get_eveapi_auth(self, keyid, vcode):
return self.get_eveapi().auth(keyID=keyid, vCode=vcode)
def check_eveapi_permission(self, keyid, vcode, bit):
try:
accessmask = int(self.get_eveapi_auth(keyid, vcode).account.APIKeyInfo().key.accessMask)
logging.debug('Key ID {} - Access Mask: {}'.format(keyid, accessmask))
except RuntimeError:
return False
mask = 1 << bit
return (accessmask & mask) > 0
# Commands
def cmd_help(self, args, msg):
if len(args) == 0:
if msg['type'] == 'groupchat':
return "Commands: {}\nAll commands are available in private chat without the {} prefix".format(
', '.join([self.cmd_prefix + x[4:] for x in dir(self) if x[:4] == 'cmd_' and x not in self.hidden_commands]),
self.cmd_prefix
)
else:
command_lines = ['{}{}: {}'.format(self.cmd_prefix, cmd[4:], getattr(self, cmd).__doc__ or 'No documentation available') for cmd in dir(self) if cmd[:4] == 'cmd_' and cmd not in self.hidden_commands]
return "Available Commands\n\n{}".format('\n'.join(command_lines))
cmd = args[0]
if hasattr(self, 'cmd_%s' % cmd):
if getattr(self, 'cmd_%s' % cmd).__doc__ is not None:
return '{}{}: {}'.format(
self.cmd_prefix,
cmd,
getattr(self, 'cmd_%s' % cmd).__doc__
)
else:
return 'This command has no documentation'
else:
return 'Unknown command'
def cmd_bestprice(self, args, msg):
"""Returns the best price for an item out of the current known market hub systems"""
item = ' '.join(args)
res = self._item_picker(item)
if isinstance(res, basestring):
return res
type_id, type_name = res
min_sell = 0
max_buy = 0
sell_sys = None
buy_sys = None
for name in self.market_systems:
sys_id = self.map.get_system_id(name)
if not sys_id:
continue
sell, buy = self._get_evecentral_price(type_id, sys_id)
if (sell < min_sell or min_sell == 0) and sell > 0:
min_sell = sell
sell_sys = name
if buy > max_buy:
max_buy = buy
buy_sys = name
return '{}\nBest Sell: {} @ {} ISK\nBest Buy: {} @ {} ISK'.format(
type_name,
sell_sys, intcomma(min_sell),
buy_sys, intcomma(max_buy)
)
def cmd_price(self, args, msg):
"""Returns the price of an item in a particular system"""
if len(args) < 2:
return '!price <system name> <item>'
item = ' '.join(args[1:])
system_id = self._system_picker(args[0])
if isinstance(system_id, basestring):
return system_id
item = self._item_picker(item)
if isinstance(item, basestring):
return item
type_id, type_name = item
sell, buy = self._get_evecentral_price(type_id, system_id)
return '{} @ {} | Sell {} | Buy: {}'.format(
type_name,
self.map.get_system_name(system_id),
intcomma(sell),
intcomma(buy)
)
def cmd_jita(self, args, msg):
"""Returns the price of a item in Jita"""
return self.cmd_price(['Jita'] + args, msg)
def cmd_amarr(self, args, msg):
"""Returns the price of a item in Amarr"""
return self.cmd_price(['Amarr'] + args, msg)
def cmd_rens(self, args, msg):
"""Returns the price of a item in Rens"""
return self.cmd_price(['Rens'] + args, msg)
def cmd_dodixie(self, args, msg):
"""Returns the price of a item in Dodixie"""
return self.cmd_price(['Dodixie'] + args, msg)
def cmd_hek(self, args, msg):
"""Returns the price of a item in Hek"""
return self.cmd_price(['Hek'] + args, msg)
def cmd_r(self, args, msg):
return self.cmd_redditimg(args, msg)
def cmd_redditimg(self, args, msg):
"""Shows a random picture from imgur.com reddit section"""
if len(args) == 0:
return "Usage: !redditimg <subreddit>"
imgs = []
for page in range(1, 11):
for img in requests.get("http://imgur.com/r/%s/top/all/page/%s.json" % (args[0], page)).json()['data']:
resp = "%s - http://i.imgur.com/%s%s" % (img['title'], img['hash'], img['ext'])
if img['nsfw']:
resp = resp + " :nsfw:"
imgs.append(resp)
if len(imgs):
return choice(imgs)
def cmd_kos(self, args, msg):
"""Checks the CVA KOS list for a name"""
arg = ' '.join(args)
resp = requests.get(self.kos_url, params={
'c': 'json',
'q': arg,
'type': 'unit',
'details': None
})
if resp.status_code != requests.codes.ok:
return "Something went wrong (Error %s)" % resp.status_code
try:
data = resp.json()
except:
return "KOS API returned invalid data."
if data['message'] != 'OK':
return "KOS API returned an error."
if data['total'] == 0:
return "KOS returned no results (Not on KOS)"
results = []
for result in data['results']:
text = '{} ({}) - {}'.format(
result['label'],
result['type'],
'KOS' if result['kos'] else 'Not KOS'
)
results.append(text)
return '\n'.join(results)
def cmd_range(self, args, msg):
"""Returns a count of the number of systems in jump range from a source system"""
if len(args) == 0 or len(args) > 2:
return '!range <system> <ship class>'
system = args[0]
if len(args) == 2:
ship_class = args[1].lower()
else:
ship_class = 'blackops'
if ship_class not in base_range.keys():
return 'Unknown class {}, please use one of: {}'.format(
ship_class,
', '.join(base_range.keys())
)
system_id = self._system_picker(system)
if isinstance(system_id, basestring):
return system_id
res = {}
systems = self.map.neighbors_jump(system_id, ship_class=ship_class)
for sys, range in systems:
if sys['region'] in res:
res[sys['region']] += 1
else:
res[sys['region']] = 1
return '{} systems in JDC5 {} range of {}:\n'.format(len(systems), ship_class, self.map.get_system_name(system_id)) + '\n'.join(['{} - {}'.format(x, y) for x, y in res.items()])
def cmd_route(self, args, msg):
"""Shows the shortest route between two sytems"""
if len(args) != 2:
return '!route <source> <destination>'
source, dest = args
source = self._system_picker(source)
if isinstance(source, basestring):
return source
dest = self._system_picker(dest)
if isinstance(dest, basestring):
return dest
route = self.map.route_gate(source, dest)
route_names = ' -> '.join(['{} ({})'.format(x['name'], round(x['security'], 2)) for x in [self.map.node[y] for y in route]])
return '{} jumps from {} to {}\n{}'.format(
len(route)-1,
self.map.get_system_name(source),
self.map.get_system_name(dest),
route_names
)
def cmd_addjb(self, args, msg):
"""Adds a jumpbridge to the internal map for routing purposes"""
if len(args) != 2:
return '!addjb <source> <destination>'
source, dest = args
source = self._system_picker(source)
if isinstance(source, basestring):
return source
dest = self._system_picker(dest)
if isinstance(dest, basestring):
return dest
self.map.add_jumpbridge(source, dest)
return "Done"
def cmd_listjbs(self, args, msg):
"""List all known jumpbridges stored in the map"""
resp_lines = []
for u, v, d in self.map.edges_iter(data=True):
if d['link_type'] == 'bridge':
line = '{} <-> {} ({}ly)'.format(
self.map.get_system_name(u),
self.map.get_system_name(v),
round(self.map.system_distance(u, v), 2),
)
resp_lines.append(line)
return '\n'.join(resp_lines)
def cmd_mapstats(self, args, msg):
"""Gives the current overview of the internal map"""
return '{} systems, {} gate jumps, {} jump bridges'.format(
len(self.map.nodes()),
len([u for u, v, d in self.map.edges_iter(data=True) if d['link_type'] == 'gate']),
len([u for u, v, d in self.map.edges_iter(data=True) if d['link_type'] == 'bridge'])
)
def cmd_hit(self, args, msg):
"""Details what class and JDC level is required to jump between two systems"""
if len(args) != 2:
return '!hit <source> <destination>'
source, dest = args
source = self._system_picker(source)
if isinstance(source, basestring):
return source
dest = self._system_picker(dest)
if isinstance(dest, basestring):
return dest
if self.map.node[dest]['security'] >= 0.5:
return '{} is a highsec system'.format(self.map.get_system_name(dest))
ly = self.map.system_distance(source, dest)
if ly > 6.5 * (1 + (0.25 * 5)):
return '{} to {} is greater than {}ly (maximum jump range of all ships)'.format(
self.map.get_system_name(source),
self.map.get_system_name(dest),
6.5 * (1 + (0.25 * 5))
)
res = []
for ship_class in base_range.keys():
res1 = []
for skill in [4, 5]:
if ship_class_to_range(ship_class, skill) >= ly:
res1.append('JDC{}'.format(skill))
if len(res1):
res.append('{}: {}'.format(ship_class, ', '.join(res1)))
return '{} -> {} ({}ly) Capable Ship Types:\n{}'.format(
self.map.get_system_name(source),
self.map.get_system_name(dest),
round(ly, 2),
'\n'.join(res)
)
def cmd_jump(self, args, msg):
"""Calculates the shortest jump route between two systems"""
if len(args) < 2:
return '!jump <source> <destination> (<ship class> <jdc level> <jfc level>)'
elif len(args) == 2:
source, dest = args
ship_class = 'blackops'
jdc = jfc = 5
elif len(args) == 3:
source, dest, ship_class = args
jdc = jfc = 5
elif len(args) == 4:
source, dest, ship_class, jdc = args
jfc = 5
else:
source, dest, ship_class, jdc, jfc = args
jf = 5
source = self._system_picker(source)
if isinstance(source, basestring):
return source
dest = self._system_picker(dest)
if isinstance(dest, basestring):
return dest
if ship_class not in base_range.keys():
return 'Unknown class {}, please use one of: {}'.format(
ship_class,
', '.join(base_range.keys())
)
try:
int(jdc)
int(jfc)
except ValueError:
return 'Invalid JDC/JFC level'
route = self.map.route_jump(source, dest, ship_class=ship_class)
if len(route):
return '{} to {} ({}/{}/{}), {} jumps ({}ly / {} isotopes):\n{}'.format(
self.map.get_system_name(source),
self.map.get_system_name(dest),
ship_class,
jdc,
jfc,
len(route)-1,
round(self.map.route_jump_distance(route), 2),
round(self.map.route_jump_isotopes(route, int(jfc), ship_class=ship_class, jf_skill=jf), 0),
' -> '.join([self.map.get_system_name(x) for x in route])
)
else:
return 'No route found'
def cmd_id(self, args, msg):
"""Provides an overview of a character's activity in-game"""
if len(args) == 0:
return '!id <character name>'
char_name = ' '.join(args)
result = self.get_eveapi().eve.CharacterID(names=char_name.strip())
char_name = result.characters[0].name
char_id = result.characters[0].characterID
if char_id == 0:
return 'Unknown character {}'.format(char_name)
headers, res = ZKillboard().characterID(char_id).kills().pastSeconds(60 * 60 * 24 * 7).get()
from collections import defaultdict, Counter
kill_types = defaultdict(int)
ship_types = defaultdict(int)
alli_assoc = defaultdict(int)
sum_value = 0.0
for kill in res:
kill_type_id = int(kill['victim']['shipTypeID'])
if kill_type_id > 0:
kill_types[self.types[unicode(kill_type_id)]] += 1
sum_value += float(kill['zkb']['totalValue'])
for attk in kill['attackers']:
if attk['allianceName'].strip() != '' and attk['allianceName'] is not None:
alli_assoc[attk['allianceName']] += 1
if int(attk['characterID']) == char_id:
ship_type_id = int(attk['shipTypeID'])
if ship_type_id > 0:
ship_types[self.types[unicode(ship_type_id)]] += 1
break
if len(res) == 0:
return '{} has had no kills in the last week'.format(char_name)
kill_types = Counter(kill_types).most_common(5)
ship_types = Counter(ship_types).most_common(5)
alli_assoc = Counter(alli_assoc).most_common(5)
return '{}, {} kill(s) ({} ISK) in the last week\nActive Systems: {}\nTop 5 Killed Types: {}\nTop 5 Ship: {}\nTop 5 Associates: {}'.format(
char_name,
len(res),
intcomma(sum_value),
', '.join(set([self.map.node[int(x['solarSystemID'])]['name'] for x in res])),
', '.join(['{} ({})'.format(x, y) for x, y in kill_types]),
', '.join(['{} ({})'.format(x, y) for x, y in ship_types]),
', '.join([x for x, y in alli_assoc])
)
def cmd_kill(self, args, msg, no_url=False, raw=None, host=None):
"""Returns a summary of a zKillboard killmail"""
if not raw:
if len(args) == 0:
return '!kill <Kill ID/zKillboard URL>'
kill_id = args[0]
try:
kill_id = int(kill_id)
except ValueError:
m = zkillboard_regex.match(kill_id)
if m:
kill_id = m.groupdict()['killID']
host = m.groupdict()['host']
else:
return 'Invalid kill ID'
headers, data = ZKillboard(base_url='https://{}/api/'.format(host)).killID(kill_id).get()
kill = data[0]
else:
kill = raw
kill_id = raw['killID']
if no_url:
url = ''
else:
url = ' - https://{}/kill/{}/'.format(host, kill_id)
# Ignore kills over an hour old if they're from stomp
age = (datetime.utcnow() - datetime.strptime(kill['killTime'], '%Y-%m-%d %H:%M:%S'))
if age.total_seconds() > 60 * 60 and raw:
return
# Drop kills less than 1mil if they've come from stomp
if raw and float(kill['zkb']['totalValue']) < 1000000:
return
if 'zkb' in kill and 'totalValue' in kill['zkb']:
value_lost = intword(float(kill['zkb']['totalValue']))
else:
value_lost = '???'
return '{} ({}) in {}, {}, {} attacker(s), {} ISK lost{}'.format(
kill['victim']['characterName'],
self.types[unicode(kill['victim']['shipTypeID'])],
self.map.node[int(kill['solarSystemID'])]['name'],
naturaltime(age),
len(kill['attackers']),
value_lost,
url,
)
def cmd_mute(self, args, msg):
"""Mutes killmail broadcast for 30 minutes"""
self.kills_muted = True
def unmute(self):
self.kills_muted = False
self.schedule('unmute', 30 * 60, unmute, [self])
return 'Killmails muted, posting will resume automatically in 30 minutes'
def cmd_nearestoffice(self, args, msg):
if len(args) != 1:
return '!nearestoffice <system>'
source = args[0]
if not self.office_api_key_keyid or not self.office_api_key_vcode:
return 'No Corp API key is setup'
if not self.check_eveapi_permission(self.office_api_key_keyid, self.office_api_key_vcode, 1):
return "The API key setup doesn't have the correct permissions"
source = self._system_picker(source)
if isinstance(source, basestring):
return source
min_route = None
target_office = None
for office in self._get_offices(self.office_api_key_keyid, self.office_api_key_vcode):
if office == source:
return 'An office is in the target system'
route_length = len(self.map.route_gate(source, office)) - 1
if not min_route or (route_length) < min_route:
target_office = office
min_route = route_length
if target_office:
return 'Nearest Office to {} is {}, {} jump(s)'.format(
self.map.get_system_name(source),
self.map.get_system_name(target_office),
min_route,
)
return 'No known offices.'
def cmd_rageping(self, args, msg):
"""Ping spams everyone's name in a room, use with caution"""
if msg['type'] != 'groupchat':
return 'This only works in MUC rooms'
names = self.plugin['xep_0045'].getRoster(msg['from'].bare)
return 'RAGE PING: {} :frogsiren:'.format(', '.join(names))
| nikdoof/dropbot | dropbot/bot.py | Python | mit | 28,390 | 0.001937 |
SERVER_HOSTNAME = "127.0.0.1"
SERVER_PORT = 9671
| prerit2010/web-frontend | config.py | Python | gpl-3.0 | 49 | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006 - 2010 Loic Dachary <loic@dachary.org>
# Copyright (C) 2006 Mekensleep
#
# Mekensleep
# 26 rue des rosiers
# 75004 Paris
# licensing@mekensleep.com
#
# 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 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 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 St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# Authors:
# Pierre-Andre (05/2006)
# Loic Dachary <loic@dachary.org>
#
import os
import sys
import shutil
import libxml2
import string
import tempfile
import math
import unittest
from os import path
TESTS_PATH = path.dirname(path.realpath(__file__))
sys.path.insert(0, path.join(TESTS_PATH, ".."))
from tests.log_history import log_history
from collections import namedtuple
from pokerengine import pokercards
from pokerengine import pokergame
from tests.testmessages import search_output, clear_all_messages, get_messages
try:
from nose.plugins.attrib import attr
except ImportError, e:
def attr(fn): return fn
CallbackIds = None
CallbackArgs = None
# ---------------------------------------------------------
def InitCallback():
global CallbackIds
global CallbackArgs
CallbackIds = None
CallbackArgs = None
# ---------------------------------------------------------
def Callback(id, *args):
global CallbackIds
global CallbackArgs
if not CallbackIds: CallbackIds = []
if not CallbackArgs: CallbackArgs = []
CallbackIds.append(id)
CallbackArgs.append(args)
# ---------------------------------------------------------
class PokerPredefinedDecks:
def __init__(self, decks):
self.decks = decks
self.index = 0
def shuffle(self, deck):
deck[:] = self.decks[self.index][:]
self.index += 1
if self.index >= len(self.decks):
self.index = 0
# ---------------------------------------------------------
class PokerGameTestCase(unittest.TestCase):
TestConfDirectory = path.join(TESTS_PATH, 'test-data/conf')
TestVariantInvalidFile = 'unittest.variant.invalid.xml'
TestVariantTemplateFile = 'unittest.variant.template.xml'
TestConfigTemplateFile = 'unittest.config.template.xml'
TestLevelsTemplateFile = 'unittest.levels.template.xml'
TestUrl = 'unittest.%s.xml'
TestConfigTemporaryFile = 'config'
TestVariantTemporaryFile = 'variant'
# ---------------------------------------------------------
def setUp(self):
self.VariantInvalidFile = path.join(PokerGameTestCase.TestConfDirectory, PokerGameTestCase.TestVariantInvalidFile)
self.ConfigTmplFile = path.join(PokerGameTestCase.TestConfDirectory, PokerGameTestCase.TestConfigTemplateFile)
self.VariantTmplFile = path.join(PokerGameTestCase.TestConfDirectory, PokerGameTestCase.TestVariantTemplateFile)
self.LevelsTmplFile = path.join(PokerGameTestCase.TestConfDirectory, PokerGameTestCase.TestLevelsTemplateFile)
self.ConfigTempFile = path.join(tempfile.gettempdir(), PokerGameTestCase.TestUrl % PokerGameTestCase.TestConfigTemporaryFile)
self.VariantTempFile = path.join(tempfile.gettempdir(), PokerGameTestCase.TestUrl % PokerGameTestCase.TestVariantTemporaryFile)
self.CreateGameServer()
self.InitGame()
InitCallback()
# ---------------------------------------------------------
def tearDown(self):
self.DeleteFile(self.ConfigTempFile)
self.DeleteFile(self.VariantTempFile)
# ---------------------------------------------------------
def testUniq(self):
"""Test Poker Game: Uniq"""
self.failUnlessEqual(pokergame.uniq([1, 4, 4, 7]).sort(), [1, 4, 7].sort())
self.failUnlessEqual(pokergame.uniq([1, 4, 4, 7, 3, 3, 3, 9, 7]).sort(), [1, 3, 4, 7, 9].sort())
# ---------------------------------------------------------
def testGetSerialByNameNoCase(self):
"""Test Poker Game: Get serial by name no case sensitive"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Set the player's name
player1.name = 'Player1'
player2.name = 'Player2'
# Seach player by his name (no case sensitive)
self.failUnlessEqual(self.game.getSerialByNameNoCase('player1'), 1)
self.failUnlessEqual(self.game.getSerialByNameNoCase('pLaYEr2'), 2)
self.failUnlessEqual(self.game.getSerialByNameNoCase('unknown'), 0)
# ---------------------------------------------------------
def testSetPosition(self):
"""Test Poker Game: Set position"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Position initially set to -1
self.failUnlessEqual(self.game.position, -1)
# The game is not running, the set position function is not avalaible
self.failIf(self.game.isRunning())
self.game.setPosition(5)
self.failUnlessEqual(self.game.position, -1)
# Blind and ante turn
self.game.forced_dealer_seat = 2
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The game is running, the set position function is available
self.failUnless(self.game.isRunning())
self.game.setPosition(2)
self.failUnlessEqual(self.game.position, 2)
self.failUnlessEqual(self.game.getSerialInPosition(), 3)
# Invalid position
self.game.setPosition(-1)
self.failUnlessEqual(self.game.getSerialInPosition(), 0)
# ---------------------------------------------------------
def testPokerGameSetInvalidMaxPlayer(self):
"""Test Poker Game: Set an invalid number max of player"""
# The minimum number of player is 2
self.game.setMaxPlayers(0)
self.failUnlessEqual(self.game.seatsLeftCount(), 0)
self.failUnlessEqual(self.game.seatsCount(), 0)
self.game.setMaxPlayers(1)
self.failUnlessEqual(self.game.seatsLeftCount(), 0)
self.failUnlessEqual(self.game.seatsCount(), 0)
# The maximum number of player is sepcified by the ABSOLUTE_MAX_PLAYERS constant
self.game.setMaxPlayers(pokergame.ABSOLUTE_MAX_PLAYERS + 1)
self.failUnlessEqual(self.game.seatsLeftCount(), 0)
self.failUnlessEqual(self.game.seatsCount(), 0)
# ---------------------------------------------------------
def testPokerGameSetValidMaxPlayer(self):
"""Test Poker Game: Set a valid number max of player"""
# Test all the valid numbers of player
for num in range(2,pokergame.ABSOLUTE_MAX_PLAYERS):
self.game.setMaxPlayers(num)
self.failUnlessEqual(self.game.seatsLeftCount(), num)
self.failUnlessEqual(self.game.seatsCount(), num)
# ---------------------------------------------------------
def testSetSeats(self):
"""Test Poker Game: Set seats"""
# Set the number maximum of players, the available seats are [1, 3, 6, 8]
self.game.setMaxPlayers(4)
# Create players
for player in range(1, 5):
player = self.AddPlayerAndSit(player)
# Set the seats of all the players
seats = [0] * pokergame.ABSOLUTE_MAX_PLAYERS
seats[1] = 1
seats[3] = 3
seats[6] = 4
seats[8] = 2
self.game.setSeats(seats)
self.failUnlessEqual(self.GetPlayer(1).seat, 1)
self.failUnlessEqual(self.GetPlayer(2).seat, 8)
self.failUnlessEqual(self.GetPlayer(3).seat, 3)
self.failUnlessEqual(self.GetPlayer(4).seat, 6)
# Set the seats of all the players
# The seat of the player 3 is not available
seats = [0] * pokergame.ABSOLUTE_MAX_PLAYERS
seats[1] = 1
seats[4] = 3
seats[6] = 4
seats[8] = 2
self.game.setSeats(seats)
self.failUnlessEqual(self.GetPlayer(3).seat, -1)
def testGetBestSeat(self):
self.game.setMaxPlayers(6)
# seats_left: 0, 2, 4, 5, 7, 8
# D S B
# Test for empty game
self.assertTrue(self.game.getBestSeat() is not None)
# Test with one player
dealer_seat = 2
small_blind_seat = 5
big_blind_seat = 8
self.assertTrue(self.game.addPlayer(1, seat=dealer_seat, name="dealer") is not None)
self.game.isRunning = lambda : True
best_seat = self.game.getBestSeat()
self.assertTrue(best_seat in self.game.seats_left and best_seat != dealer_seat)
self.assertTrue(self.game.addPlayer(2, seat=small_blind_seat, name="small") is not None)
self.game.player_list = [1,2]
self.game.dealer = 0
self.assertEqual(self.game.getBestSeat(), 4)
self.assertTrue(self.game.addPlayer(3, seat=big_blind_seat, name="big") is not None)
self.game.player_list = [1,2,3]
self.assertTrue(self.game.addPlayer(10, name="whatever") is not None)
self.assertEqual(self.game.getPlayer(10).seat, 0)
self.assertTrue(self.game.addPlayer(20, name="whatever") is not None)
self.assertEqual(self.game.getPlayer(20).seat, 4)
self.assertEqual(self.game.getBestSeat(), 7)
# ---------------------------------------------------------
def testPokerGameOpen(self):
"""Test Poker Game: Open and close"""
self.failUnlessEqual(self.game.is_open, True)
self.game.close()
self.failUnlessEqual(self.game.is_open, False)
self.game.open()
self.failUnlessEqual(self.game.is_open, True)
# ---------------------------------------------------------
def testPokerGameCanAddPlayer(self):
"""Test Poker Game: Can add player"""
# The player can be added to the game
self.failUnless(self.game.canAddPlayer(1))
# No player can be added if the game is closed
self.game.close()
self.failIf(self.game.canAddPlayer(2))
# Player can be added if the game is opened
self.game.open()
self.failUnless(self.game.canAddPlayer(2))
# ---------------------------------------------------------
def testPokerGameAddPlayerWithoutSelectedSeat(self):
"""Test Poker Game: Add a player without a selected seat"""
# Add a new player
p1 = self.game.addPlayer(1)
self.failUnless(p1 != None)
self.failUnless(self.game.isSeated(1))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Try to add the same player
self.failUnless(p1 == self.game.addPlayer(1))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Add a new player
self.failUnless(self.game.addPlayer(2))
self.failUnless(self.game.isSeated(2))
self.failUnlessEqual(self.game.seatsLeftCount(), 0)
# Try to add new one but there is no seat left
self.failIf(self.game.addPlayer(3))
self.failIf(self.game.isSeated(3))
self.failUnlessEqual(self.game.seatsLeftCount(), 0)
# ---------------------------------------------------------
def testPokerGameAddPlayerWithSelectedSeat(self):
"""Test Poker Game: Add a player with a selected seat"""
# Add a player on the seat 2
self.failUnless(self.game.addPlayer(1,2))
self.failUnless(self.game.isSeated(1))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Try to add the same player on the same seat
self.failUnless(self.game.addPlayer(1,2))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Try to add the same player on another seat
self.failIf(self.game.addPlayer(1,7))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Try to add a new player on an invalid seat
self.failIf(self.game.addPlayer(2,3))
self.failIf(self.game.isSeated(2))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Try to add a new player on an unavailable seat
self.failIf(self.game.addPlayer(2,2))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Add a player on the seat 7
self.failUnless(self.game.addPlayer(2,7))
self.failUnless(self.game.isSeated(2))
self.failUnlessEqual(self.game.seatsLeftCount(), 0)
# ---------------------------------------------------------
def testPokerGameAddPlayerClientGame(self):
"""Test Poker Game: Add a player client game"""
# Create a client game
self.CreateGameClient()
self.InitGame()
# Try to add a new player without a selected seat
self.failIf(self.game.addPlayer(1))
self.failIf(self.game.isSeated(1))
self.failUnlessEqual(self.game.seatsLeftCount(), 2)
# Add a player on the seat 2
self.failUnless(self.game.addPlayer(1,2))
self.failUnless(self.game.isSeated(1))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Try to add the same player on the same seat
self.failUnless(self.game.addPlayer(1,2))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Try to add the same player on another seat
self.failUnless(self.game.addPlayer(1,7) == None)
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Try to add a new player on an invalid seat
self.failUnless(self.game.addPlayer(2,3) == None)
self.failIf(self.game.isSeated(2))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Try to add a new player on an unavailable seat
self.failUnless(self.game.addPlayer(2,2) == None)
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Add a player on the seat 7
self.failUnless(self.game.addPlayer(2,7))
self.failUnless(self.game.isSeated(2))
self.failUnlessEqual(self.game.seatsLeftCount(), 0)
# ---------------------------------------------------------
def testPokerGameGetPlayer(self):
"""Test Poker Game: Get player"""
self.failUnlessEqual(self.game.serialsAll(), [])
self.failUnlessEqual(self.game.playersAll(), [])
self.failUnlessEqual(self.game.allCount(), 0)
self.failUnless(self.game.addPlayer(1))
player = self.GetPlayer(1)
self.failUnlessEqual(self.game.getPlayer(2), None)
self.failUnlessEqual(self.game.serialsAll(), [1])
self.failUnlessEqual(self.game.playersAll(), [player])
self.failUnlessEqual(self.game.allCount(), 1)
# ---------------------------------------------------------
def testPokerGameSeats(self):
"""Test Poker Game: Seats"""
seats = self.game.seats()
for seat in seats:
self.failUnlessEqual(seats[seat], 0)
self.failIf(self.game.addPlayer(1, 2) == None)
self.failIf(self.game.addPlayer(2, 7) == None)
seats = self.game.seats()
self.failUnlessEqual(seats[2], 1)
self.failUnlessEqual(seats[7], 2)
def testPokerGameSeatsAreDeterministic(self):
game = self.game
game.variant = 'holdem'
game.setMaxPlayers(3)
self.assertEqual(game.seats_all, [2,7,5])
self.assertEqual(game.seats_left, [2,7,5])
self.AddPlayerAndSit(1, 2)
self.AddPlayerAndSit(2, 5)
self.assertEqual(game.seats_left, [7])
game.removePlayer(2)
self.assertEqual(game.seats_left, [7,5])
player3 = self.AddPlayerAndSit(3)
self.assertEqual(player3.seat, 7)
# ---------------------------------------------------------
def testPokerGamePlayerCanComeBack(self):
"""Test Poker Game: Player can come back"""
# Unknown player
self.failIf(self.game.canComeBack(1))
self.failIf(self.game.comeBack(1))
# Add a new player
player1 = self.AddPlayerAndSit(1, 2)
# Initially the player are connected and not auto
self.failIf(self.game.canComeBack(1))
self.failIf(self.game.comeBack(1))
# Player disconnected
player1.remove_next_turn = True
self.failUnlessEqual(self.game.serialsDisconnected(), [1])
# The player can now come back
self.failUnless(self.game.canComeBack(1))
self.failUnless(self.game.comeBack(1))
# The player is now in the game
self.failIf(self.game.canComeBack(1))
self.failIf(player1.remove_next_turn)
self.failIf(player1.sit_out_next_turn)
self.failIf(player1.sit_requested)
self.failIf(player1.auto)
# The player is an automatic player
player1.auto = True
self.failUnless(player1.isAuto())
# The player now can come back
self.failUnless(self.game.canComeBack(1))
self.failUnless(self.game.comeBack(1))
# The player is now in the game
self.failIf(self.game.canComeBack(1))
self.failIf(player1.remove_next_turn)
self.failIf(player1.sit_out_next_turn)
self.failIf(player1.sit_requested)
self.failIf(player1.auto)
# ---------------------------------------------------------
def testPokerGameSitPlayer(self):
"""Test Poker Game: Player sit"""
self.failUnlessEqual(self.game.sitCount(), 0)
self.failUnlessEqual(self.game.serialsSit(), [])
self.failUnlessEqual(self.game.playersSit(), [])
self.failUnlessEqual(self.game.sitOutCount(), 0)
self.failUnlessEqual(self.game.serialsSitOut(), [])
self.failUnlessEqual(self.game.playersSitOut(), [])
self.failIf(self.game.addPlayer(1) == None)
player = self.GetPlayer(1)
self.failUnlessEqual(self.game.sitCount(), 0)
self.failUnlessEqual(self.game.serialsSit(), [])
self.failUnlessEqual(self.game.playersSit(), [])
self.failUnlessEqual(self.game.sitOutCount(), 1)
self.failUnlessEqual(self.game.serialsSitOut(), [1])
self.failUnlessEqual(self.game.playersSitOut(), [player])
player.sit_out = False
self.failUnlessEqual(self.game.sitCount(), 1)
self.failUnlessEqual(self.game.serialsSit(), [1])
self.failUnlessEqual(self.game.playersSit(), [player])
self.failUnlessEqual(self.game.sitOutCount(), 0)
self.failUnlessEqual(self.game.serialsSitOut(), [])
self.failUnlessEqual(self.game.playersSitOut(), [])
# ---------------------------------------------------------
def testPokerGameCallback(self):
"""Test Poker Game: Callback"""
# No callback registered
InitCallback()
self.game.runCallbacks('Args1', 'Args2')
self.failUnlessEqual(len(self.game.callbacks), 0)
self.failUnlessEqual(CallbackIds, None)
self.failUnlessEqual(CallbackArgs, None)
# Register a callback
InitCallback()
self.game.registerCallback(Callback)
self.game.runCallbacks('Args1', 'Args2')
self.failUnlessEqual(len(self.game.callbacks), 1)
self.failUnlessEqual(CallbackIds, [self.game.id])
self.failUnlessEqual(CallbackArgs, [('Args1', 'Args2')])
# Unregister the previous callback
InitCallback()
self.game.unregisterCallback(Callback)
self.game.runCallbacks('Args1', 'Args2')
self.failUnlessEqual(len(self.game.callbacks), 0)
self.failUnlessEqual(CallbackIds, None)
self.failUnlessEqual(CallbackArgs, None)
# ---------------------------------------------------------
def testPokerGameBettingStructure(self):
"""Test Poker Game: Initialisation of the betting structure"""
self.failUnlessEqual(self.game.getBettingStructureName(), 'Bet Description')
self.failUnlessEqual(self.game.buyIn(), 50)
self.failUnlessEqual(self.game.maxBuyIn(), 10000)
self.failUnlessEqual(self.game.bestBuyIn(), 1600)
self.failUnlessEqual(self.game.getChipUnit(), 300)
bet_properties = {
'buy-in': '100',
'max-buy-in': '20000',
'best-buy-in': '1000',
'unit': '600'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', None, bet_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnlessEqual(self.game.buyIn(), 100)
self.failUnlessEqual(self.game.maxBuyIn(), 20000)
self.failUnlessEqual(self.game.bestBuyIn(), 1000)
self.failUnlessEqual(self.game.getChipUnit(), 600)
rounds_properties = [
{ 'name': 'pre-flop', 'cap': 3 },
{ 'name': 'flop', 'cap': sys.maxint },
{ 'name': 'turn', 'cap': sys.maxint },
{ 'name': 'river', 'cap': 3 }
]
self.failUnlessEqual(len(self.game.bet_info), len(rounds_properties))
self.game.current_round = 0
for round_properties in rounds_properties:
for prop, value in round_properties.items():
self.failUnlessEqual(self.game.betInfo()[prop], value)
self.game.current_round += 1
# ---------------------------------------------------------
def testPokerGameBlindBettingStructure(self):
"""Test Poker Game: Initialisation of the blind betting structure"""
self.failUnlessEqual(self.game.smallBlind(), 500)
self.failUnlessEqual(self.game.bigBlind(), 1000)
# Change the blind properties
blind_properties = { 'small': '1000', 'big': '2000' }
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnlessEqual(self.game.smallBlind(), 1000)
self.failUnlessEqual(self.game.bigBlind(), 2000)
# Change the blind properties
blind_properties = {
'change': 'double',
'frequency': '15',
'unit': 'minute',
'small': '2000',
'big': '4000'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnlessEqual(self.game.blind_info['small'], 2000)
self.failUnlessEqual(self.game.blind_info['small_reference'], 2000)
self.failUnlessEqual(self.game.blind_info['big'], 4000)
self.failUnlessEqual(self.game.blind_info['big_reference'], 4000)
# Change the blind properties
blind_properties = { 'change': 'levels', 'levels': PokerGameTestCase.TestLevelsTemplateFile }
levels_info = [
{ 'small': 1000, 'big': 1500, 'value': 100, 'bring-in': 150 },
{ 'small': 1500, 'big': 3000, 'value': 150, 'bring-in': 300 },
{ 'small': 2500, 'big': 5000, 'value': 250, 'bring-in': 500 }
]
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnlessEqual(self.game.blind_info["levels"], levels_info)
# ---------------------------------------------------------
def testPokerGameAnteBettingStructure(self):
"""Test Poker Game: Initialisation of the ante betting structure"""
# Change the ante properties
ante_properties = { 'value': '200', 'bring-in': '1000' }
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', 'ante', ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnlessEqual(self.game.ante_info["value"], 200)
self.failUnlessEqual(self.game.ante_info["bring-in"] , 1000)
# Change the ante properties
ante_properties = {
'change': 'double',
'frequency': '15',
'unit': 'minute',
'value': '50',
'bring-in': '200'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/ante', None, ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnlessEqual(self.game.ante_info['value'], 50)
self.failUnlessEqual(self.game.ante_info['value_reference'], 50)
self.failUnlessEqual(self.game.ante_info['bring-in'], 200)
self.failUnlessEqual(self.game.ante_info['bring-in_reference'], 200)
# Change the ante properties
ante_properties = { 'change': 'levels', 'levels': PokerGameTestCase.TestLevelsTemplateFile }
levels_info = [
{ 'small': 1000, 'big': 1500, 'value': 100, 'bring-in': 150 },
{ 'small': 1500, 'big': 3000, 'value': 150, 'bring-in': 300 },
{ 'small': 2500, 'big': 5000, 'value': 250, 'bring-in': 500 }
]
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/ante', None, ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnlessEqual(self.game.ante_info["levels"], levels_info)
# ---------------------------------------------------------
def testPokerGameGetLevelValues(self):
"""Test Poker Game: Get level values"""
# Change the blind properties
blind_properties = {
'change': 'double',
'frequency': '15',
'unit': 'minute',
'small': '2000',
'big': '4000'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Change the ante properties
ante_properties = {
'change': 'double',
'frequency': '15',
'unit': 'minute',
'value': '50',
'bring-in': '200'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', 'ante', ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Change double, check the blind and ante infos
for level in range(3):
blind_info, ante_info = self.game.getLevelValues(level)
self.failUnlessEqual(blind_info['small'], 2000 * pow(2, level - 1))
self.failUnlessEqual(blind_info['big'], 4000 * pow(2, level - 1))
self.failUnlessEqual(ante_info['value'], 50 * pow(2, level - 1))
self.failUnlessEqual(ante_info['bring-in'], 200 * pow(2, level - 1))
# Change the blind properties
blind_properties = { 'change': 'levels',
'levels': PokerGameTestCase.TestLevelsTemplateFile
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Change the ante properties
ante_properties = { 'change': 'levels', 'levels': PokerGameTestCase.TestLevelsTemplateFile }
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/ante', None, ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Change levels, check the blind and ante infos
levels_info = [
{ 'small': 1000, 'big': 1500, 'value': 100, 'bring-in': 150 },
{ 'small': 1500, 'big': 3000, 'value': 150, 'bring-in': 300 },
{ 'small': 2500, 'big': 5000, 'value': 250, 'bring-in': 500 }
]
for level in range(3):
blind_info, ante_info = self.game.getLevelValues(level + 1)
self.failUnlessEqual(blind_info['small'], levels_info[level]['small'])
self.failUnlessEqual(blind_info['big'], levels_info[level]['big'])
self.failUnlessEqual(ante_info['value'], levels_info[level]['value'])
self.failUnlessEqual(ante_info['bring-in'], levels_info[level]['bring-in'])
# Change the blind properties
blind_properties = { 'change': 'invalid' }
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Change the ante properties
ante_properties = { 'change': 'invalid' }
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/ante', None, ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Change invalid, check the blind and ante infos
blind_info, ante_info = self.game.getLevelValues(0)
self.failUnlessEqual(blind_info, None)
self.failUnlessEqual(blind_info, ante_info)
# ---------------------------------------------------------
def testPokerGameSetLevelValues(self):
"""Test Poker Game: Set level values"""
# Change the blind properties
blind_properties = {
'change': 'levels',
'frequency': '15',
'unit': 'minute',
'levels': PokerGameTestCase.TestLevelsTemplateFile
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Change the ante properties
ante_properties = {
'change': 'levels',
'frequency': '15',
'unit': 'minute',
'levels': PokerGameTestCase.TestLevelsTemplateFile
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', 'ante', ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Change the level and check the blind and ante infos
levels_info = [
{ 'small': 1000, 'big': 1500, 'value': 100, 'bring-in': 150 },
{ 'small': 1500, 'big': 3000, 'value': 150, 'bring-in': 300 },
{ 'small': 2500, 'big': 5000, 'value': 250, 'bring-in': 500 }
]
# Change the level and check
for level in range(3):
blind_info, ante_info = self.game.getLevelValues(level + 1)
self.game.setLevel(level + 1)
self.failUnlessEqual(self.game.getLevel(), level + 1)
self.failUnlessEqual(self.game.blind_info['small'], blind_info['small'])
self.failUnlessEqual(self.game.blind_info['big'], blind_info['big'])
self.failUnlessEqual(self.game.ante_info['value'], ante_info['value'])
self.failUnlessEqual(self.game.ante_info['bring-in'], ante_info['bring-in'])
self.failUnlessEqual(self.game.blind_info['hands'], self.game.hands_count)
self.failUnlessEqual(self.game.blind_info['time'], self.game.time)
self.failUnlessEqual(self.game.ante_info['hands'], self.game.hands_count)
self.failUnlessEqual(self.game.ante_info['time'], self.game.time)
# ---------------------------------------------------------
def testPokerGameSetVariantInvalid(self):
"""Test Poker Game: Variant with invalid specifications"""
if not self.CopyFile(self.VariantInvalidFile, self.VariantTempFile):
self.fail('Error during creation of variant file ' + self.VariantInvalidFile)
self.failUnlessRaises(UserWarning, self.game.setVariant,PokerGameTestCase.TestVariantTemporaryFile)
# ---------------------------------------------------------
def testPokerGameSetVariantWinnerOrder(self):
"""Test Poker Game: Set variant winner order"""
# The winner order is set to high in the self.VariantTmplFile file
self.failIf(self.game.isLow())
self.failIf(self.game.hasLow())
self.failUnless(self.game.isHigh())
self.failUnless(self.game.hasHigh())
self.failIf(self.game.isHighLow())
# Change the winner order to low
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant/wins/winner', None, {'order': 'low8'}):
self.fail('Error during modification of variant file ' + self.VariantTempFile)
self.game.setVariant(PokerGameTestCase.TestVariantTemporaryFile)
# The winner order is now low
self.failUnless(self.game.isLow())
self.failUnless(self.game.hasLow())
self.failIf(self.game.isHigh())
self.failIf(self.game.hasHigh())
self.failIf(self.game.isHighLow())
# Invalid winner order
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant/wins/winner', None, {'order': 'invalid'}):
self.fail('Error during modification of variant file ' + self.VariantTempFile)
# An exception is raised if the order is not low8 or hi
self.failUnlessRaises(UserWarning,self.game.setVariant, PokerGameTestCase.TestVariantTemporaryFile)
# ---------------------------------------------------------
def testPokerGameSetVariantRoundInfos(self):
"""Test Poker Game: Set variant round infos"""
# 2 rounds in the template file
self.failUnlessEqual(len(self.game.round_info),4)
self.failUnlessEqual(len(self.game.round_info_backup),4)
for round in range(len(self.game.round_info)):
self.failUnlessEqual(self.game.round_info[round],self.game.round_info_backup[round])
round1_info = {
'name': 'pre-flop',
'position': 'under-the-gun',
'board': [],
'board_size': 0,
'hand_size': 2,
'cards': ['down', 'down']
}
round2_info = {
'name': 'flop',
'position': 'next-to-dealer',
'board': ['', '', ''],
'board_size': 3,
'hand_size': 2,
'cards': []
}
self.failUnlessEqual(self.game.round_info[0], round1_info)
self.failUnlessEqual(self.game.round_info[1], round2_info)
self.failUnlessEqual(self.game.round_info[0],self.game.round_info_backup[0])
self.failUnlessEqual(self.game.round_info[1],self.game.round_info_backup[1])
# ---------------------------------------------------------
def testPokerGameResetRoundInfos(self):
"""Test Poker Game: Reset round infos"""
round1_info = {
'name': 'pre-flop',
'position': 'under-the-gun',
'board': [],
'board_size': 0,
'hand_size': 2,
'cards': ['down', 'down']
}
# The round info are loaded from the VariantTmplFile file
self.failUnlessEqual(self.game.round_info[0], round1_info)
# Change all the round infos
self.game.round_info[0]['name'] = 'ModifiedRound'
self.game.round_info[0]['position'] = 'ModifiedPosition'
self.game.round_info[0]['board'] = ['ModifiedBoard']
self.game.round_info[0]['board_size'] = 'ModifiedBoardSize'
self.game.round_info[0]['hand_size'] = 'ModifiedHandSize'
self.game.round_info[0]['cards'] = ['up']
# Restore the round backup
self.failIfEqual(self.game.round_info[0], round1_info)
self.game.resetRoundInfo()
self.failUnlessEqual(self.game.round_info[0], round1_info)
# ---------------------------------------------------------
def testPokerGameLoadTournamentLevels(self):
"""Test Poker Game: Load tournament levels"""
# The levels are loaded from the LevelsTmplFile file
levels_info = [
{ 'small': 1000, 'big': 1500, 'value': 100, 'bring-in': 150 },
{ 'small': 1500, 'big': 3000, 'value': 150, 'bring-in': 300 },
{ 'small': 2500, 'big': 5000, 'value': 250, 'bring-in': 500 }
]
levels = self.game.loadTournamentLevels(self.TestLevelsTemplateFile)
self.failUnlessEqual(levels, levels_info)
# ---------------------------------------------------------
def testPokerGamePayBuyIn(self):
"""Test Poker Game: Pay buy in"""
self.failIf(self.game.addPlayer(1) == None)
player = self.GetPlayer(1)
# Get the buy in values
self.failUnlessEqual(self.game.buyIn(), 50)
self.failUnlessEqual(self.game.maxBuyIn(), 10000)
self.failUnlessEqual(self.game.bestBuyIn(), 1600)
# Can not pay more then the max buy in
self.failIf(self.game.payBuyIn(1,20000))
self.failIf(player.isBuyInPayed())
# Can not pay less than the min buy in
self.failIf(self.game.payBuyIn(1,40))
self.failIf(player.isBuyInPayed())
# Pay the buy in
self.failUnless(self.game.payBuyIn(1,100))
self.failUnless(player.isBuyInPayed())
self.failUnlessEqual(self.game.getPlayerMoney(1), 100)
# The game in now a tournament, there is no maximum limit
# Change the blind properties
blind_properties = {
'change': 'double',
'frequency': '15',
'unit': 'minute',
'small': '2000',
'big': '4000'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# The player can pay more than the max buy in
self.failUnless(self.game.payBuyIn(1,20000))
self.failUnless(player.isBuyInPayed())
self.failUnlessEqual(self.game.getPlayerMoney(1), 20000)
# ---------------------------------------------------------
def testPokerGameSitRequested(self):
"""Test Poker Game: Sit requested"""
self.failIf(self.game.addPlayer(1) == None)
self.game.sitRequested(1)
player = self.GetPlayer(1)
self.failUnlessEqual(player.isSitRequested(), True)
self.failUnlessEqual(player.isWaitForBlind(), False)
self.failUnlessEqual(player.sit_out_next_turn, False)
# ---------------------------------------------------------
def testPokerGameSit(self):
"""Test Poker Game: Sit"""
self.failIf(self.game.addPlayer(1) == None)
player = self.GetPlayer(1)
# Can not sit because of missing buyin
self.failUnlessEqual(self.game.sit(1), False)
# Can sit after buyin
self.failUnlessEqual(self.game.payBuyIn(1,self.game.bestBuyIn()), True)
self.failUnlessEqual(player.isBuyInPayed(), True)
self.failUnlessEqual(self.game.sit(1), True)
# Can not sit, again, after being already seated
self.failUnlessEqual(self.game.sit(1), False)
# Can sit in if sit_out_next_turn
self.game.isInTurn = lambda serial: True
self.game.sitOutNextTurn(1)
self.failUnlessEqual(self.game.sit(1), True)
# Can sit in if autoPlayer
self.game.autoPlayer(1)
self.failUnlessEqual(self.game.sit(1), True)
# ---------------------------------------------------------
def testPokerGameBuildPlayerList(self):
"""Test Poker Game: Build player list"""
player1 = self.AddPlayerAndSit(1, 7)
self.failUnless(self.game.addPlayer(2, 2))
self.failUnless(self.game.payBuyIn(2,self.game.bestBuyIn()))
# Can not construct the player list because there is only one player sit
self.failIf(self.game.buildPlayerList(False))
# The player 2 is now sit
self.failUnlessEqual(self.game.sit(2), True)
# The construction of the player list is now possible
self.failUnless(self.game.buildPlayerList(False))
# The players are ordered by his seat
self.failUnlessEqual(self.game.player_list, [2, 1])
# The player 1 is waiting for blind and first round
player1.wait_for = 'first_round'
self.failUnless(player1.isWaitForBlind())
self.failUnless(self.game.buildPlayerList(False))
self.failUnlessEqual(self.game.player_list, [2])
self.failUnless(self.game.buildPlayerList(True))
self.failUnlessEqual(self.game.player_list, [2])
# The player 1 is only waiting for blind
player1.wait_for = 'big'
self.failUnless(player1.isWaitForBlind())
self.failUnless(self.game.buildPlayerList(False))
self.failUnlessEqual(self.game.player_list, [2])
self.failUnless(self.game.buildPlayerList(True))
self.failUnlessEqual(self.game.player_list, [2, 1])
# ---------------------------------------------------------
def testMoveDealerLeft(self):
"""Test Poker Game: Move dealer left"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# The construction of the player list
self.failUnless(self.game.buildPlayerList(False))
self.failUnlessEqual(self.game.player_list, [1, 2])
# The dealer is the player 1
self.failUnlessEqual(self.game.dealer_seat, 2)
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getPlayerDealer(), player1)
# Move the dealer
self.game.moveDealerLeft()
# The player 2 is now the dealer
self.failUnlessEqual(self.game.dealer_seat, 7)
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getPlayerDealer(), player2)
# Re init the game players
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# The construction of the player list
self.failUnless(self.game.buildPlayerList(False))
self.failUnlessEqual(self.game.player_list, [1, 2, 3])
# The dealer is the player 1
self.failUnlessEqual(self.game.dealer_seat, 2)
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getPlayerDealer(), player1)
# Move the dealer
player2.missed_blind = None
self.game.moveDealerLeft()
# The player 2 is now the dealer
self.failUnlessEqual(self.game.dealer_seat, 5)
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getPlayerDealer(), player2)
# No blind info, nothing done
self.game.blind_info = None
player1.missed_blind = None
self.game.moveDealerLeft()
# The player 2 is still the dealer
self.failUnlessEqual(self.game.dealer_seat, 5)
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getPlayerDealer(), player2)
# ---------------------------------------------------------
def testDealerFromDealerSeat(self):
"""Test Poker Game: Dealer from dealer seat"""
self.game.setMaxPlayers(3)
self.failUnlessEqual(self.game.dealer, -1)
self.failUnlessEqual(self.game.dealer_seat, -1)
self.game.dealerFromDealerSeat()
# The dealer and his seat are not initialised
self.failUnlessEqual(self.game.dealer, -1)
self.failUnlessEqual(self.game.dealer_seat, -1)
# Create player 1
player1 = self.AddPlayerAndSit(1, 2)
self.failUnlessEqual(self.game.dealer_seat, 2)
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.dealer, -1)
# Create player 2
player2 = self.AddPlayerAndSit(2, 5)
self.failUnlessEqual(self.game.dealer_seat, 2)
# Construct the player list
self.failUnlessEqual(self.game.buildPlayerList(False), True)
self.failUnlessEqual(self.game.player_list, [1, 2])
# The dealer is the player 1
self.failUnlessEqual(self.game.dealer_seat, 2)
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getSerialDealer(), 1)
self.failUnlessEqual(self.game.getPlayerDealer(), player1)
# Change the dealer seat
self.game.dealer_seat = 5
# The dealer is now the player 2
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getSerialDealer(), 2)
self.failUnlessEqual(self.game.getPlayerDealer(), player2)
# Add a player but do not reconstruct the player list
player3 = self.AddPlayerAndSit(3)
# Change the dealer seat
self.game.dealer_seat = 7
# The dealder is still the player 2
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getSerialDealer(), 2)
self.failUnlessEqual(self.game.getPlayerDealer(), player2)
# ---------------------------------------------------------
def testSetDealer(self):
"""Test Poker Game: Set dealer"""
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Construct the player list
self.failUnless(self.game.buildPlayerList(False))
# The game is not running
self.failIf(self.game.isRunning())
# The dealer can be set because the game is not running
self.game.setDealer(7)
# The dealer is the player 2
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getSerialDealer(), 2)
# The dealer can be set because the game is not running
self.game.setDealer(2)
# The dealer is the player 1
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getSerialDealer(), 1)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The game is now running
self.failUnless(self.game.isRunning())
self.failUnlessEqual(self.game.getSerialDealer(), 1)
# The set dealer function has no effect
self.game.setDealer(7)
# The dealer is still the player 1
self.game.dealerFromDealerSeat()
self.failUnlessEqual(self.game.getSerialDealer(), 1)
# ---------------------------------------------------------
def testPokerGameMoney2Bet(self):
"""Test Poker Game: Money to bet"""
self.game.registerCallback(Callback)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Initial player money and bet
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1600)
# Transfert from money to bet
InitCallback()
self.game.money2bet(1, 500)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1100)
self.failUnlessEqual(player1.bet, 500)
self.failUnlessEqual(player1.isAllIn(), False)
# Check the callback
self.failUnlessEqual(CallbackIds, [self.game.id])
self.failUnlessEqual(CallbackArgs, [('money2bet', 1, 500)])
# Initial player money and bet
InitCallback()
self.failUnlessEqual(player2.bet, 0)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1600)
# Transfert from money to bet
self.game.money2bet(2, 2000)
self.failUnlessEqual(self.game.getPlayerMoney(2), 0)
self.failUnlessEqual(player2.bet, 1600)
self.failUnlessEqual(player2.isAllIn(), True)
# Check the callback
self.failUnlessEqual(CallbackIds, [self.game.id, self.game.id])
self.failUnlessEqual(CallbackArgs, [('money2bet', 2, 1600), ('all-in', 2)])
# ---------------------------------------------------------
def testNotFoldCount(self):
"""Test Poker Game: Not fold count"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(self.game.notFoldCount(), 2)
self.failUnlessEqual(self.game.serialsNotFold(), [1, 2])
self.failUnlessEqual(self.game.playersNotFold(), [player1, player2])
player1.fold = True
self.failUnlessEqual(self.game.notFoldCount(), 1)
self.failUnlessEqual(self.game.serialsNotFold(), [2])
self.failUnlessEqual(self.game.playersNotFold(), [player2])
# ---------------------------------------------------------
def testPot2Money(self):
"""Test Poker Game: Pot to money"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(self.game.getPlayerMoney(1), self.game.bestBuyIn())
self.game.pot = 500
self.game.pot2money(1)
self.failUnlessEqual(self.game.getPlayerMoney(1), self.game.bestBuyIn() + 500)
self.failUnlessEqual(self.game.pot, 0)
# ---------------------------------------------------------
def testGetPotAmount(self):
"""Test Poker Game: getPotAmount"""
# Create players
player1 = self.AddPlayerAndSit(1)
player2 = self.AddPlayerAndSit(2)
self.game.beginTurn(1)
self.failUnlessEqual(0 ,self.game.getPotAmount())
self.game.state = pokergame.GAME_STATE_END
self.failUnlessEqual(0 ,self.game.getPotAmount())
# ---------------------------------------------------------
def testCancelState(self):
"""Test Poker Game: Cancel state"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
attribs = {
'current_round': -2,
'position': -1,
'state': 'end'
}
self.game.position = -1
self.game.cancelState()
for key, value in attribs.items():
self.failUnlessEqual(getattr(self.game,key), value)
self.game.position = 0
self.game.turn_history = []
self.game.cancelState()
self.failUnlessEqual(self.game.turn_history, [('position', -1, None)] )
# ---------------------------------------------------------
def testHighestBet(self):
"""Test Poker Game: Highest bet"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(player2.bet, 0)
player1.bet = 500
self.failUnlessEqual(self.game.highestBetNotFold(), 500)
self.failUnlessEqual(self.game.highestBetInGame(), 500)
player2.bet = 1000
self.failUnlessEqual(self.game.highestBetNotFold(), 1000)
self.failUnlessEqual(self.game.highestBetInGame(), 1000)
player2.fold = True
self.failUnlessEqual(self.game.highestBetNotFold(), 500)
self.failUnlessEqual(self.game.highestBetInGame(), 500)
player2.fold = False
player2.all_in = True
self.failUnlessEqual(self.game.highestBetNotFold(), 1000)
self.failUnlessEqual(self.game.highestBetInGame(), 500)
# ---------------------------------------------------------
def testBetsEqual(self):
"""Test Poker Game: Bets equal"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(player2.bet, 0)
player1.bet = 500
self.failUnlessEqual(self.game.betsEqual(), False)
player2.bet = 500
self.failUnlessEqual(self.game.betsEqual(), True)
player2.bet = 1000
player2.all_in = True
self.failUnlessEqual(self.game.betsEqual(), False)
player2.fold = True
self.failUnlessEqual(self.game.betsEqual(), True)
player2.fold = False
player1.all_in = True
self.failUnlessEqual(self.game.betsEqual(), True)
# ---------------------------------------------------------
def testCanCall(self):
"""Test Poker Game: Can call"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failIf(self.game.canCall(1))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
player1.bet = 1000
self.failUnless(self.game.canCall(2))
player2.bet = 1500
self.failIf(self.game.canCall(2))
# ---------------------------------------------------------
def testCall(self):
"""Test Poker Game: Call"""
self.game.setMaxPlayers(3)
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failIf(self.game.call(1))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
self.failIf(self.game.canAct(1))
self.failIf(self.game.call(1))
# Deal cards
self.game.dealCards()
self.failUnless(self.game.callNraise(1, 100))
self.failUnless(self.game.canAct(2))
self.failIf(player2.talked_once)
self.failUnless(self.game.call(2))
self.failUnlessEqual(player2.bet, 100)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1500)
self.failUnless(player2.talked_once)
self.failUnless(self.game.canAct(3))
# ---------------------------------------------------------
def testCanCheck(self):
"""Test Poker Game: Can check"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failIf(self.game.canCheck(1))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
player1.bet = 1000
player2.bet = 500
self.failIf(self.game.canCheck(2))
player2.bet = 1000
self.failUnless(self.game.canCheck(2))
player2.bet = 1500
self.failUnless(self.game.canCheck(2))
# ---------------------------------------------------------
def testCheck(self):
"""Test Poker Game: Check"""
# Create Players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Check is not available during blind and ante round
self.failIf(self.game.check(1))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Deal cards
self.game.dealCards()
# Player 1 can now raise
self.failUnless(self.game.canAct(1))
self.failUnless(self.game.callNraise(1, 100))
# Player 2 bet is less than the highest bet
self.failUnless(self.game.canAct(2))
self.failIf(self.game.canCheck(2))
self.failIf(self.game.check(2))
# Player 2 can now check
player2.bet = 100
self.failUnless(self.game.canCheck(2))
self.failIf(player2.talked_once)
# Player 2 check
self.failUnless(self.game.check(2))
# Second round
self.failUnless(self.game.isSecondRound())
# ---------------------------------------------------------
def testCanFold(self):
"""Test Poker Game: Can fold"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player can not fold
self.failIf(self.game.canFold(1))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# The player can now fold
self.failUnless(self.game.canFold(1))
# The player 2 is not in game so he can not fold
player2.all_in = True
self.failIf(self.game.isInGame(2))
self.failIf(self.game.canFold(2))
# ---------------------------------------------------------
def testFold(self):
"""Test Poker Game: Fold"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Player can not fold
self.failIf(self.game.fold(1))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Player 1 not in position
self.failIf(self.game.canAct(1))
self.failIf(self.game.fold(1))
# Deal cards
self.game.dealCards()
# Player 1 raise
self.failUnless(self.game.callNraise(1, 100))
# Player 2 already fold, the fold function has no effect
player2.fold = True
self.failUnless(self.game.canAct(2))
self.failUnless(self.game.fold(2))
self.failUnless(self.game.canAct(2))
# Player 2 fold
player2.fold = False
player2.bet = 300
self.failIf(player2.isFold())
self.failUnless(self.game.canAct(2))
self.failUnless(self.game.fold(2))
self.failUnless(player2.isFold())
self.failUnlessEqual(player2.bet, 0)
self.failUnlessEqual(self.game.pot, 300)
# Player 3 can act
self.failUnless(self.game.canAct(3))
# ---------------------------------------------------------
def testCanRaise(self):
"""Test Poker Game: Can raise"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failIf(self.game.canRaise(1))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# The player can now raise
self.failUnless(self.game.canRaise(1))
self.game.round_cap_left = 0
self.failIf(self.game.canRaise(1))
self.game.round_cap_left = sys.maxint
player1.bet = 1000
player1.money = 600
self.failUnless(self.game.canRaise(2))
player1.talked_once = False
self.failUnless(self.game.canRaise(1))
player1.talked_once = True
self.failIf(self.game.canRaise(1))
player1.bet = player2.money + 1000
self.failIf(self.game.canRaise(2))
player2.bet = 1600
player2.money = 0
self.failIf(self.game.canRaise(2))
# ---------------------------------------------------------
def testCallNRaise(self):
"""Test Poker Game: Call N raise"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3 ,7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failIf(self.game.canAct(1))
self.failIf(self.game.callNraise(1, 100))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# The card are not dealt so the players can not act
self.failIf(self.game.canAct(1))
self.failIf(self.game.callNraise(1, 100))
# Deal cards
self.game.dealCards()
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/variants/round', None, {'min': '100', 'max': '300'}):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnlessEqual(self.game.betLimitsForSerial(1), (100, 300, 100))
self.failUnless(self.game.callNraise(1, 50))
self.failUnlessEqual(player1.bet, 100)
self.failUnlessEqual(self.game.betLimitsForSerial(2), (200, 400, 100))
self.failUnless(self.game.canAct(2))
self.failUnless(self.game.callNraise(2, 500))
self.failUnlessEqual(player2.bet, 400)
self.failUnless(self.game.canAct(3))
self.game.round_cap_left = 0
self.failIf(self.game.callNraise(3, 100))
self.game.round_cap_left = -1
self.failIf(self.game.callNraise(3, 100))
# ---------------------------------------------------------
def testCanAct(self):
"""Test Poker Game: Can act"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# It the blind and ante turn so the player can act
self.failUnless(self.game.canAct(1))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Can not act because the cards are not dealt
self.failIf(self.game.cardsDealt())
self.failIf(self.game.canAct(1))
# Deal cards
self.game.dealCards()
# The cards are now dealt so the player 1 can act
self.failUnless(self.game.cardsDealt())
self.failUnless(self.game.canAct(1))
# The player 2 can not act because it is not its turn
self.failIfEqual(self.game.getSerialInPosition(), 2)
self.failIf(self.game.canAct(2))
self.game.callNraise(1, 1000)
# The player 2 can now play
self.failUnlessEqual(self.game.getSerialInPosition(), 2)
#self.game.setPosition(1)
self.failUnless(self.game.canAct(2))
# ---------------------------------------------------------
def testWillAct(self):
"""Test Poker Game: Will act"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# The game is not running
self.failIf(self.game.isRunning())
self.failIf(self.game.willAct(1))
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Deal cards
self.game.dealCards()
self.failUnless(self.game.isRunning())
# The player 1 can not call
self.failIf(self.game.canCall(1))
self.failUnless(self.game.willAct(1))
# The player 1 raise
self.game.callNraise(1, 100)
# The player 2 can call and will act
self.failUnless(self.game.canCall(2))
self.failIf(player2.talked_once)
self.failUnless(self.game.willAct(2))
# The player 2 call
self.game.callNraise(2, 200)
# The player 2 has talked so he won't act
self.failUnless(player2.talked_once)
self.failIf(self.game.willAct(2))
# ---------------------------------------------------------
def testPossibleActions(self):
"""Test Poker Game: Possible actions"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# It is the blind and ante turn so there is no possible action
self.failUnless(self.game.canAct(1))
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(self.game.possibleActions(1), [])
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Deal cards
self.game.dealCards()
# The player 1 can raise or check
self.failUnless(self.game.canAct(1))
self.failUnlessEqual(self.game.possibleActions(1), ['raise', 'check'])
# The player 2 can not do anything because it is not its turn
self.failUnlessEqual(self.game.possibleActions(2), [])
# The player 1 raise 1000
self.game.callNraise(1, 1000)
# The player 2 can now call, raise or fold
self.failUnlessEqual(self.game.possibleActions(2), ['call', 'raise', 'fold'])
# The player 2 can not raise because he has not enough money
player1.bet = 1800
self.failUnlessEqual(self.game.possibleActions(2), ['call', 'fold'])
# ---------------------------------------------------------
def testBetsNull(self):
"""Test Poker Game: Bets null"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Game is not running
self.failIf(self.game.betsNull())
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Game is running
self.failUnless(self.game.betsNull())
# The player 1 has bet
player1.bet = 1000
self.failIf(self.game.betsNull())
# Th eplayer 1 is fold
player1.fold =True
self.failUnless(self.game.betsNull())
# ---------------------------------------------------------
def testRoundCap(self):
"""Test Poker Game: Round cap"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Round cap is 0 because the game is not running
self.failIf(self.game.isRunning())
self.failUnlessEqual(self.game.roundCap(), 0)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# The game is running
self.failUnless(self.game.isRunning())
# First round cap initially equal to 3
self.failUnlessEqual(self.game.roundCap(), 3)
# Change the cap of the first level
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/variants/round[@name="pre-flop"]', None, {'cap': '20'}):
self.fail('Error during modification of variant file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# First round cap equal to 20
self.failUnlessEqual(self.game.roundCap(), 20)
# ---------------------------------------------------------
def testBetLimits(self):
"""Test Poker Game: Bet limits"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# The game is not running
self.failUnlessEqual(self.game.betLimitsForSerial(1), (0,0,0))
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# No limit set in the configuration file
player1.bet = 1000
self.failUnlessEqual(self.game.betLimitsForSerial(2), (1000, 1600 , 1000))
# MIN and MAX limits
# Change the bet infos
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/variants/round', None, {'min': '100', 'max': '300'}):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Check the bet limits
self.failUnlessEqual(self.game.betLimitsForSerial(2), (1100, 1300 , 1000))
# MIN and POT limits
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/variants/round', None, {'min': 'big', 'max': 'pot'}):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Check the bet limts
player1.bet = 400
self.failUnlessEqual(self.game.betLimitsForSerial(2), (1400, 1400, 1000))
# POW LEVEL limits
# Change the bet infos
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/variants/round', None, {'pow_level': '100'}):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Check the bet limits for level 0
self.failUnlessEqual(self.game.getLevel(), 0)
self.failUnlessEqual(self.game.betLimitsForSerial(2), (400 + 100 * math.pow(2,-1), 400 + 100 * math.pow(2,-1), 400))
# FIXED limits
# Change the bet infos
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/variants/round', None, {'fixed': '100'}):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Check the bet limits
self.failUnlessEqual(self.game.betLimitsForSerial(2), (500, 500, 400))
# ROUND CAP LEFT 0
self.game.round_cap_left = 0
# Check the bet limits
self.failUnlessEqual(self.game.betLimitsForSerial(2), (0, 0, 400))
# ---------------------------------------------------------
def testBestHand(self):
"""Test Poker Game: Best hand"""
player1 = self.AddPlayerAndSit(1, 2)
player1.hand = pokercards.PokerCards(['Ad', 'As', 'Ah', '3s'])
self.game.board = pokercards.PokerCards(['9d', '6s', 'Td', '4d', '4h'])
self.failUnless(self.game.isHigh())
self.game.variant = 'holdem'
bestHand = pokercards.PokerCards(['Ad', 'Ah', 'As', '4d', '4h'])
hand = self.game.bestHand('hi', 1)
self.failUnlessEqual(pokercards.PokerCards(hand[1][1:]), bestHand)
self.failUnlessEqual(self.game.readablePlayerBestHand('hi', 1), 'Aces full of Fours: As, Ad, Ah, 4d, 4h')
self.game.variant = 'omaha'
bestHand = pokercards.PokerCards(['Ad', 'Ah', '4d', '4h', 'Td'])
hand = self.game.bestHand('hi', 1)
self.failUnlessEqual(pokercards.PokerCards(hand[1][1:]), bestHand)
self.failUnlessEqual(self.game.readablePlayerBestHand('hi', 1), 'Two pairs Aces and Fours, Ten kicker: Ad, Ah, 4d, 4h, Td')
value, cards = self.game.bestHand('hi', 1)
self.failUnlessEqual(self.game.bestHandValue('hi', 1), value)
self.failUnlessEqual(self.game.bestHandCards('hi', 1), cards)
# ---------------------------------------------------------
def testBestHands(self):
"""Test Poker Game: Best hands"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Players and board cards
player1.hand = pokercards.PokerCards(['Ad', 'As', 'Ah', '3s'])
player2.hand = pokercards.PokerCards(['Jh', '5c', '7d', '2d'])
self.game.board = pokercards.PokerCards(['9d', '6s', 'Td', '4d', '4h'])
# Best hands
bestHand1 = pokercards.PokerCards(['Ad', 'Ah', 'As', '4d', '4h'])
bestHand2 = pokercards.PokerCards(['7d', '2d', '9d', 'Td', '4d'])
self.game.variant = 'holdem'
self.failUnless(self.game.isHigh())
# Check best hands
results = self.game.bestHands([1, 2])
# Player 1 hand
self.failUnless(1 in results)
self.failUnless('hi' in results[1])
self.failUnlessEqual(pokercards.PokerCards(results[1]['hi'][1][1:]), bestHand1)
self.failUnlessEqual(self.game.readablePlayerBestHands(1), 'Aces full of Fours: As, Ad, Ah, 4d, 4h')
# Player 2 hand
self.failUnless(2 in results)
self.failUnless('hi' in results[2])
self.failUnlessEqual(pokercards.PokerCards(results[2]['hi'][1][1:]), bestHand2)
self.failUnlessEqual(self.game.readablePlayerBestHands(2), 'Flush Ten: Td, 9d, 7d, 4d, 2d')
# Then hand with a NOCARD can not be evaluate
player1.hand = pokercards.PokerCards(['Jh', '5c', '7d', pokercards.PokerCards.NOCARD])
results = self.game.bestHands([1])
self.failUnlessEqual(len(results), 0)
# ---------------------------------------------------------
def testBestHandsHoldemFlopStreet(self):
"""Test Poker Game: Best hands, holdem viariant, flop street"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Players and board cards
player1.hand = pokercards.PokerCards(['Ad', 'As'])
player2.hand = pokercards.PokerCards(['Jh', '5c'])
self.game.board = pokercards.PokerCards(['9d', '6s', 'Td'])
self.game.variant = 'holdem'
self.failUnless(self.game.isHigh())
# Player 1 hand
self.failUnlessEqual(self.game.readablePlayerBestHands(1), 'A pair of Aces, Ten kicker: As, Ad, Td, 9d, 6s')
# Player 2 hand
self.failUnlessEqual(self.game.readablePlayerBestHands(2), 'High card Jack: Jh, Td, 9d, 6s, 5c')
# ---------------------------------------------------------
def testReadableHandValue(self):
"""Test Poker Game: Readable hand value"""
self.game.variant = 'holdem'
player1 = self.AddPlayerAndSit(1, 2)
player1.hand = pokercards.PokerCards(['2h', '5s', '6h', '9s', 'Ks'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'High card King')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'High card King')
player1.hand = pokercards.PokerCards(['2h', '2s', '6h', '9s', 'Ks'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'Pair of Deuces')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'A pair of Deuces, King kicker')
player1.hand = pokercards.PokerCards(['3h', '3s', '6h', '6s', 'Ks'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'Pairs of Sixes and Treys')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'Two pairs Sixes and Treys, King kicker')
player1.hand = pokercards.PokerCards(['Th', 'Ts', 'Td', '6s', 'Qs'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'Trips Tens')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'Three of a kind Tens, Queen kicker')
player1.hand = pokercards.PokerCards(['7h', '8s', '9d', 'Ts', 'Js'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'Straight Jack')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'Straight Jack to Seven')
player1.hand = pokercards.PokerCards(['2s', '5s', '6s', '9s', 'Ks'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'Flush King')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'Flush King')
player1.hand = pokercards.PokerCards(['Qh', 'Qs', 'Qc', 'Ts', 'Td'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'Queens full of Tens')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'Queens full of Tens')
player1.hand = pokercards.PokerCards(['6h', '6s', '6d', '6c', 'Qs'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'Quads Sixes, Queen kicker')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'Four of a kind Sixes, Queen kicker')
player1.hand = pokercards.PokerCards(['7h', '8h', '9h', 'Th', 'Jh'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'Straight flush')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'Straight flush Jack')
player1.hand = pokercards.PokerCards(['Ts', 'Js', 'Qs', 'Ks', 'As'])
cards = self.game.bestHandCards('hi', 1)
self.failUnlessEqual(self.game.readableHandValueShort('hi', cards[0], cards[1:]), 'Royal flush')
self.failUnlessEqual(self.game.readableHandValueLong('hi', cards[0], cards[1:]), 'Royal flush')
player1.hand = pokercards.PokerCards(['Ac', '2s', '3h', '4d', '5s'])
cards = self.game.bestHandCards('low', 1)
self.failUnlessEqual(self.game.readableHandValueShort('low', cards[0], cards[1:]), 'The wheel')
self.failUnlessEqual(self.game.readableHandValueLong('low', cards[0], cards[1:]), 'The wheel')
player1.hand = pokercards.PokerCards(['8h', '2s', '3h', '4d', '5s'])
cards = self.game.bestHandCards('low', 1)
self.failUnlessEqual(self.game.readableHandValueShort('low', cards[0], cards[1:]), '8, 5, 4, 3, 2')
self.failUnlessEqual(self.game.readableHandValueLong('low', cards[0], cards[1:]), '8, 5, 4, 3, 2')
# Unknown values
self.failUnlessEqual(self.game.readableHandValueShort('low', 'Unknown', cards[1:]), 'Unknown')
self.failUnlessEqual(self.game.readableHandValueLong('low', 'Unknown', cards[1:]), 'Unknown')
# ---------------------------------------------------------
def testHandEV(self):
"""Test Poker Game: Hand eval"""
self.game.variant = 'holdem'
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
player1.hand = pokercards.PokerCards(['Ad', 'As'])
self.failUnless(self.game.handEV(1, 10000) in range(830,870))
player1.hand = pokercards.PokerCards(['2c', '7s'])
self.failUnless(self.game.handEV(1, 10000) in range(330,370))
self.game.board = pokercards.PokerCards(['2c', '3c', '4s'])
self.failUnless(self.game.handEV(1, 10000) in range(430,470))
player2.hand = pokercards.PokerCards(['4h', '5c'])
self.failUnless(self.game.handEV(1, 10000, True) in range(430,470))
self.failUnless(self.game.handEV(1, 10000) in range(100, 140))
self.failUnless(self.game.handEV(2, 10000, True) in range(690, 730))
self.failUnless(self.game.handEV(2, 10000) in range(860, 900))
self.failUnlessEqual(self.game.handEV(3, 10000), None)
# ---------------------------------------------------------
def testMoneyMap(self):
"""Test Poker Game: Money map"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
player1.money = 1500
player2.money = 600
self.failUnlessEqual(self.game.moneyMap(), { 1: 1500, 2: 600})
player2.fold = True
self.failUnlessEqual(self.game.moneyMap(), { 1: 1500})
# ---------------------------------------------------------
def testHasLevel(self):
"""Test Poker Game: Has level"""
self.failIf(self.game.hasLevel())
# Change the blind properties
blind_properties = {
'change': 'double',
'frequency': '15',
'unit': 'minute',
'small': '2000',
'big': '4000'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnless(self.game.hasLevel())
if not self.CopyFile(self.ConfigTmplFile, self.ConfigTempFile):
self.fail('Error during creation of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failIf(self.game.hasLevel())
# Change the ante properties
ante_properties = {
'change': 'double',
'frequency': '15',
'unit': 'minute',
'value': '50',
'bring-in': '200'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', 'ante', ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnless(self.game.hasLevel())
# ---------------------------------------------------------
def testLevelUp(self):
"""Test Poker Game: Level up"""
# The blind properties
self.failIf(self.game.delayToLevelUp())
# Change the blind properties
blind_properties = {
'change': 'levels',
'levels': PokerGameTestCase.TestLevelsTemplateFile,
'frequency': '3',
'unit': 'minute',
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failUnless(self.game.hasLevel())
# Level 0
self.game.setLevel(0)
self.failUnless(self.game.delayToLevelUp(), (0, 'minute'))
# Level 1
self.game.setLevel(1)
# The level is not finished
self.failIf(self.game.levelUp())
# 3 minutes to wait is a little bit long so this test is not active
# time.sleep(3 * 60)
# self.failUnless(self.game.levelUp())
# Change the blind properties
blind_properties = {
'change': 'levels',
'levels': PokerGameTestCase.TestLevelsTemplateFile,
'frequency': '3',
'unit': 'hand',
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Level 0
self.game.setLevel(0)
self.failUnless(self.game.delayToLevelUp(), (0, 'hand'))
# Level 1
self.game.setLevel(1)
self.game.setHandsCount(2)
self.failUnless(self.game.delayToLevelUp(), (5, 'hand'))
self.failIf(self.game.levelUp())
# Change the blind properties
blind_properties = {
'change': 'levels',
'levels': PokerGameTestCase.TestLevelsTemplateFile,
'frequency': '3',
'unit': 'Invalid',
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.failIf(self.game.delayToLevelUp())
# The game is not directing
self.game.is_directing = False
self.failIf(self.game.levelUp())
# ---------------------------------------------------------
def testCardsDealt(self):
"""Test Poker Game: Cards dealt"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnless(self.game.cardsDealt())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
self.failIf(self.game.cardsDealt())
self.failUnlessEqual(self.game.roundInfo()["hand_size"], 2)
self.failUnlessEqual(self.game.roundInfo()["board_size"], 0)
player1.hand = pokercards.PokerCards(['Ad', 'As'])
player2.hand = pokercards.PokerCards(['4d', 'Ts'])
self.failUnless(self.game.cardsDealt())
# Second round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isSecondRound())
self.failIf(self.game.cardsDealt())
self.failUnlessEqual(self.game.roundInfo()["hand_size"], 2)
self.failUnlessEqual(self.game.roundInfo()["board_size"], 3)
self.game.board = pokercards.PokerCards(['Qd', 'Kh', '8c'])
self.failUnless(self.game.cardsDealt())
# ---------------------------------------------------------
def testBet2Pot(self):
"""Test Poker Game: Bet to pot"""
self.game.registerCallback(Callback)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
InitCallback()
player1.bet = 500
self.game.bet2pot(serial = 1, dead_money = True)
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(player1.dead, 500)
self.failUnlessEqual(self.game.pot, 500)
self.failUnlessEqual(CallbackIds, [self.game.id])
self.failUnlessEqual(CallbackArgs, [('bet2pot', 1, 500)])
# ---------------------------------------------------------
def testDealCards(self):
"""Test Poker Game: Deal cards"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Client game, the deal card has no effect
self.failIf(self.game.cardsDealt())
self.game.is_directing = False
# Deal cards
self.game.dealCards()
self.failIf(self.game.cardsDealt())
self.game.is_directing = True
# Deal the cards
self.failIf(self.game.cardsDealt())
# Deal cards
self.game.dealCards()
self.failUnless(self.game.cardsDealt())
# The cards are hidden
self.failUnless(player1.hand.areHidden())
self.failUnless(player2.hand.areHidden())
# Check the players cards
player1_cards = pokercards.PokerCards(['8s', 'As'])
player2_cards = pokercards.PokerCards(['3h', '6d'])
player1_cards.allHidden()
player2_cards.allHidden()
self.failUnlessEqual(player1.hand, player1_cards)
self.failUnlessEqual(player2.hand, player2_cards)
# Second round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isSecondRound())
# Deal cards
self.game.dealCards()
# Check the board cards
self.failUnlessEqual(self.game.board, pokercards.PokerCards(['6s', '6h', 'Ah']))
# Next round
self.game.nextRound()
self.game.initRound()
# There is not enough cards in the deck for all the players
info = self.game.roundInfo()
info['board'] = ['board', 'board']
info["board_size"] = 2
info['cards'] = ['up', 'down']
info["hand_size"] = 2
self.game.deck = ['8d', '2h', '2c', '8c']
# Deal cards
self.game.dealCards()
# The player cards are transfered to the board
self.failUnlessEqual(info["hand_size"], 0)
self.failUnlessEqual(info["board_size"], 4)
# Can not deal all the cards needed
info = self.game.roundInfo()
info['board'] = ['board', 'board']
info["board_size"] = 2
info['cards'] = ['up', 'unknown', 'down']
info["hand_size"] = 3
self.game.deck = ['8d', '2h', '2c', '8c']
self.failUnlessRaises(UserWarning,self.game.dealCards)
# ---------------------------------------------------------
def testBotAutoPlay(self):
"""Test Poker Game: Bot auto play"""
# Change the bet properties
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/variants/round', None, {'min': '100', 'max': '300'}):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Change the variant name for cards evaluation
self.game.variant = 'holdem'
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# No possible action because the cards are not dealt
self.failUnlessEqual(self.game.possibleActions(1), [])
self.game.botPlayer(1)
self.failIf(player1.talked_once)
# Deal cards
self.game.dealCards()
# Player 1 is a bot
self.failUnlessEqual(self.game.possibleActions(1), ['raise', 'check'])
self.game.botPlayer(1)
self.failUnless(player1.isBot())
self.failUnless(player1.isAutoBlindAnte())
self.failUnlessEqual(player1.auto_muck, pokergame.AUTO_MUCK_ALWAYS)
self.failUnless(player1.isAuto())
# Player 1 automatically bet the minimum
self.failUnlessEqual(player1.bet, 100)
self.failUnlessEqual(player1.money, 1500)
self.failUnless(player1.talked_once)
# Player 2 automatically call
self.game.botPlayer(2)
# The game is finished
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_END)
# ---------------------------------------------------------
def testGetRequestedAction(self):
"""Test Poker Game: Get requested action"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player 2 is in position
self.failUnlessEqual(self.game.getSerialInPosition(), 2)
self.failUnlessEqual(self.game.getRequestedAction(1), None)
self.failUnlessEqual(self.game.getRequestedAction(2), 'blind_ante')
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Player 2 is in position
self.failUnlessEqual(self.game.getSerialInPosition(), 2)
self.failUnlessEqual(self.game.getRequestedAction(2), 'play')
# Add a third player
self.failUnless(self.game.addPlayer(3))
player3 = self.GetPlayer(3)
# The buy in is not payed
self.failIf(player3.isBuyInPayed())
self.failUnlessEqual(self.game.getRequestedAction(3), 'buy-in')
# Pay the buy in
self.failUnless(self.game.payBuyIn(3,self.game.bestBuyIn()))
self.failUnlessEqual(self.game.getRequestedAction(3), None)
# Player 3 has no money
player3.money = 0
self.failUnlessEqual(self.game.getRequestedAction(3), 'rebuy')
# Change the blind properties
blind_properties = {
'change': 'levels',
'levels': PokerGameTestCase.TestLevelsTemplateFile,
'frequency': '15',
'unit': 'minute'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# The game is now a tournament
self.failUnless(self.game.isTournament())
# The player 1 and 3 are not in position
self.failUnlessEqual(self.game.getRequestedAction(3), None)
self.failUnlessEqual(self.game.getRequestedAction(1), None)
# The player 2 is in position
self.failUnlessEqual(self.game.getRequestedAction(2), 'play')
# ---------------------------------------------------------
def testTalked(self):
"""Test Poker Game: Talked"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failIf(self.game.call(1))
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Deal cards
self.game.dealCards()
# Player 1 can talk
self.failUnless(self.game.isInPosition(1))
self.failUnless(self.game.canAct(1))
self.failIf(player1.talked_once)
self.failUnless(self.game.callNraise(1, 600))
self.failUnlessEqual(player1.bet, 600)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1000)
self.failUnless(player1.talked_once)
# Player 2 can talk
self.failUnless(self.game.isInPosition(2))
self.failUnless(self.game.canAct(2))
self.failIf(player2.talked_once)
self.failUnless(self.game.call(2))
self.failUnlessEqual(self.game.getPlayerMoney(2), 1000)
# Second round
self.failUnless(self.game.isSecondRound())
# ---------------------------------------------------------
def testTalkedClientGame(self):
"""Test Poker Game: Talked Client game"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failIf(self.game.call(1))
# Automatically pay the blind
self.game.autoBlindAnte(1)
self.game.autoBlindAnte(2)
# First round
self.failUnless(self.game.isFirstRound())
# Client game
self.game.is_directing = False
# player 1 raise
self.failUnless(self.game.callNraise(1, 600))
# Player 2 call
self.failUnless(self.game.call(2))
# Init round is not done
# The players are mot reset
self.failUnless(player1.talked_once)
self.failUnless(player2.talked_once)
# ---------------------------------------------------------
def testBlindInfo(self):
"""Test Poker Game: Blind info"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Blind info has been set
self.failUnless(self.game.blind_info)
# Check the blind values
self.failUnlessEqual(self.game.bigBlind(), 1000)
self.failUnlessEqual(self.game.smallBlind(), 500)
# Check blind amounts
self.game.setPlayerBlind(1, 'big')
self.failUnlessEqual(self.game.blindAmount(1), (self.game.bigBlind(), 0, 'big'))
self.game.setPlayerBlind(1, 'late')
self.failUnlessEqual(self.game.blindAmount(1), (self.game.bigBlind(), 0, 'late'))
self.game.setPlayerBlind(1, 'small')
self.failUnlessEqual(self.game.blindAmount(1), (self.game.smallBlind(), 0, 'small'))
self.game.setPlayerBlind(1, 'big_and_dead')
self.failUnlessEqual(self.game.blindAmount(1), (self.game.bigBlind(), self.game.smallBlind(), 'big_and_dead'))
self.game.setPlayerBlind(1, False)
self.failUnlessEqual(self.game.blindAmount(1), (0, 0, False))
self.game.setPlayerBlind(1, True)
self.failUnlessEqual(self.game.blindAmount(1), (0, 0, True))
self.game.setPlayerBlind(1, 'invalid')
self.failUnlessEqual(self.game.blindAmount(1), None)
# Unset the blind infos
self.game.blind_info = None
self.failUnlessEqual(self.game.bigBlind(), None)
self.failUnlessEqual(self.game.smallBlind(), None)
self.failUnlessEqual(self.game.blindAmount(1), (0, 0, False))
# ---------------------------------------------------------
def testSitOutNextTurn(self):
"""Test Poker Game: Sit out next turn"""
self.game.setMaxPlayers(3)
# Create all the players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player 2 is in position
self.failUnlessEqual(self.game.getSerialInPosition(), 2)
# The player 2 sit out next turn
self.failIf(self.game.isSitOut(2))
self.failUnless(self.game.sitOutNextTurn(2))
self.failUnless(player2.isSitOut())
self.failIf(player2.sit_out_next_turn)
self.failIf(player2.sit_requested)
self.failIf(player2.wait_for)
# The player 1 is not in position but he want to sit out
self.failIfEqual(self.game.getSerialInPosition(), 1)
self.failIf(player1.sit_out_next_turn)
self.failIf(player1.sit_requested)
self.failIf(self.game.sitOutNextTurn(1))
self.failUnless(player1.sit_out_next_turn)
self.failIf(player1.sit_requested)
# Client game
self.game.is_directing = False
# Player 3 sit out
self.failUnlessEqual(self.game.getSerialInPosition(), 3)
self.failIf(player3.sit_out_next_turn)
self.failIf(player3.sit_requested)
self.failIf(self.game.sitOutNextTurn(3))
self.failUnless(player3.sit_out_next_turn)
self.failIf(player3.sit_requested)
self.failUnlessEqual(player3.wait_for, False)
# ---------------------------------------------------------
def testSitOut(self):
"""Test Poker Game: Sit out"""
self.game.setMaxPlayers(4)
player1 = self.AddPlayerAndSit(1, 1)
player2 = self.AddPlayerAndSit(2, 3)
player3 = self.AddPlayerAndSit(3, 6)
player4 = self.AddPlayerAndSit(4, 8)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Sit out
self.game.setPosition(0)
self.failIf(self.game.getSitOut(1))
self.failUnless(self.game.sitOut(1))
self.failUnless(self.game.getSitOut(1))
self.failIf(player1.sit_out_next_turn)
self.failIf(player1.sit_requested)
self.failIf(player1.wait_for)
# the player is already sit out
self.failIf(self.game.sitOut(1))
self.game.setPosition(1)
self.failUnlessEqual(self.game.getSerialInPosition(), 2)
self.game.setPosition(2)
self.failIf(self.game.getSitOut(3))
self.failUnless(self.game.sitOut(3))
self.failUnless(self.game.getSitOut(3))
self.failIf(player3.sit_out_next_turn)
self.failIf(player3.sit_requested)
self.failIf(player3.wait_for)
self.failUnlessEqual(self.game.getSerialInPosition(), 4)
#
# Check that autoPayBlindAnte skips players that are sit out for some reason.
#
player1.sit_out = True
self.game.setPosition(0)
self.assertEquals([1, 2, 3, 4], self.game.player_list)
self.game.autoPayBlindAnte()
# ---------------------------------------------------------
def testSit(self):
"""Test Poker Game: Sit"""
self.game.setMaxPlayers(3)
# Add Player
self.failUnless(self.game.addPlayer(1, 2))
player1 = self.GetPlayer(1)
self.failIf(player1.isSit())
# The buy in is not payed, the player can not be added
self.failIf(player1.isBuyInPayed())
self.failIf(self.game.sit(1))
# Pay the buy in
self.failUnless(self.game.payBuyIn(1,self.game.bestBuyIn()))
self.failUnless(player1.isBuyInPayed())
# The player is broke, the player can not be added
money = self.game.getPlayerMoney(1)
player1.money = 0
self.failUnless(self.game.isBroke(1))
self.failIf(self.game.sit(1))
# Restore the player money
player1.money = money
self.failIf(self.game.isBroke(1))
# The player can sit
player1.wait_for = 'big'
self.failUnless(self.game.sit(1))
self.failUnless(player1.isSit())
self.failUnlessEqual(player1.wait_for, False)
self.failIf(player1.auto)
# Add a second player
player2 = self.AddPlayerAndSit(2, 5)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Add the third player
self.failUnless(self.game.addPlayer(3, 7))
self.failUnless(self.game.payBuyIn(3,self.game.bestBuyIn()))
player3 = self.GetPlayer(3)
self.failIf(player3.isSit())
# The player sit
self.failUnless(self.game.sit(3))
self.failUnless(player3.isSit())
self.failUnlessEqual(player3.wait_for, 'first_round')
# ---------------------------------------------------------
def testRebuy(self):
"""Test Poker Game: Rebuy"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
self.failUnlessEqual(self.game.maxBuyIn(), 10000)
# The player 3 is unknown so it can not rebuy
self.failIf(self.game.rebuy(3, 100))
# The player money + the rebuy amount is too low
player1.money = 10
self.failIf(self.game.rebuy(1, 10))
# The player money + the rebuy amount is too high
player1.money = 5000
self.failIf(self.game.rebuy(1, 5001))
# Test rebuy when game is not directing
self.game.is_directing = False
# The player money + the rebuy amount is too low, but game is not directing
player1.money = 10
self.failUnless(self.game.rebuy(1, 10))
# The player money + the rebuy amount is too high, but game is not directing
player1.money = 5000
self.failUnless(self.game.rebuy(1, 5001))
# Reset game and player money
self.game.is_directing = True
player1.money = 5000
# The player 1 rebuy 1000 but the game is not running so the money is added to it rebuy amount
self.failIf(self.game.isPlaying(1))
self.failUnless(self.game.rebuy(1, 1000))
self.failUnless(self.game.getPlayerMoney(1), 5000)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player 1 rebuy 1000 and the game is not running so the money is added directly to its money amount
self.failUnless(self.game.isPlaying(1))
self.failUnless(self.game.rebuy(1, 1000))
self.failUnless(self.game.getPlayerMoney(1), 6000)
# ---------------------------------------------------------
def testFullEmpty(self):
"""Test Poker Game: Full empty"""
# The game must be empty
self.failUnless(self.game.empty())
self.failIf(self.game.full())
# Add one player
player1 = self.AddPlayerAndSit(1, 2)
# The game is not empty and not full
self.failIf(self.game.empty())
self.failIf(self.game.full())
# Add the second player, the game is now full
player2 = self.AddPlayerAndSit(2, 7)
self.failIf(self.game.empty())
self.failUnless(self.game.full())
# ---------------------------------------------------------
def testSerialsAllSorted(self):
"""Test Poker Game: Serials all sorted"""
self.game.setMaxPlayers(3)
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# The dealer is not specified or incorrect so get the list of player sorted by serial number
self.game.dealer = -1
self.failUnlessEqual(self.game.serialsAllSorted(), [1, 2, 3])
self.game.dealer = 4
self.failUnlessEqual(self.game.serialsAllSorted(), [1, 2, 3])
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(self.game.dealer, 0)
self.failUnlessEqual(self.game.serialsAllSorted(), [2, 3, 1])
# Remove the player 1, do not reconstruct the player list
del self.game.serial2player[1]
self.failUnlessEqual(self.game.serialsAll(), [2, 3])
self.failUnlessEqual(self.game.player_list, [1, 2, 3])
# The dealer can not be the player 2
self.failUnlessEqual(self.game.serialsAllSorted(), [3, 2])
# ---------------------------------------------------------
def testSerialsInactive(self):
self.game.setMaxPlayers(3)
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# pre-test: all players should not be on auto when started
self.assertEquals(player3.auto, False)
self.assertEquals(self.game.serialsInactive(), [])
player1.auto = True
self.assertEquals(self.game.serialsInactive(), [player1.serial])
player2.auto = True
player2.action_issued = True
self.assertEquals(self.game.serialsInactive(), [player1.serial])
# ---------------------------------------------------------
def testBlind(self):
"""Test Poker Game: Blind"""
self.game.setMaxPlayers(3)
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Not Blind or Ante turn
self.failIf(self.game.isBlindAnteRound())
self.failIf(self.game.blind(1))
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player 1 can not act so it can not blind
self.failIf(self.game.canAct(1))
self.failIf(self.game.isBlindRequested(1))
self.failIf(self.game.blind(1))
# Get the blind limits for player 2
self.game.setPlayerBlind(2, 'big_and_dead')
self.failUnlessEqual(self.game.blindAmount(2), (1000, 500, 'big_and_dead'))
# The player 2 can blind, use the defined limits
self.failUnless(self.game.isBlindRequested(2))
self.game.blind(2)
self.failUnlessEqual(player2.bet, 1000)
self.failUnlessEqual(self.game.pot, 500)
self.failUnlessEqual(self.game.getPlayerMoney(2), 100)
# The player 2 has blind
self.failUnless(player2.blind)
self.failUnlessEqual(player2.missed_blind, None)
self.failIf(player2.wait_for)
# The player 3 can blind, bet 400 and 200 for the dead
self.failUnless(self.game.isBlindRequested(3))
self.game.blind(3, 400, 200)
self.failUnlessEqual(player3.bet, 400)
self.failUnlessEqual(self.game.pot, 500 + 200)
self.failUnlessEqual(player3.money, 1000)
# Blind structure unknown
self.game.blind_info = None
# The blind has not effect
self.failIf(self.game.isBlindRequested(1))
self.game.blind(1, 400, 200)
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(self.game.pot, 500 + 200)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1600)
# ---------------------------------------------------------
def testBlindAnteRoundEnd(self):
"""Test Poker Game: Blind and ante round end"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# No effect for server game
self.game.blindAnteRoundEnd()
self.failUnless(self.game.isBlindAnteRound())
# Client game
self.game.is_directing = False
# First Round
self.game.blindAnteRoundEnd()
self.failUnless(self.game.isFirstRound())
# Blind and ante round
self.game.resetRound()
self.game.initBlindAnte()
self.failUnless(self.game.isBlindAnteRound())
# Player 1 is all in
self.game.payBlind(1, 1600, 0)
self.failUnlessEqual(player1.bet, 1600)
self.failUnlessEqual(self.game.getPlayerMoney(1), 0)
self.failUnless(player1.isAllIn())
self.failIf(self.game.isInGame(1))
self.game.payBlind(2, 1600, 0)
# All the players are all in except one
self.game.blindAnteRoundEnd()
self.failUnlessEqual(self.game.pot, 3200)
# First Round
self.failUnless(self.game.isFirstRound())
# ---------------------------------------------------------
def testPayBlind(self):
"""Test Poker Game: Pay blind"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failIf(self.game.isBlindAntePayed())
# The player 1 pay blind
self.game.payBlind(1, 600, 200)
self.failUnlessEqual(player1.bet, 600)
self.failUnlessEqual(self.game.pot, 200)
self.failUnlessEqual(self.game.getPlayerMoney(1), 800)
self.failUnless(player1.blind)
self.failUnlessEqual(player1.missed_blind, None)
self.failIf(player1.wait_for)
# All blinds are not payed
self.failIf(self.game.isBlindAntePayed())
# The blind is higher than the player money
self.game.payBlind(2, 2000, 100)
self.failUnlessEqual(player2.bet, 1600)
self.failUnlessEqual(self.game.pot, 200 + 0)
self.failUnlessEqual(self.game.getPlayerMoney(2), 0)
self.failUnless(player2.blind)
self.failUnlessEqual(player2.missed_blind, None)
self.failIf(player2.wait_for)
# All blinds are not payed
self.failIf(self.game.isBlindAntePayed())
# The blind + the dead is higher than the player money
self.game.payBlind(3, 1000, 1000)
self.failUnlessEqual(player3.bet, 1000)
self.failUnlessEqual(self.game.pot, 200 + 0 + 600)
self.failUnlessEqual(player3.money, 0)
self.failUnless(player3.blind)
self.failUnlessEqual(player3.missed_blind, None)
self.failIf(player3.wait_for)
# All blinds are now payed
self.failUnless(self.game.isBlindAntePayed())
# ---------------------------------------------------------
def testWaitBigBlind(self):
"""Test Poker Game: Wait big blind"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player 2 can not act
self.failIf(self.game.canAct(2))
self.failIf(self.game.waitBigBlind(2))
# No blind info
blind_info = self.game.blind_info
self.game.blind_info = None
self.failIf(self.game.waitBigBlind(1))
self.failIf(self.game.waitBigBlind(2))
self.game.blind_info = blind_info
# The player 1 can act
self.failUnless(self.game.canAct(1))
self.failUnless(self.game.waitBigBlind(1))
self.failUnlessEqual(player1.wait_for, 'big')
# Player 2 pay the blind
self.failUnless(self.game.canAct(2))
self.game.autoBlindAnte(2)
self.failUnlessEqual(self.game.getPlayerMoney(2), 600)
self.failUnlessEqual(player2.bet, 1000)
self.failUnless(player2.isBlind())
# Player 1 pay the blind
self.failUnless(self.game.canAct(1))
self.game.autoBlindAnte(1)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1100)
self.failUnlessEqual(player1.bet, 500)
self.failUnless(player1.isBlind())
# Blind and ante turn finished
self.failIf(self.game.isBlindAnteRound())
# Waiting big blind is unavalaible
self.failIf(self.game.waitBigBlind(1))
self.failIf(self.game.waitBigBlind(2))
# ---------------------------------------------------------
def testAnte(self):
"""Test Poker Game: Ante"""
# Change the ante properties
ante_properties = {
'value': '100',
'bring-in': '200'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', 'ante', ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.game.setMaxPlayers(3)
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Not Blind or Ante turn
self.failIf(self.game.isBlindAnteRound())
self.failIf(self.game.ante(1))
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player 1 can not act so it can not ante
self.failIf(self.game.canAct(1))
self.failIf(self.game.isAnteRequested(1))
self.failIf(self.game.ante(1))
# Get the ante value
self.failUnlessEqual(self.game.ante_info['value'], 100)
# The player 2 can ante, use the defined limits
self.failUnless(self.game.isAnteRequested(2))
self.game.ante(2)
self.failUnlessEqual(player2.bet, 0)
self.failUnlessEqual(self.game.pot, 100)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1500)
# The player 2 has ante
self.failUnless(player2.ante)
# The player 3 can ante 400
self.failUnless(self.game.isAnteRequested(3))
self.game.ante(3, 400)
self.failUnlessEqual(player3.bet, 0)
self.failUnlessEqual(self.game.pot, 100 + 400)
self.failUnlessEqual(player3.money, 1200)
# Ante structure unknown
self.game.ante_info = None
# The ante has not effect
self.failIf(self.game.isAnteRequested(1))
self.game.ante(1, 400)
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(self.game.pot, 100 + 400)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1600)
# ---------------------------------------------------------
def testAutoPayBlind(self):
""" Test Poker Game: Auto pay blind"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The players are not auto
self.failIf(player1.isAutoBlindAnte())
self.failIf(player2.isAutoBlindAnte())
self.failIf(player3.isAutoBlindAnte())
# The auto pay blind has no effect
self.failUnlessEqual(self.game.getSerialInPosition(), 2)
self.game.autoPayBlindAnte()
# The player 2 is still in position
self.failUnlessEqual(self.game.getSerialInPosition(), 2)
# The turn is still blind and ante
self.failUnless(self.game.isBlindAnteRound())
# pay the blind for player 2
player2.auto_blind_ante = True
self.game.autoPayBlindAnte()
# The player 3 sit out
self.failUnless(self.game.sitOut(3))
self.failUnless(player3.isSitOut())
self.failUnlessEqual(self.game.getSerialInPosition(), 1)
# pay the blind for player 1
player1.auto_blind_ante = True
self.game.autoPayBlindAnte()
self.failUnlessEqual(True, player1.isBlind())
# The blind of the player 1 and 2 are automatically payed
self.game.autoPayBlindAnte()
self.failUnlessEqual(self.game.getPlayerMoney(1), 600)
self.failUnlessEqual(player1.bet, 1000)
self.failUnless(player1.blind)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1100)
self.failUnlessEqual(player2.bet, 500)
self.failUnless(player2.blind)
# First round
self.failUnless(self.game.isFirstRound())
# ---------------------------------------------------------
def testAutoPayBlindAllIn(self):
""" Test Poker Game: Auto pay blind all in"""
self.game.variant = 'holdem'
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player1.money = 400
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The players 1 automatically pay the blind
self.game.autoBlindAnte(1)
self.failUnlessEqual(self.game.getPlayerMoney(1), 0)
self.failUnlessEqual(player1.bet, 400)
self.failUnless(player1.blind)
# Player 1 is all in
self.failUnless(player1.isAllIn())
# The players 2 automatically pay the blind
self.game.autoBlindAnte(2)
# The game is finished
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_END)
# Check the end information
self.failUnless(self.game.isGameEndInformationValid())
# The player 1 win
self.failUnlessEqual(self.game.winners, [1])
self.failUnlessEqual(player1.money, 400 + ( 400 - self.game.getRakedAmount() ))
self.failUnlessEqual(player2.money, 1600 - 400)
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(player2.bet, 0)
self.failUnlessEqual(self.game.pot, 0)
# ---------------------------------------------------------
def testAutoPayBlindAllIn2(self):
""" Test Poker Game: Auto pay blind all in and a third player is to act"""
self.game.variant = 'holdem'
# Create players
self.game.setMaxPlayers(3)
player1 = self.AddPlayerAndSit(1, 2)
player1.money = 600
player2 = self.AddPlayerAndSit(2, 5)
player2.money = 400
player3 = self.AddPlayerAndSit(3, 7)
player3.money = 600
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The players 2 automatically pay the blind
self.game.autoBlindAnte(2)
self.failUnlessEqual(self.game.getPlayerMoney(2), 0)
self.failUnlessEqual(player2.bet, 400)
self.failUnless(player2.blind)
# Player 2 is all in
self.failUnless(player2.isAllIn())
# The players 3 automatically pay the blind
self.game.autoBlindAnte(3)
# The players 1 is to act and calls
self.failUnless(self.game.canAct(1))
self.failUnless(self.game.call(1))
# The game is finished
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_END)
# Check the end information
self.failUnless(self.game.isGameEndInformationValid())
# The player 3 win
self.failUnlessEqual(self.game.winners, [3])
self.failUnlessEqual(player3.money, 600 + 600 + 400 - self.game.getRakedAmount() )
self.failUnlessEqual(player2.money, 0)
self.failUnlessEqual(player1.money, 0)
self.failUnlessEqual(self.game.pot, 0)
# ---------------------------------------------------------
def testAutoPayAnte(self):
""" Test Poker Game: Auto pay ante"""
# Change the ante properties
ante_properties = {
'value': '100',
'bring-in': '200'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', 'ante', ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Reset the blind infos
self.game.blind_info = None
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The players are not auto
self.failIf(player1.isAutoBlindAnte())
self.failIf(player2.isAutoBlindAnte())
# The auto pay ante has no effect
self.failUnlessEqual(self.game.getSerialInPosition(), 1)
self.game.autoPayBlindAnte()
# The player 2 is still in position
self.failUnlessEqual(self.game.getSerialInPosition(), 1)
# The turn is still blind and ante
self.failUnless(self.game.isBlindAnteRound())
# The antes will be automatically payed
player1.auto_blind_ante = True
player2.auto_blind_ante = True
# The ante of the player 1 and 2 are automatically payed
self.game.autoPayBlindAnte()
self.failUnlessEqual(self.game.getPlayerMoney(1), 1500)
self.failUnlessEqual(player1.bet, 0)
self.failUnless(player1.ante)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1500)
self.failUnlessEqual(player2.bet, 0)
self.failUnless(player2.ante)
self.failUnlessEqual(self.game.pot, 100 + 100)
# The blind and ante turn is finished
self.failIf(self.game.isBlindAnteRound())
# ---------------------------------------------------------
def testAutoPayAnteAllIn(self):
""" Test Poker Game: Auto pay ante all in"""
self.game.variant = 'holdem'
# Change the ante properties
ante_properties = {
'value': '900',
'bring-in': '200'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', 'ante', ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Reset the blind infos
self.game.blind_info = None
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The players 1 automatically pay the blind
self.game.autoBlindAnte(1)
self.failUnlessEqual(self.game.getPlayerMoney(1), 700)
self.failUnlessEqual(self.game.pot, 900)
self.failUnless(player1.ante)
# Player 1 is all in
player1.all_in = True
self.failUnless(player1.isAllIn())
# The players 2 automatically pay the blind
self.game.autoBlindAnte(2)
# The game is finished
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_END)
# Check the end information
self.failUnless(self.game.isGameEndInformationValid())
# The player 1 win
self.failUnlessEqual(self.game.winners, [1])
rake = self.game.getRakedAmount()
self.failUnlessEqual(int(1800 * 0.05), rake)
self.failUnlessEqual(player1.money, 1600 + ( 900 - rake ))
self.failUnlessEqual(player2.money, 1600 - ( 900 ))
self.failUnlessEqual(self.game.pot, 0)
#
# The rake must be deduced from the delta
#
showdown_info = self.game.showdown_stack[0]
self.failUnlessEqual(900 - rake, showdown_info['serial2delta'][1])
self.failUnlessEqual(-900, showdown_info['serial2delta'][2])
# ---------------------------------------------------------
def testPayAnte(self):
"""Test Poker Game: Pay ante"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
self.game.variant = 'holdem'
# Change the ante properties
ante_properties = {
'value': '100',
'bring-in': '200'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', 'ante', ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Reset the blind infos
self.game.blind_info = None
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failIf(self.game.isBlindAntePayed())
# The player 1 pay ante
self.game.payAnte(1, 600)
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(self.game.pot, 600)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1000)
self.failUnless(player1.ante)
# All antes are not payed
self.failIf(self.game.isBlindAntePayed())
# The ante is higher than the player money
self.game.payAnte(2, 2000)
self.failUnlessEqual(player2.bet, 0)
self.failUnlessEqual(self.game.pot, 600 + 1600)
self.failUnlessEqual(self.game.getPlayerMoney(2), 0)
self.failUnless(player2.ante)
# All antes are not payed
self.failIf(self.game.isBlindAntePayed())
# The player 3 is sit out
self.game.setPosition(2)
self.failUnless(self.game.sitOut(3))
# All antes are now payed
self.failUnless(self.game.isBlindAntePayed())
# ---------------------------------------------------------
def testMinMoney(self):
"""Test Poker Game: min money"""
#
# game with blinds
#
self.failUnless(self.game.minMoney() > self.game.blind_info["big"]);
#
# game with antes
#
# Change the ante properties
ante_properties = {
'value': '100',
'bring-in': '200'
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet', 'ante', ante_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Reset the blind infos
self.game.blind_info = None
self.failUnless(self.game.minMoney() > self.game.ante_info["bring-in"]);
#
# tournament
#
self.game.ante_info["change"] = True;
self.failUnlessEqual(self.game.minMoney(), 0)
#
# no blinds, no antes
#
self.game.blind_info = None
self.game.ante_info = None
self.failUnlessEqual(self.game.minMoney(), 0)
# ---------------------------------------------------------
def testIsBroke(self):
"""Test Poker Game: Is broke"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Unknown players are not broke
self.failIf(self.game.isBroke(3))
# No player is broke
self.failIf(self.game.isBroke(1))
self.failIf(self.game.isBroke(2))
self.failUnlessEqual(self.game.brokeCount(), 0)
# The player 1 is broke, no money
player1.money = 0
# One player broke
self.failUnless(self.game.isBroke(1))
self.failUnlessEqual(self.game.brokeCount(), 1)
self.failUnlessEqual(self.game.serialsBroke(), [1])
self.failUnlessEqual(self.game.playersBroke(), [player1])
# The player 2 is borke, not enough money to play
self.failIf(self.game.isTournament())
# Change the blind properties
blind_properties = { 'small': '1000',
'big': '2000',
}
if not self.ModifyXMLFile(self.ConfigTempFile, '/bet/blind', None, blind_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
# Nothing should have changed
self.failIf(self.game.isBroke(2))
self.failUnlessEqual(self.game.brokeCount(), 1)
self.failUnlessEqual(self.game.serialsBroke(), [1])
self.failUnlessEqual(self.game.playersBroke(), [player1])
# ---------------------------------------------------------
def testAllIn(self):
"""Test Poker Game: All in"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The players are not initially all in
self.failIf(player1.isAllIn())
self.failIf(player2.isAllIn())
self.failUnlessEqual(self.game.allInCount(), 0)
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Deal cards
self.game.dealCards()
# The player 1 put all his money
self.failUnless(self.game.callNraise(1, self.game.getPlayerMoney(1)))
self.failUnless(player1.isAllIn())
self.failUnlessEqual(self.game.allInCount(), 1)
self.failUnlessEqual(self.game.serialsAllIn(), [1])
self.failUnlessEqual(self.game.playersAllIn(), [player1])
# ---------------------------------------------------------
def testUncalledInvalid(self):
"""Test Poker Game: uncalled amount does not pass distributeMoney checks"""
self.game.setVariant('holdem')
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
player2.money += player1.money
uncalled = player2.money
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The players are not initially all in
self.failIf(player1.isAllIn())
self.failIf(player2.isAllIn())
self.failUnlessEqual(self.game.allInCount(), 0)
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Deal cards
self.game.dealCards()
# The player 1 put all his money
self.failUnless(self.game.call(1))
self.failUnless(self.game.callNraise(2, self.game.getPlayerMoney(2)))
self.failUnless(player2.isAllIn())
self.failUnlessEqual(self.game.allInCount(), 1)
self.failUnlessEqual(self.game.serialsAllIn(), [2])
self.failUnlessEqual(self.game.playersAllIn(), [player2])
self.failUnlessEqual(self.game.uncalled, uncalled)
distributeMoney = self.game.distributeMoney
def f():
self.game.uncalled = 42 # invalid value
distributeMoney()
self.game.distributeMoney = f
try:
self.game.call(1)
except UserWarning, arg:
self.failUnlessEqual(str(arg), "serial2side_pot[winner.serial] != self.uncalled (1600 != 42)")
# ---------------------------------------------------------
def testRakeContributions(self):
"""Test Poker Game: rake contributions"""
self.game.setVariant('holdem')
# Create players
self.game.setMaxPlayers(3)
for i in xrange(1, 4):
self.AddPlayerAndSit(i)
self.game.botPlayer(i)
self.game.beginTurn(1)
self.failIf(self.game.isRunning())
self.failUnlessEqual(150, self.game.getRakedAmount())
self.failUnlessEqual(3000, self.game.getPotAmount())
self.failUnlessEqual({1: 50, 2: 50, 3: 50}, self.game.getRakeContributions())
# ---------------------------------------------------------
def testRakeContributionsUncalled(self):
"""Test Poker Game: rake contributions uncalled"""
self.game.setVariant('holdem')
# Create players
self.game.setMaxPlayers(3)
for i in xrange(1, 4):
player = self.AddPlayerAndSit(i)
self.game.botPlayer(i)
player.money = 100
player.money = 3000
self.game.beginTurn(1)
self.failIf(self.game.isRunning())
self.failUnlessEqual(15, self.game.getRakedAmount())
self.failUnlessEqual(700, self.game.getPotAmount())
self.failUnlessEqual({1: 5, 2: 5, 3: 5}, self.game.getRakeContributions())
# ---------------------------------------------------------
def testRake(self):
self.game.variant = 'holdem'
class PokerRakeHalf:
def __init__(self, game):
pass
def getRake(self, pot, uncalled, is_tournament):
return int((pot - uncalled) * .4)
self.game.rake = PokerRakeHalf(self.game)
cards = [4, 37, 2, 29, 48, 16, 22, 23, 8, 3, 7]
self.game.deck = self.game.eval.card2string(cards)
self.game.shuffler = PokerPredefinedDecks([cards])
# Create players
player_serials = [1,2,3]
player_seats = [2,5,7]
player_money = [100000,1000,50000]
players = {}
self.game.setMaxPlayers(3)
for (serial,seat,money) in zip(player_serials,player_seats,player_money):
players[serial] = self.AddPlayerAndSit(serial,seat)
players[serial].money = money
self.game.autoBlindAnte(serial)
self.game.beginTurn(1)
self.failUnless(self.game.isFirstRound())
self.game.callNraise(1, 90000)
self.game.call(2)
self.game.call(3)
for (serial,player) in players.items():
self.assertTrue(player.money>=0,"player %d has less than 0 money: %d" % (serial,player.money))
# ---------------------------------------------------------
def testRake2(self):
self.game.variant = 'holdem'
class PokerRakeMock:
def __init__(self, game):
pass
def getRake(self, pot, uncalled, is_tournament):
return int((pot - uncalled) * .1)
self.game.rake = PokerRakeMock(self.game)
# deck info
cards_to_player = (
(145,('6d','As')),
(148,('Qc','2s')),
(147,('4s','Qh')),
(150,('3h','4c')),
)
cards_board = ('9c','8h','9h','9d','4d')
# build deck
cards = []
for i in range(2):
for (player,card_strings) in cards_to_player:
cards.append(self.game.eval.string2card(card_strings[i]))
cards.extend(self.game.eval.string2card(cards_board))
cards.reverse()
self.game.deck = self.game.eval.card2string(cards)
self.game.shuffler = PokerPredefinedDecks([cards])
PlayerMock = namedtuple('PlayerMock', ('serial','seat','money'))
players_simple = [
PlayerMock(145, 1, 640000),
PlayerMock(148, 3, 10000),
PlayerMock(147, 6, 620000),
PlayerMock(150, 8, 10000),
]
players = {}
self.game.setMaxPlayers(4)
self.game.forced_dealer_seat = 6
for p in players_simple:
players[p.serial] = self.AddPlayerAndSit(p.serial, p.seat)
players[p.serial].money = p.money
players[p.serial].missed_blind = None
self.game.autoBlindAnte(p.serial)
self.game.beginTurn(1)
self.failUnless(self.game.isFirstRound())
self.game.callNraise(148, 800000)
self.game.call(147)
self.game.callNraise(150, 900000)
self.game.call(145)
self.game.callNraise(145,200000)
self.game.call(147)
self.game.callNraise(145,200000)
self.game.callNraise(147,400000)
self.game.callNraise(145,220000)
self.game.fold(147)
for (serial,player) in players.items():
self.assertTrue(player.money>=0,"player %d has less than 0 money: %d" % (serial,player.money))
# ---------------------------------------------------------
def testShortStackAtBigBlind(self):
# Include a min_bet in the betting structure
game = self.game
self.ModifyXMLFile(self.ConfigTempFile, '/bet/variants/round', None, {'min': str(game.bigBlind())})
game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
game.setMaxPlayers(4)
players_info = [
(1, 1, 2000),
(2, 3, 2000),
(3, 6, 947),
(4, 8, 2000),
]
players = {}
for (serial,seat,money) in players_info:
players[serial] = game.addPlayer(serial, seat)
game.payBuyIn(serial, 2000)
game.sit(serial)
players[serial] = self.GetPlayer(serial)
players[serial].money = money
game.autoBlindAnte(serial)
game.beginTurn(1)
self.assertEqual(players[3].bet, 947)
game.call(4)
self.failUnlessEqual(players[4].bet, game.bigBlind())
def testFlushes(self):
g = pokergame.PokerGame('poker.%s.xml', True, [path.join(TESTS_PATH, '../conf'), PokerGameTestCase.TestConfDirectory])
g.setVariant('holdem')
g.setBettingStructure('5-10_100-1000_no-limit')
players = [1,2]
for s in players:
g.addPlayer(s, s)
g.payBuyIn(s, g.buy_in)
g.sit(s)
# define a deck in which 2 players have flushes
cards = [17, 16, 9, 8, 5, 4, 2, 1, 0]
g.deck = g.eval.card2string(cards)
g.shuffler = PokerPredefinedDecks([cards])
g.beginTurn(1)
g.bet(1, g.buy_in)
g.bet(2, g.buy_in)
self.failUnlessEqual(g.winners, [2])
def testDisconnected(self):
"""Test Poker Game: Diconnected"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player are initially connected
self.failIf(player1.remove_next_turn)
self.failIf(player2.remove_next_turn)
self.failUnlessEqual(self.game.disconnectedCount(), 0)
self.failUnlessEqual(self.game.connectedCount(), 2)
self.failUnlessEqual(self.game.serialsDisconnected(), [])
self.failUnlessEqual(self.game.serialsConnected(), [1, 2])
self.failUnlessEqual(self.game.playersDisconnected(), [])
self.failUnlessEqual(self.game.playersConnected(), [player1, player2])
# Remove the player 1
self.failIf(self.game.removePlayer(1))
self.failUnless(player1.remove_next_turn)
# The player 1 is now disconnected
self.failUnlessEqual(self.game.disconnectedCount(), 1)
self.failUnlessEqual(self.game.connectedCount(), 1)
self.failUnlessEqual(self.game.serialsDisconnected(), [1])
self.failUnlessEqual(self.game.serialsConnected(), [2])
self.failUnlessEqual(self.game.playersDisconnected(), [player1])
self.failUnlessEqual(self.game.playersConnected(), [player2])
# ---------------------------------------------------------
def testReturnBlindAnte(self):
"""Test Poker Game: Return blind ante"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player 1 blind
self.game.setPlayerBlind(1, 'big')
self.game.blind(1)
self.failUnlessEqual(player1.bet, 1000)
self.failUnlessEqual(self.game.getPlayerMoney(1), 600)
# The player 2 sit out so the game is canceled
self.game.sitOut(2)
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1600)
# The game is finished, there is no winners
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_END)
self.failUnlessEqual(len(self.game.winners), 0)
# No winner, the end information are not valid
self.failIf(self.game.isGameEndInformationValid())
# ---------------------------------------------------------
def testCanceled(self):
"""Test Poker Game: Canceled"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player 1 blind
self.game.autoBlindAnte(1)
self.failUnlessEqual(player1.bet, 500)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1100)
# There is more than one player sit, cancel is not available
self.failIfEqual(self.game.sitCount(), 1)
self.game.canceled(1, 500)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1100)
# The player 2 sit out
self.failUnless(self.game.sitOut(2))
self.failUnlessEqual(self.game.sitCount(), 1)
# Cancel is not available in the current state
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_END)
self.game.canceled(1, 500)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1100)
# Change the game round to blind and ante
self.game.resetRound()
self.failUnless(self.game.isBlindAnteRound())
# The pot value does not correspond to the player bet
self.game.pot = 100
self.game.canceled(1, 500)
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1100)
# Change the game round to blind and ante
self.game.resetRound()
self.failUnless(self.game.isBlindAnteRound())
# The game is explicitely canceled
self.game.pot = 500
self.game.canceled(1, 500)
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1600)
# The game is finished, there is no winners
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_END)
self.failUnlessEqual(len(self.game.winners), 0)
# No winner, the end information are not valid
self.failIf(self.game.isGameEndInformationValid())
# ---------------------------------------------------------
def testNoAutoPlayer(self):
"""Test Poker Game: No auto player"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# The player 1 is an automatic player
player1.auto = True
# The player 1 is not an automatic player
self.failUnless(self.game.noAutoPlayer(1))
self.failIf(player1.auto)
# Invalid player
self.failIf(self.game.noAutoPlayer(3))
# ---------------------------------------------------------
def testAutoPlayer(self):
"""Test Poker Game: Auto player"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# The player 1 is set an automatic player
self.game.autoPlayer(1)
self.failUnless(player1.auto)
# The player 1 sit out because he is not a bot
self.game.interactivePlayer(1)
self.game.autoPlayer(1)
# The blind is automatically payed because the player 2 is a bot
self.game.botPlayer(2)
self.game.autoPlayer(2)
self.failUnlessEqual(player2.blind, True)
# Client game
self.game.is_directing = False
# AutoPlayer has no effect
self.game.botPlayer(3)
self.game.autoPlayer(3)
self.failIfEqual(player3.blind, True)
# ---------------------------------------------------------
def testPlayersPlaying(self):
"""Test Poker Game: Players playing"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# The game is not running so there is no playing players
self.failUnlessEqual(self.game.playingCount(), 0)
self.failUnlessEqual(self.game.serialsPlaying(), [])
self.failUnlessEqual(self.game.playersPlaying(), [])
self.failUnlessEqual(self.game.notPlayingCount(), 2)
self.failUnlessEqual(self.game.serialsNotPlaying(), [1, 2])
self.failUnlessEqual(self.game.playersNotPlaying(), [player1, player2])
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# All the players are now playing
self.failUnlessEqual(self.game.playingCount(), 2)
self.failUnlessEqual(self.game.serialsPlaying(), [1, 2])
self.failUnlessEqual(self.game.playersPlaying(), [player1, player2])
self.failUnlessEqual(self.game.notPlayingCount(), 0)
self.failUnlessEqual(self.game.serialsNotPlaying(), [])
self.failUnlessEqual(self.game.playersNotPlaying(), [])
# ---------------------------------------------------------
def testMuckStateSitOut(self):
"""Test Poker Game: Muck state sit out"""
player1 = self.AddPlayerAndSit(1, 2)
self.game.state = pokergame.GAME_STATE_MUCK
self.game.player_list = [ 1 ]
self.failIf(self.game.sitOutNextTurn(1))
self.failUnlessEqual(True, self.game.getPlayer(1).sit_out_next_turn)
# ---------------------------------------------------------
def testMuckStateWonFold(self):
"""Test Poker Game: Muck state won fold"""
self.game.setVariant('holdem')
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Deal cards
self.game.dealCards()
# Buy in amount
self.failUnlessEqual(self.game.getPlayerMoney(1), 1600)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1600)
# The players raise
self.failUnless(self.game.callNraise(1, 100))
self.failUnless(self.game.callNraise(2, 200))
self.failUnlessEqual(player1.bet, 100)
self.failUnlessEqual(player2.bet, 200)
# The player 1 fold
self.failUnless(self.game.fold(1))
# The winner is the player 2
self.failUnlessEqual(self.game.winners, [2])
self.failUnlessEqual(self.game.playersWinner(), [player2])
self.failUnless(self.game.isWinnerBecauseFold())
# Money amounts after
self.failUnlessEqual(self.game.getPlayerMoney(1), 1500)
rake = self.game.getRakedAmount()
self.failUnlessEqual(10, rake)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1700 - rake)
# ---------------------------------------------------------
def testMuckStateWonAllIn(self):
"""Test Poker Game: Muck state won all in"""
self.game.setVariant('holdem')
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Deal cards
self.game.dealCards()
# Buy in amount
self.failUnlessEqual(self.game.getPlayerMoney(1), 1600)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1600)
# The players raise
self.failUnless(self.game.callNraise(1, 100))
self.failUnless(self.game.callNraise(2, 1600))
self.failUnless(player1.bet, 100)
self.failUnless(player2.bet, 1600)
# The player 2 is all in
self.failUnlessEqual(self.game.getPlayerMoney(2), 0)
self.failUnless(player2.isAllIn())
# The player 1 is also all in
self.failUnless(self.game.callNraise(1, self.game.getPlayerMoney(1)))
self.failUnless(player1.isAllIn())
# All the players are now all in
# All the cards must be dealt
# Each player has 2 cards, and there are 5 cards in the board
hand1 = pokercards.PokerCards(['8s', 'As'])
hand2 = pokercards.PokerCards(['3h', '6d'])
board = pokercards.PokerCards(['4s', 'Qs', '6s', '6h', 'Ah'])
self.failUnlessEqual(player1.hand, hand1)
self.failUnlessEqual(player2.hand, hand2)
self.failUnlessEqual(self.game.board, board)
# The player 1 wins with a flush
self.failUnlessEqual(self.game.winners, [1])
self.failUnlessEqual(self.game.playersWinner(), [player1])
# Money amounts after
self.failUnlessEqual(self.game.getPotAmount(), 3200)
self.failUnlessEqual(self.game.getRakedAmount(), 160)
self.failUnlessEqual(self.game.getPlayerMoney(1), 3040)
self.failUnlessEqual(self.game.getPlayerMoney(2), 0)
def testMuckStateWonRegular(self):
"""Test Poker Game: Muck state won regular"""
self.game.setVariant('holdem')
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Deal cards
self.game.dealCards()
# Buy in amount
self.failUnlessEqual(self.game.getPlayerMoney(1), 1600)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1600)
# Round 1
self.failUnless(self.game.callNraise(1, 100))
self.failUnless(self.game.callNraise(2, 200))
self.failUnless(self.game.call(1))
# Round 2
self.failUnless(self.game.callNraise(2, 100))
self.failUnless(self.game.call(1))
# Round 3
self.failUnless(self.game.callNraise(2, 100))
self.failUnless(self.game.callNraise(1, 300))
self.failUnless(self.game.call(2))
# Round 4
self.failUnless(self.game.isLastRound())
self.failUnless(self.game.check(2))
self.failUnless(self.game.check(1))
# The turn is finished
# Each player has 2 cards, and there is 5 cards in the board
hand1 = pokercards.PokerCards(['8s', 'As'])
hand2 = pokercards.PokerCards(['3h', '6d'])
board = pokercards.PokerCards(['4s', 'Qs', '6s', '6h', 'Ah'])
self.failUnlessEqual(player1.hand, hand1)
self.failUnlessEqual(player2.hand, hand2)
self.failUnlessEqual(self.game.board, board)
# The player 1 wins with a flush
self.failUnlessEqual(self.game.winners, [1])
self.failUnlessEqual(self.game.playersWinner(), [player1])
# Money amounts after
self.failUnlessEqual(self.game.getPotAmount(), 1200)
self.failUnlessEqual(self.game.getRakedAmount(), 60)
self.failUnlessEqual(self.game.getPlayerMoney(1), 2140) # 2200 - 60
self.failUnlessEqual(self.game.getPlayerMoney(2), 1000)
# The money has been already distributed
self.failUnless(self.game.moneyDistributed())
# The distribution has no effect
self.game.distributeMoney()
# Money amounts after
self.failUnlessEqual(self.game.getPlayerMoney(1), 2140)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1000)
# ---------------------------------------------------------
def testHighLowWinners(self):
"""Test Poker Game: high low winners"""
# Modify wins properties
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant/wins', None, { 'ways': '2'}):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
winner_properties = {'id': '2', 'type': 'hand', 'order': 'low8'}
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant/wins', 'winner', winner_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
self.game.setVariant(PokerGameTestCase.TestVariantTemporaryFile)
self.game.variant = 'holdem8'
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# High low game
self.failUnless(self.game.isHighLow())
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Auto pay blind
for serial in self.game.serialsAll():
self.game.autoBlindAnte(serial)
# Deal all the cards
while not self.game.isLastRound():
self.game.nextRound()
self.game.dealCards()
# Check players money and bet
self.failUnlessEqual(player1.bet, 0)
self.failUnlessEqual(player2.bet, 500)
self.failUnlessEqual(player3.bet, 1000)
self.failUnlessEqual(player1.money, 1600)
self.failUnlessEqual(player2.money, 1100)
self.failUnlessEqual(player3.money, 600)
self.game.initRound()
self.failUnless(self.game.callNraise(2,501))
self.failUnless(self.game.call(3))
self.failUnless(self.game.call(1))
# 2 winners
self.failUnlessEqual(self.game.winners, [2, 3])
# Check money distribution
self.failUnlessEqual(self.game.getRakedAmount(), 150)
self.failUnlessEqual(player1.money, 599)
#
# Each player gives his share to the rake, i.e. 150/2
#
self.failUnlessEqual(player2.money, 2026) # 2101 - (150/2)
self.failUnlessEqual(player3.money, 2025) # 2100 - (150/2)
# ---------------------------------------------------------
def testRemovePlayer(self):
"""Test Poker Game: Remove player"""
# The number max of player is 2 so there are 2 seats left
self.failUnlessEqual(self.game.seatsLeftCount(), 2)
self.failUnlessEqual(self.game.seats_left, [2, 7])
# Add a new player on the seat 7
player1 = self.AddPlayerAndSit(1, 7)
self.failUnlessEqual(player1.seat, 7)
# 1 seat is still left
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
self.failUnlessEqual(self.game.seats_left, [2])
# Remove the player
self.failUnless(self.game.removePlayer(1))
# The Player has been delete
self.failUnlessEqual(self.game.getPlayer(1), None)
# The player seat is now left
self.failUnlessEqual(self.game.seatsLeftCount(), 2)
self.failUnlessEqual(self.game.seats_left, [2, 7])
# Add two players on the same seat
player1 = self.AddPlayerAndSit(1)
player2 = self.AddPlayerAndSit(2)
player2.seat = player1.seat
self.failUnlessEqual(self.game.seatsLeftCount(), 0)
# Remove the player
self.failUnless(self.game.removePlayer(1))
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# Remove the second player
self.failUnless(self.game.removePlayer(2))
# The number of seat left is still the same
self.failUnlessEqual(self.game.seatsLeftCount(), 1)
# ---------------------------------------------------------
def testCardsDealtThisRoundCount(self):
"""Test Poker Game: Card dealt this round"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# The game is not running
self.failUnlessEqual(self.game.cardsDealtThisRoundCount(), -1)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(self.game.cardsDealtThisRoundCount(), 0)
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# First round 2 cards down
round_info = self.game.roundInfo()
self.failUnlessEqual(round_info["cards"], ['down', 'down'])
self.failUnlessEqual(self.game.cardsDealtThisRoundCount(), 2)
self.failUnlessEqual(self.game.downCardsDealtThisRoundCount(), 2)
self.failUnlessEqual(self.game.upCardsDealtThisRoundCount(), 0)
# Set a card to up
round_info["cards"] = ['down', 'up']
self.failUnlessEqual(self.game.downCardsDealtThisRoundCount(), 1)
self.failUnlessEqual(self.game.upCardsDealtThisRoundCount(), 1)
# ---------------------------------------------------------
def testUpdateStats(self):
"""Test Poker Game: Update stats"""
self.game.setMaxPlayers(3)
# Initial pots
pots = {
'contributions': { 'total': {} },
'pots': [[0, 0]],
'last_round': -1,
'building': 0,
}
# Initial stats
stats = {
'flops': [],
'flops_count': 20,
'percent_flop': 0,
'pots': [],
'pots_count': 20,
'average_pot': 0,
'hands_per_hour': 0,
'time': -1,
'hands_count': 0,
'frequency': 180 # seconds
}
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Check stats
for attribute, value in stats.items():
self.failUnlessEqual(self.game.stats[attribute], value)
# Update stats flop
self.game.updateStatsFlop(True)
# Check stats
self.failUnlessEqual(self.game.stats['flops'], [0])
self.failUnlessEqual(self.game.stats['percent_flop'], 0)
# Init stats
self.game.stats = stats.copy()
# Update stats
self.game.updateStatsFlop(False)
# Check stats
self.failUnlessEqual(self.game.stats['flops'], [100])
self.failUnlessEqual(self.game.stats['percent_flop'], 100)
# Update stats end turn
self.failUnlessEqual(self.game.stats['time'], -1)
self.game.updateStatsEndTurn()
self.failIfEqual(self.game.stats['time'], -1)
self.failUnlessEqual(self.game.stats['hands_count'], 0)
# Set the frequency to 1 hour
self.game.stats['frequency'] = 3600
# Modification fo the time
self.game.setTime(4000)
# Modification of the pots
self.game.side_pots['pots'] = [[500, 300]]
# Modification of the hand count
self.game.hands_count = 1
# Update stats end turn
self.game.updateStatsEndTurn()
# Check stats
self.failUnlessEqual(self.game.stats['average_pot'], 300)
self.failUnlessEqual(self.game.stats['hands_per_hour'], 1)
self.failUnlessEqual(self.game.stats['hands_count'], 1)
# ---------------------------------------------------------
def testSidePots(self):
"""Test Poker Game: Side pots"""
# Initial pots
pots = {
'contributions': { 'total': {} },
'pots': [[0, 0]],
'last_round': -1,
'building': 0,
}
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# The side pots is initally empty
self.failUnlessEqual(self.game.getPots(), {})
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(self.game.playersInPotCount(self.game.getPots()), 0)
self.failIf(self.game.isSingleUncalledBet(self.game.getPots()))
# The blind contribution has been added to the pots
current_round = self.game.current_round
pots['contributions'][current_round] = {}
self.failUnlessEqual(self.game.getPots(), pots)
# The player 1 pay the blind
self.game.autoBlindAnte(1)
self.failUnlessEqual(player1.bet, 500)
self.failUnlessEqual(self.game.playersInPotCount(self.game.getPots()), 1)
self.failUnless(self.game.isSingleUncalledBet(self.game.getPots()))
# The pots has been updated
pots['building'] += 500
pots['contributions']['total'][1] = 500
pots['contributions'][current_round][len(pots['pots']) -1] = {}
pots['contributions'][current_round][len(pots['pots']) -1][1] = 500
self.failUnlessEqual(self.game.getPots(), pots)
# The player 2 pay also the blind
self.game.autoBlindAnte(2)
self.failUnlessEqual(player2.bet, 1000)
self.failUnlessEqual(self.game.playersInPotCount(self.game.getPots()), 2)
self.failIf(self.game.isSingleUncalledBet(self.game.getPots()))
# First round
self.failUnless(self.game.isFirstRound())
# The pots has been updated
pots['building'] += 1000
pots['contributions']['total'][2] = 1000
# The blind turn will be finished so its contribution infos will be copy in the first round infos and deleted
pots['contributions'][current_round][len(pots['pots']) -1][2] = 1000
pots['contributions'][current_round + 1] = pots['contributions'][-1]
del pots['contributions'][current_round]
pots['last_round'] = 0
current_round += 1
# Check pots
self.failUnlessEqual(self.game.getPots(), pots)
# The player 1 raises and is allin
self.failUnless(self.game.callNraise(1, 700))
self.failUnlessEqual(player1.bet, 1200)
# The pots has been updated
pots['building'] += 700
pots['contributions']['total'][1] += 700
pots['contributions'][current_round][len(pots['pots']) -1][1] += 700
self.failUnlessEqual(self.game.getPots(), pots)
self.failUnlessEqual(self.game.getLatestPotContributions(), {0: {1: 1200, 2: 1000}})
# The player 2 call
self.failUnless(self.game.call(2))
# Second round
self.failUnless(self.game.isSecondRound())
self.failUnlessEqual(self.game.playersInPotCount(self.game.getPots()), 0)
# The round is finished, the post has been updated
pots['building'] = 0
pots['pots'][0] = [1200 + 1200, 1200 + 1200]
pots['contributions']['total'][2] += 200
pots['contributions'][current_round][len(pots['pots']) -1][2] += 200
current_round += 1
pots['last_round'] = 1
pots['contributions'][current_round] = {}
# Check pots
self.failUnlessEqual(self.game.getPots(), pots)
self.failUnlessEqual(self.game.getSidePotTotal(), 2400)
# The player 2 raise 100
self.failUnless(self.game.callNraise(2, 100))
self.failUnlessEqual(self.game.getLatestPotContributions(), {0: {2: 100}})
# The player 1 call
self.failUnless(self.game.call(1))
# Round 3
self.failUnlessEqual(self.game.current_round, 2)
self.failUnlessEqual(self.game.playersInPotCount(self.game.getPots()), 0)
# The pots has been updated
pots['last_round'] = 2
pots['pots'][0] = [1200 + 1200 + 100 + 100, 1200 + 1200 + 100 + 100]
pots['contributions']['total'][1] += 100
pots['contributions']['total'][2] += 100
pots['contributions'][current_round][len(pots['pots']) -1] = {}
pots['contributions'][current_round][len(pots['pots']) -1][1] = 100
pots['contributions'][current_round][len(pots['pots']) -1][2] = 100
current_round += 1
pots['contributions'][current_round] = {}
# Check pots
self.failUnlessEqual(self.game.getPots(), pots)
self.failUnlessEqual(self.game.getSidePotTotal(), 2600)
self.failUnlessEqual(self.game.playersInPotCount(self.game.getPots()), 0)
# ---------------------------------------------------------
def testEndTurn(self):
"""Test Poker Game: End turn"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Pay the blind
self.game.autoBlindAnte(1)
self.game.autoBlindAnte(2)
# Check the players money and bet
self.failUnlessEqual(player1.bet, 500)
self.failUnlessEqual(player2.bet, 1000)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1100)
self.failUnlessEqual(self.game.getPlayerMoney(2), 600)
# Set a rebuy amount for each player
self.failIf(self.game.rebuy(1, 400))
self.failIf(self.game.rebuy(2, 600))
# The rebuy is credited to the player
wascalled = {"p1": False, "p2": False}
def P1rebuy400(game_id,game_type,*args):
if game_type == "end":
self.assertEqual(self.game.id, game_id)
self.failUnless(self.game.rebuy(1, 400))
wascalled["p1"] = True
def P2rebuy600(game_id,game_type,*args):
if game_type == "end":
self.assertEqual(self.game.id, game_id)
self.failUnless(self.game.rebuy(2, 600))
wascalled["p2"] = True
self.game.state = pokergame.GAME_STATE_MUCK
self.game.registerCallback(P1rebuy400)
self.game.registerCallback(P2rebuy600)
self.game.endState()
self.assertTrue(wascalled["p1"])
self.assertTrue(wascalled["p2"])
self.game.unregisterCallback(P1rebuy400)
self.game.unregisterCallback(P2rebuy600)
self.failUnlessEqual(self.game.getPlayerMoney(1), 1500)
self.failUnlessEqual(self.game.getPlayerMoney(2), 1200)
# The hand count is incremented
self.failUnlessEqual(self.game.hands_count, 1)
# import rpdb2; rpdb2.start_embedded_debugger("bla")
# self.game.sit(1)
# self.game.sit(2)
self.game.beginTurn(2)
# The player 1 is broke
player1.money = 0
self.failUnless(self.game.isBroke(1))
# Remove the player 2
self.game.removePlayer(2)
# This fails because of the Error #8737
self.failUnless(player2.remove_next_turn)
# Make the player remove needed
self.game.endTurn()
# The player 1 sit out
self.failIfEqual(self.game.getPlayer(1), None)
self.failUnless(self.game.getSitOut(1))
# The player 2 has been removed
self.failUnlessEqual(len(self.game.seats_left), 1)
self.failUnlessEqual(self.game.allCount(), 1)
self.failUnlessEqual(self.game.getPlayer(2), None)
# ---------------------------------------------------------
def testBeginTurn(self):
"""Test Poker Game: Begin turn"""
hand_serial = 1
# Create player 1
player1 = self.AddPlayerAndSit(1, 2)
# There is not enough player to start
self.failIf(self.game.buildPlayerList(True))
self.game.beginTurn(hand_serial)
self.failUnlessEqual(self.game.player_list, [])
self.failUnlessEqual(self.game.current_round, -2)
# Create player 2
player2 = self.AddPlayerAndSit(2, 7)
# Warning the muckable list is not empty
self.game.setMuckableSerials([1])
# Begin turn
self.game.beginTurn(hand_serial)
# The muckable serials have been reset
self.game.setMuckableSerials([])
# Init player infos
player_infos = {
'bet': 0,
'dead': 0,
'fold': False,
'hand': pokercards.PokerCards(),
'side_pot_index': 0,
'all_in': False,
'ante': False
}
# Init side pots infos
side_pots_infos ={
'contributions': { 'total': {} },
'pots': [[0, 0]],
'last_round': -1,
'building': 0,
}
# Current round initialisation
side_pots_infos['contributions'][self.game.current_round] = {}
# Init game infos
game_infos = {
'hand_serial': hand_serial,
'pot': 0,
'board': pokercards.PokerCards(),
'winners': [],
'muckable_serials': [],
'win_condition': pokergame.WON_NULL,
'serial2best': {},
'showdown_stack': [],
'side_pots': side_pots_infos
}
# Check game initialisation
for attribute, value in game_infos.items():
self.failUnlessEqual(getattr(self.game, attribute), value)
# Check players initialisation
for player in (player1, player2):
for attribute, value in player_infos.items():
self.failUnlessEqual(getattr(player, attribute), value)
# Check history, first event of type game
self.failIfEqual(len(self.game.historyGet()), 0)
self.failUnlessEqual(self.game.historyGet()[0][0], 'game')
# Check player list
self.failUnlessEqual(self.game.player_list, [1, 2])
# Blind and ante turn
self.failUnless(self.game.isBlindAnteRound())
# Call again begin turn has no effect
self.game.beginTurn(3)
self.failIfEqual(self.game.hand_serial, 3)
# ---------------------------------------------------------
def testInitRound(self):
"""Test Poker Game: Init round"""
round_infos = {
0: {
'name': 'pre-flop',
'position': 'under-the-gun'
},
1: {
'name': 'flop',
'position': 'next-to-dealer'
},
2: {
'name': 'turn',
'position': 'high'
},
3: {
'name': 'river',
'position': 'invalid'
}
}
# Change the round turn properties
round_turn_properties = {'type': 'high'}
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant/round[@name="turn"]/position', None, round_turn_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Change the round river properties
round_river_properties = {'type': 'invalid'}
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant/round[@name="river"]/position', None, round_river_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the variant structure
self.game.setVariant(PokerGameTestCase.TestVariantTemporaryFile)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Check the round infos
round_info = self.game.roundInfo()
self.failUnlessEqual(round_info['name'], round_infos[self.game.current_round]['name'])
self.failUnlessEqual(round_info['position'], round_infos[self.game.current_round]['position'])
# Check game init
self.failUnlessEqual(self.game.last_bet, 0)
self.failUnless(self.game.first_betting_pass)
self.failUnlessEqual(self.game.getSerialInPosition(), 1)
self.failUnlessEqual(self.game.getPlayerLastToTalk(), player2)
# Check players init
for player in (player1, player2):
self.failIf(player.talked_once)
# Second round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isSecondRound())
# Check the round infos
round_info = self.game.roundInfo()
self.failUnlessEqual(round_info['name'], round_infos[self.game.current_round]['name'])
self.failUnlessEqual(round_info['position'], round_infos[self.game.current_round]['position'])
self.failUnlessEqual(self.game.getSerialInPosition(), 2)
self.failUnlessEqual(self.game.getPlayerLastToTalk(), player1)
# Round 3
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.current_round, 2)
# Check the round infos
round_info = self.game.roundInfo()
self.failUnlessEqual(round_info['name'], round_infos[self.game.current_round]['name'])
self.failUnlessEqual(round_info['position'], round_infos[self.game.current_round]['position'])
self.failUnlessEqual(self.game.getSerialInPosition(), 1)
self.failUnlessEqual(self.game.getPlayerLastToTalk(), player2)
# Round 4
self.game.nextRound()
self.failUnlessRaises(UserWarning,self.game.initRound)
# ---------------------------------------------------------
def testInitRoundClientGame(self):
"""Test Poker Game: Init round client game"""
# Create a client game
self.CreateGameClient()
self.InitGame()
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
round_infos = {
0: {
'name': 'pre-flop',
'position': 'under-the-gun'
},
1: {
'name': 'flop',
'position': 'low'
},
2: {
'name': 'turn',
'position': 'under-the-gun'
}
}
# Change the round flop properties
round_flop_properties = { 'type': 'low' }
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant/round[@name="flop"]/position', None, round_flop_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Change the round turn properties
round_flop_properties = { 'type': 'under-the-gun' }
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant/round[@name="turn"]/position', None, round_flop_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the variant structure
self.game.setVariant(PokerGameTestCase.TestVariantTemporaryFile)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(self.game.player_list, [1, 2, 3])
# Player 2 is waiting big blind
player2.wait_for = 'big'
# First round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isFirstRound())
# Check the round infos
round_info = self.game.roundInfo()
self.failUnlessEqual(round_info['name'], round_infos[self.game.current_round]['name'])
self.failUnlessEqual(round_info['position'], round_infos[self.game.current_round]['position'])
self.failUnlessEqual(self.game.player_list, [1, 3])
# Check game init
self.failUnlessEqual(self.game.last_bet, 0)
self.failUnless(self.game.first_betting_pass)
self.failUnlessEqual(self.game.getSerialInPosition(), 3)
self.failUnlessEqual(self.game.getPlayerLastToTalk(), player1)
# Check players init
for player in (player1, player2):
self.failIf(player.talked_once)
# Second round
self.game.nextRound()
self.game.initRound()
self.failUnless(self.game.isSecondRound())
# Check the round infos
round_info = self.game.roundInfo()
self.failUnlessEqual(round_info['name'], round_infos[self.game.current_round]['name'])
self.failUnlessEqual(round_info['position'], round_infos[self.game.current_round]['position'])
self.failUnlessEqual(self.game.getSerialInPosition(), 1)
self.failUnlessEqual(self.game.getPlayerLastToTalk(), player3)
# The player 1 and 2 are fold
player1.fold = True
player2.fold = True
self.failIf(player1.isInGame())
self.failIf(player2.isInGame())
# Next round
self.game.nextRound()
# Not enough player in game to init the round
self.failUnless(self.game.inGameCount, 1)
self.failUnlessRaises(UserWarning, self.game.initRound)
# ---------------------------------------------------------
def testInitRoundBlindAllIn(self):
"""Test Poker Game: Init round blinds are all-in"""
# Create a client game
self.CreateGameClient()
self.InitGame()
self.game.setMaxPlayers(4)
# Create players
player1 = self.AddPlayerAndSit(1, 1)
player2 = self.AddPlayerAndSit(2, 3)
player3 = self.AddPlayerAndSit(3, 6)
player4 = self.AddPlayerAndSit(4, 8)
# Change the round flop properties
round_flop_properties = { 'type': 'low' }
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant/round[@name="flop"]/position', None, round_flop_properties):
self.fail('Error during modification of configuration file ' + self.ConfigTempFile)
# Reload the variant structure
self.game.setVariant(PokerGameTestCase.TestVariantTemporaryFile)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.failUnlessEqual(self.game.player_list, [1, 2, 3, 4])
# Player 2 & 4 are all_in
player2.all_in = True
player4.all_in = True
self.failUnless("small", player2.blind)
self.failUnless("big", player3.blind)
# First round
self.game.nextRound()
self.game.initRound()
#
# idx
# players: 0 | 1 dealer - first to talk
# 1 | 2 small blind all in
# 2 | 3 big blind - last to talk
# 3 | 4 all in
#
self.assertEqual(0, self.game.position)
self.assertEqual(2, self.game.last_to_talk)
# ---------------------------------------------------------
def testMuck(self):
"""Test Poker Game: Muck"""
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Init the muckable serials
self.game.setMuckableSerials([10,20])
self.failUnlessEqual(self.game.muckable_serials, [10,20])
# Init the muckable serials
self.game.setMuckableSerials((1,2))
self.failUnlessEqual(list, type(self.game.muckable_serials));
self.failUnlessEqual(self.game.muckable_serials, [1,2])
# Muck not available
self.game.muck(1, True)
self.failUnlessEqual(self.game.muckable_serials, [1,2])
# Muck state
self.game.changeState(pokergame.GAME_STATE_MUCK)
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_MUCK)
# Player 1 muck
self.game.muck(1, False)
self.failUnlessEqual(self.game.muckable_serials, [2])
self.failUnless(player1.hand.areVisible())
# The muck serial list is not empty
# The state is still MUCK STATE
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_MUCK)
# Unknown player, muck has no effect
self.game.muck(3, True)
self.failUnlessEqual(self.game.muckable_serials, [2])
# Client game
self.game.is_directing = False
# Muck state has no effect
self.game.muckState(pokergame.WON_NULL)
# Muck has no effect
self.game.muck(2, False)
self.failUnlessEqual(self.game.muckable_serials, [2])
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_MUCK)
self.game.is_directing = True
# Player 2 muck
self.game.muck(2, False)
self.failUnlessEqual(self.game.muckable_serials, [])
self.failUnless(player2.hand.areVisible())
# The game is finished
self.failUnlessEqual(self.game.state, pokergame.GAME_STATE_END)
# ---------------------------------------------------------
def testGetMaxBoardSize(self):
"""Test Poker Game: Get max board size"""
# The max board size is initially set to 5
self.failUnlessEqual(self.game.getMaxBoardSize(), 5)
# Change the variant type
if not self.ModifyXMLFile(self.VariantTempFile, '/poker/variant', None, {'type': 'NotCommunity'}):
self.fail('Error during modification of variant file ' + self.VariantTempFile)
self.game.setVariant(PokerGameTestCase.TestVariantTemporaryFile)
# Not a community variant, max board size set 0
self.failUnlessEqual(self.game.getMaxBoardSize(), 0)
# ---------------------------------------------------------
def testGetParamList(self):
"""Test Poker Game: Get param list"""
self.failUnlessEqual(len(self.game.getParamList('/bet/variants/round')), 4)
self.failUnlessEqual(len(self.game.getParamList('/poker/variant/community/position')), 5)
# ---------------------------------------------------------
def testGetParam(self):
"""Test Poker Game: Get param"""
self.failUnlessEqual(self.game.getParam('/bet/@buy-in'), '50')
self.failUnlessEqual(self.game.getParam('/poker/variant/@type'), 'community')
# ---------------------------------------------------------
def testGetParamProperties(self):
"""Test Poker Game: Get param properties"""
bet_properties = {
'buy-in': '50',
'max-buy-in': '10000',
'best-buy-in': '1600',
'unit': '300'
}
properties = self.game.getParamProperties('/bet')[0]
for attribute, value in bet_properties.items():
self.failUnlessEqual(properties[attribute], value)
variant_properties = {
'type': 'community',
'name': 'VariantName',
'id': 'VariantTest'
}
properties = self.game.getParamProperties('/poker/variant')[0]
for attribute, value in variant_properties.items():
self.failUnlessEqual(properties[attribute], value)
# ---------------------------------------------------------
def testIsGameEndInformationValid(self):
"""Test Poker Game: Is game end information are valid"""
# The game state is not GAME_STATE_END
self.failIfEqual(self.game.state,pokergame.GAME_STATE_END)
self.failIf(self.game.isGameEndInformationValid())
# Change the game state
self.game.changeState(pokergame.GAME_STATE_END)
self.failUnlessEqual(self.game.state,pokergame.GAME_STATE_END)
# there is no winner
self.failUnlessEqual(len(self.game.winners),0)
self.failIf(self.game.isGameEndInformationValid())
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 7)
# Set the winners
self.game.winners = [1]
# The end information are valid
self.failUnless(self.game.isGameEndInformationValid())
# Remove the winner from the player list
del self.game.serial2player[1]
# The end information are now invalid
self.failIf(self.game.isGameEndInformationValid())
# ---------------------------------------------------------
def testDispatchMuck(self):
"""Test Poker Game: Dispatch Muck"""
self.game.setVariant('holdem')
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Deal all the cards
while not self.game.isLastRound():
self.game.nextRound()
self.game.dealCards()
# Init winners
self.game.setWinners([1])
# Init winners per side
self.game.side2winners = { 'hi': [], 'low': [] }
# Winner because fold
self.game.win_condition = pokergame.WON_FOLD
self.failUnlessEqual(self.game.dispatchMuck(), ((), (1,)))
self.game.win_condition = pokergame.WON_REGULAR
# Dealer is the player 2
self.failUnlessEqual(self.game.dealer, 0)
# The player 2 and 3 muck, the winner show his cards
self.failUnlessEqual(self.game.dispatchMuck(), ((1,), (2,3)))
# Init winners per side
self.game.side2winners = { 'hi': [2], 'low': [] }
# The player 2 show also his cards
self.failUnlessEqual(self.game.dispatchMuck(), ((2, 3, 1), ()))
# Init winners per side
self.game.side2winners = { 'hi': [], 'low': [3] }
# All the player show their cards
self.failUnlessEqual(self.game.dispatchMuck(), ((2,1), (3,)))
# Client game
self.game.is_directing = False
self.failUnlessEqual(self.game.dispatchMuck(), None)
# ---------------------------------------------------------
def testAutoMuckNever(self):
"""Test Poker Game: Auto muck never"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Auto pay blind
for serial in self.game.serialsAll():
self.game.autoBlindAnte(serial)
# Set auto muck state
self.game.autoMuck(1, pokergame.AUTO_MUCK_NEVER)
self.game.autoMuck(2, pokergame.AUTO_MUCK_NEVER)
self.game.autoMuck(3, pokergame.AUTO_MUCK_NEVER)
# Players 1 and 2 fold
self.failUnless(self.game.fold(1))
self.failUnless(self.game.fold(2))
# Player 3 is the winner and muckable
self.failUnlessEqual(self.game.winners, [3])
self.failUnlessEqual(self.game.muckable_serials, [3])
# ---------------------------------------------------------
def testAutoMuckAlways(self):
"""Test Poker Game: Auto muck always"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Auto pay blind
for serial in self.game.serialsAll():
self.game.autoBlindAnte(serial)
# Set auto muck state
self.game.autoMuck(1, pokergame.AUTO_MUCK_ALWAYS)
self.game.autoMuck(2, pokergame.AUTO_MUCK_ALWAYS)
self.game.autoMuck(3, pokergame.AUTO_MUCK_ALWAYS)
# Players 1 and 2 fold
self.failUnless(self.game.fold(1))
self.failUnless(self.game.fold(2))
# No muckable players
self.failUnlessEqual(self.game.winners, [3])
self.failUnlessEqual(self.game.muckable_serials, [])
# ---------------------------------------------------------
def testAutoMuckWin(self):
"""Test Poker Game: Auto muck win"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Auto pay blind
for serial in self.game.serialsAll():
self.game.autoBlindAnte(serial)
# Set auto muck state
self.game.autoMuck(1, pokergame.AUTO_MUCK_WIN)
self.game.autoMuck(2, pokergame.AUTO_MUCK_WIN)
self.game.autoMuck(3, pokergame.AUTO_MUCK_WIN)
# Players 1 and 2 fold
self.failUnless(self.game.fold(1))
self.failUnless(self.game.fold(2))
# Player 3 is the winner but not muckable
self.failUnless(self.game.isWinnerBecauseFold())
self.failUnlessEqual(self.game.winners, [3])
self.failUnlessEqual(self.game.muckable_serials, [])
# ---------------------------------------------------------
def testAutoMuckLose(self):
"""Test Poker Game: Auto muck lose"""
self.game.variant = 'holdem'
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddPlayerAndSit(2, 5)
player3 = self.AddPlayerAndSit(3, 7)
# Blind and ante turn
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
# Auto pay blind
for serial in self.game.serialsAll():
self.game.autoBlindAnte(serial)
# Set auto muck state
self.game.autoMuck(1, pokergame.AUTO_MUCK_LOSE)
self.game.autoMuck(2, pokergame.AUTO_MUCK_LOSE)
self.game.autoMuck(3, pokergame.AUTO_MUCK_LOSE)
# Deal all the cards
while not self.game.isLastRound():
self.game.nextRound()
self.game.dealCards()
self.game.initRound()
self.failUnless(self.game.callNraise(2,100))
self.failUnless(self.game.call(3))
self.failUnless(self.game.call(1))
# Player 3 is the winner but not muckable
self.failIf(self.game.isWinnerBecauseFold())
self.failUnlessEqual(self.game.winners, [3])
self.failUnlessEqual(self.game.muckable_serials, [])
# ---------------------------------------------------------
def testUpdateBlinds(self):
"""Test Poker Game: Update blinds"""
self.game.setMaxPlayers(4)
# Create 1 player
player1 = self.AddPlayerAndSit(1, 1)
# Not enough player sit
# The wait_for attribute is reset if not equal to first round
player1.wait_for = 'first_round'
self.game.updateBlinds()
self.failUnlessEqual(player1.wait_for, 'first_round')
player1.wait_for = 'big'
self.game.updateBlinds()
self.failUnlessEqual(player1.wait_for, False)
# Create players
player2 = self.AddPlayerAndSit(2, 3)
player3 = self.AddPlayerAndSit(3, 6)
player4 = self.AddPlayerAndSit(4, 8)
# Init players infos
self.game.playersBeginTurn()
# Update blinds
blinds = {
1: { 'blind': False, 'missed_blind': None, 'wait_for': False},
2: { 'blind': 'small', 'missed_blind': None, 'wait_for': False},
3: { 'blind': 'big', 'missed_blind': None, 'wait_for': False},
4: { 'blind': False, 'missed_blind': None, 'wait_for': False}
}
self.game.updateBlinds()
# Check blinds
for player in blinds.keys():
for attribute, value in blinds[player].items():
self.failUnlessEqual(getattr(self.game.getPlayer(player), attribute), value)
# Move the dealer
self.game.moveDealerLeft()
# Update blinds
blinds = {
1: { 'blind': False, 'missed_blind': None, 'wait_for': False},
2: { 'blind': False, 'missed_blind': None, 'wait_for': False},
3: { 'blind': 'small', 'missed_blind': None, 'wait_for': False},
4: { 'blind': 'big', 'missed_blind': None, 'wait_for': False}
}
self.game.updateBlinds()
# Check blinds
for player in blinds.keys():
for attribute, value in blinds[player].items():
self.failUnlessEqual(getattr(self.game.getPlayer(player), attribute), value)
# Move the dealer
self.game.moveDealerLeft()
# Update blinds
blinds = {
1: { 'blind': 'big', 'missed_blind': None, 'wait_for': False},
2: { 'blind': False, 'missed_blind': None, 'wait_for': False},
3: { 'blind': False, 'missed_blind': None, 'wait_for': False},
4: { 'blind': 'small', 'missed_blind': None, 'wait_for': False}
}
self.game.updateBlinds()
# Check blinds
for player in blinds.keys():
for attribute, value in blinds[player].items():
self.failUnlessEqual(getattr(self.game.getPlayer(player), attribute), value)
# Forbid missed blinds
player1.missed_blind = 'small'
player1.wait_for = 'late'
player2.missed_blind = 'small'
player3.missed_blind = 'small'
self.game.updateBlinds()
blinds = {
1: { 'blind': 'big', 'missed_blind': None, 'wait_for': False},
2: { 'blind': False, 'missed_blind': None, 'wait_for': False},
3: { 'blind': False, 'missed_blind': None, 'wait_for': False},
4: { 'blind': 'small', 'missed_blind': None, 'wait_for': False}
}
# Check blinds
for player in blinds.keys():
for attribute, value in blinds[player].items():
self.failUnlessEqual(getattr(self.game.getPlayer(player), attribute), value)
# ---------------------------------------------------------
def testUpdateSmallBlinds(self):
"""Test Poker Game: Update small blinds"""
self.game.setMaxPlayers(4)
# Create players
player1 = self.AddPlayerAndSit(1, 1)
player2 = self.AddPlayerAndSit(2, 3)
player3 = self.AddPlayerAndSit(3, 6)
player4 = self.AddPlayerAndSit(4, 8)
# Update blinds
blinds = {
1: { 'blind': False, 'missed_blind': None, 'wait_for': False},
2: { 'blind': 'small', 'missed_blind': None, 'wait_for': False},
3: { 'blind': 'big', 'missed_blind': None, 'wait_for': False},
4: { 'blind': False, 'missed_blind': None, 'wait_for': False}
}
self.game.updateBlinds()
# Check blinds
for player in blinds.keys():
for attribute, value in blinds[player].items():
self.failUnlessEqual(getattr(self.game.getPlayer(player), attribute), value)
# Init players infos
self.game.playersBeginTurn()
# Player 2 has already payed the blind =>
# Nothing is done
player2.blind = True
self.game.updateBlinds()
blinds = {
1: { 'blind': False, 'missed_blind': None, 'wait_for': False},
2: { 'blind': True, 'missed_blind': None, 'wait_for': False},
3: { 'blind': 'big', 'missed_blind': None, 'wait_for': False},
4: { 'blind': False, 'missed_blind': None, 'wait_for': False}
}
# Check blinds
for player in blinds.keys():
for attribute, value in blinds[player].items():
self.failUnlessEqual(getattr(self.game.getPlayer(player), attribute), value)
# Init players infos
self.game.playersBeginTurn()
# Player 2 has missed a blind
player2.missed_blind = 'small'
self.game.updateBlinds()
blinds = {
1: { 'blind': False, 'missed_blind': None, 'wait_for': False},
2: { 'blind': False, 'missed_blind': 'small', 'wait_for': 'late'},
3: { 'blind': 'small', 'missed_blind': None, 'wait_for': False},
4: { 'blind': 'big', 'missed_blind': None, 'wait_for': False}
}
# Check blinds
for player in blinds.keys():
for attribute, value in blinds[player].items():
self.failUnlessEqual(getattr(self.game.getPlayer(player), attribute), value)
# ---------------------------------------------------------
def testUpdateBigBlinds(self):
"""Test Poker Game: Update big blinds"""
self.game.setMaxPlayers(4)
# Create players
player1 = self.AddPlayerAndSit(1, 1)
player2 = self.AddPlayerAndSit(2, 3)
player3 = self.AddPlayerAndSit(3, 6)
player4 = self.AddPlayerAndSit(4, 8)
# Update blinds
blinds = {
1: { 'blind': False, 'missed_blind': None, 'wait_for': False},
2: { 'blind': 'small', 'missed_blind': None, 'wait_for': False},
3: { 'blind': 'big', 'missed_blind': None, 'wait_for': False},
4: { 'blind': False, 'missed_blind': None, 'wait_for': False}
}
self.game.updateBlinds()
# Check blinds
for player in blinds.keys():
for attribute, value in blinds[player].items():
self.failUnlessEqual(getattr(self.game.getPlayer(player), attribute), value)
# Init players infos
self.game.playersBeginTurn()
# Player 2 has already payed the blind =>
# Nothing is done
player3.blind = True
player3.wait_for = 'small'
self.game.updateBlinds()
blinds = {
1: { 'blind': False, 'missed_blind': None, 'wait_for': False},
2: { 'blind': 'small', 'missed_blind': None, 'wait_for': False},
3: { 'blind': True, 'missed_blind': None, 'wait_for': False},
4: { 'blind': False, 'missed_blind': None, 'wait_for': False}
}
# Check blinds
for player in blinds.keys():
for attribute, value in blinds[player].items():
self.failUnlessEqual(getattr(self.game.getPlayer(player), attribute), value)
# ---------------------------------------------------------
def testUpdateErrorSmallAndBigBlinds(self):
"""Test Poker Game: Update error small and big blinds"""
self.game.setMaxPlayers(pokergame.ABSOLUTE_MAX_PLAYERS)
# Create players
for num in range(pokergame.ABSOLUTE_MAX_PLAYERS):
player = self.AddPlayerAndSit(num + 1)
player.wait_for = 'big'
self.game.getPlayer(1).wait_for = 'first_round'
# Error small blind can not be assigned
self.game.updateBlinds()
# Check player 1 blinds
blinds1 = {'blind': 'late', 'missed_blind': None, 'wait_for': 'first_round'}
# Check blinds
for attribute, value in blinds1.items():
self.failUnlessEqual(getattr(self.game.getPlayer(1), attribute), value)
blinds = {'blind': 'late', 'missed_blind': None, 'wait_for': 'big'}
# Check players blinds
for num in range(1, pokergame.ABSOLUTE_MAX_PLAYERS):
for attribute, value in blinds.items():
self.failUnlessEqual(getattr(self.game.getPlayer(num + 1), attribute), value)
def testShowdownstack(self):
game = pokergame.PokerGameServer("poker.%s.xml", [path.join(TESTS_PATH, '../conf'), PokerGameTestCase.TestConfDirectory])
game.setVariant("holdem")
game.setBettingStructure("100-200_2000-20000_no-limit")
player = {}
money = {
66: 300,
76: 100,
77: 200,
}
for serial in (66, 76, 77):
self.assert_(game.addPlayer(serial))
player[serial] = game.serial2player[serial]
player[serial].money = 20000
player[serial].buy_in_payed = True
self.assert_(game.sit(serial))
player[serial].auto_blind_ante = True
player[serial].money = money[serial]
game.autoMuck(serial, pokergame.AUTO_MUCK_ALWAYS)
game.dealer_seat = 0
game.beginTurn(1)
player[66].blind = 'small'
player[76].blind = 'big'
player[77].blind = None
game.deck = ['7c', 'Qs', '6c', 'Qc', '2h', '8c', '4h', 'Jh', '4c', '9s', '3h' ]
game.setPosition(0)
game.callNraise(66, 200)
self.assertEqual("end", game.state)
game_state = game.showdown_stack[0]
self.assertEqual(game_state["type"], "game_state")
for s, p in player.items():
self.assertEqual(p.money, game_state["serial2money"][s])
def testAllInWithDead(self):
""" Test Poker Game: Allin with dead blind and lost to the winner although the winner has less money """
game = pokergame.PokerGameServer("poker.%s.xml", [path.join(TESTS_PATH, '../conf'), PokerGameTestCase.TestConfDirectory])
game.setVariant("holdem")
game.setBettingStructure("100-200_2000-20000_no-limit")
player = {}
money = {}
money[66] = 300
money[76] = 100
money[77] = 200
for serial in (66, 76, 77):
self.assert_(game.addPlayer(serial))
player[serial] = game.serial2player[serial]
player[serial].money = 20000
player[serial].buy_in_payed = True
self.assert_(game.sit(serial))
#player[serial].auto_blind_ante = True
player[serial].money = money[serial]
game.autoMuck(serial, pokergame.AUTO_MUCK_ALWAYS)
game.dealer_seat = 0
game.beginTurn(1)
player[66].blind = 'big_and_dead'
player[76].blind = 'small'
player[77].blind = 'big'
#
# 77: 4c 8c
# 76: 9s 4h
# 66: 3h Jh
#
game.deck = ['7c', 'Qs', '6c', 'Qc', '2h', '8c', '4h', 'Jh', '4c', '9s', '3h' ]
game.setPosition(0)
game.blind(66, 200, 100)
game.blind(76, 100, 0)
game.blind(77, 200, 0)
self.assertEqual("end", game.state)
rake = game.getRakedAmount()
self.failUnlessEqual(30, rake)
self.assertEqual(400 - rake, game.showdown_stack[0]['serial2delta'][77])
def testDeadWithUncalled(self):
""" Test Poker Game: dead blind + a player has uncalled bet and is not the winner.
"""
game = pokergame.PokerGameServer("poker.%s.xml", [path.join(TESTS_PATH, '../conf'), PokerGameTestCase.TestConfDirectory])
game.setVariant("holdem")
game.setBettingStructure("100-200_2000-20000_no-limit")
player = {}
money = {}
money[66] = 20000
money[76] = 10000
money[77] = 10000
for serial in (66, 76, 77):
self.assert_(game.addPlayer(serial))
player[serial] = game.serial2player[serial]
player[serial].money = 2000
player[serial].buy_in_payed = True
self.assert_(game.sit(serial))
#player[serial].auto_blind_ante = True
game.autoMuck(serial, pokergame.AUTO_MUCK_ALWAYS)
player[serial].money = money[serial]
game.dealer_seat = 0
game.beginTurn(1)
player[66].blind = 'big_and_dead'
player[76].blind = 'small'
player[77].blind = 'big'
#
# 77: 4c 8c
# 76: 9s 4h
# 66: 3h Jh
#
game.deck = ['7c', 'Qs', '6c', 'Qc', '2h', '4h', 'Jh', '8c', '9s', '3h', '4c' ]
game.setPosition(0)
game.blind(66, 200, 100)
game.blind(76, 100, 0)
game.blind(77, 200, 0)
self.assertEqual(game.state, "pre-flop")
game.callNraise(66, 20000)
game.call(76)
game.fold(77)
def testLastInGameDoesNotAct(self):
""" Test Poker Game: player folds (although he could check) while a player is allin and
another player is behind him. The turn ends now, the last player is not asked for his action.
"""
game = pokergame.PokerGameServer("poker.%s.xml", [path.join(TESTS_PATH, '../conf'), PokerGameTestCase.TestConfDirectory])
game.setVariant("holdem")
game.setBettingStructure("100-200_2000-20000_no-limit")
player = {}
money = {}
money[66] = 2000
money[76] = 30000
money[77] = 1000
for serial in (66, 76, 77):
self.assert_(game.addPlayer(serial))
player[serial] = game.serial2player[serial]
player[serial].money = 2000
player[serial].buy_in_payed = True
self.assert_(game.sit(serial))
#player[serial].auto_blind_ante = True
game.autoMuck(serial, pokergame.AUTO_MUCK_ALWAYS)
game.autoBlindAnte(serial)
player[serial].money = money[serial]
game.dealer_seat = 0
#
# 77: 4c 8c
# 76: 9s 4h
# 66: 3h Jh
#
game.deck = ['7c', 'Qs', '6c', 'Qc', '2h', '4h', 'Jh', '8c', '9s', '3h', '4c' ]
game.board = pokercards.PokerCards(['9c', '3d', '2d', 'Qd', 'Ah'])
# player list: [66, 76, 77]
# dealer: 66
game.beginTurn(1)
game.call(66)
game.call(76)
game.check(77)
self.assertEqual(game.state, "flop")
game.callNraise(76, 1500)
game.call(77)
game.call(66)
self.assertEqual(game.state, "turn")
game.fold(76)
self.assertEqual(game.state, "end")
def testAllInAndFoldInNewRound(self):
""" Test Poker Game: player folds to a raise when heads up
in a betting round. Another player was allin in the previous
round. The winner has an uncalled amount AND wins the pot
in which the allin player was not.
"""
game = pokergame.PokerGameServer("poker.%s.xml", [path.join(TESTS_PATH, '../conf'), PokerGameTestCase.TestConfDirectory])
game.setVariant("holdem")
game.setBettingStructure("100-200_2000-20000_no-limit")
player = {}
money = {}
money[66] = 2000
money[76] = 30000
money[77] = 1000
for serial in (66, 76, 77):
self.assert_(game.addPlayer(serial))
player[serial] = game.serial2player[serial]
player[serial].money = 2000
player[serial].buy_in_payed = True
self.assert_(game.sit(serial))
#player[serial].auto_blind_ante = True
game.autoMuck(serial, pokergame.AUTO_MUCK_ALWAYS)
game.autoBlindAnte(serial)
player[serial].money = money[serial]
game.dealer_seat = 0
#
# 77: 4c 8c
# 76: 9s Jd
# 66: 3h Jh
#
game.deck = ['7c', 'Qs', '6c', 'Qc', '2h', 'Jd', 'Jh', '8c', '9s', '3h', '4c' ]
game.board = pokercards.PokerCards(['9c', '3d', '2d', 'Qd', 'Ah'])
# player list: [66, 76, 77]
# dealer: 66
game.beginTurn(1)
game.call(66)
game.call(76)
game.check(77)
self.assertEqual(game.state, "flop")
game.callNraise(76, 1500)
game.call(77)
game.call(66)
self.assertEqual(game.state, "turn")
game.callNraise(76, 1500)
game.fold(66)
self.assertEqual(game.state, "end")
def testUpdateHistoryEnd(self):
game = self.game
game.turn_history = [("one",), ("two",), ("end",), ("three",)]
game.updateHistoryEnd(winners = "winners", showdown_stack = "showdown_stack")
self.assertEqual(("end", "winners", "showdown_stack"), game.turn_history[2])
def testEmtpyShowdownStack(self):
turn_history = [("end", [], []),]
pokergame.history2messages(None, turn_history)
def testPlayerListIndexAdd(self):
game = self.game
players = [
(100, True),
(101, True),
(102, False),
(103, False),
(104, True),
(105, False),
]
pred = lambda x: x[1]
game.player_list = [p[0] for p in players]
game.serial2player = dict((p[0],p) for p in players)
players_truey_count = len([p for p in players if pred(p)])
# positive without skip
self.assertEqual(1,game.playerListIndexAdd(0, 1, pred))
# positive with skip
self.assertEqual(4,game.playerListIndexAdd(1, 1, pred))
# positive with skip, position is falsy
self.assertEqual(4,game.playerListIndexAdd(2, 1, pred))
self.assertEqual(4,game.playerListIndexAdd(3, 1, pred))
# test loop over
self.assertEqual(0,game.playerListIndexAdd(3, 2, pred))
self.assertEqual(0,game.playerListIndexAdd(4, 1, pred))
# test simple negative
self.assertEqual(4,game.playerListIndexAdd(0, -1, pred))
self.assertEqual(4,game.playerListIndexAdd(5, -1, pred))
self.assertEqual(1,game.playerListIndexAdd(4, -1, pred))
# test too big for list, position is truey
self.assertEqual(0,game.playerListIndexAdd(4, 1+2*players_truey_count, pred))
self.assertEqual(0,game.playerListIndexAdd(4, 1-2*players_truey_count, pred))
# test too big for list, position is falsy
self.assertEqual(4,game.playerListIndexAdd(3, 1+2*players_truey_count, pred))
self.assertEqual(0,game.playerListIndexAdd(3, 1-2*players_truey_count, pred))
# test too big for list, position is falsy, gets itself
self.assertEqual(4,game.playerListIndexAdd(3, 4+2*players_truey_count, pred))
self.assertEqual(0,game.playerListIndexAdd(3, 4-2*players_truey_count, pred))
def testHistoryReduceAutoPlaySitInAndOut(self):
histories = []
self.game.variant = 'holdem'
self.game.setMaxPlayers(4)
player_serials = [100,200,300,400]
player_seats = [1,3,6,8]
players = {}
for (serial,seat) in zip(player_serials,player_seats):
players[serial] = self.AddPlayerAndSit(serial, seat)
self.game.noAutoBlindAnte(serial)
self.game.beginTurn(1)
self.failUnless(self.game.isBlindAnteRound())
self.game.blind(200)
if self.game.historyCanBeReduced(): self.game.historyReduce()
# . Table.playerTimeoutTimer
self.game.sitOutNextTurn(300)
self.game.autoPlayer(300)
if self.game.historyCanBeReduced(): self.game.historyReduce()
# . PACKET_POKER_TABLE_JOIN
# .. Avatar.performPacketPokerTableJoin
# ... PokerTable.joinPlayer
self.game.comeBack(300)
if self.game.historyCanBeReduced(): self.game.historyReduce()
# . PACKET_POKER_SIT_OUT
# .. Table.sitOutPlayer
self.game.sitOutNextTurn(300)
if self.game.historyCanBeReduced(): self.game.historyReduce()
# . PACKET_POKER_SIT
# .. Avatar.performPacketPokerSit
# ... Table.sitPlayer
# .... Avatar.sitPlayer
self.game.sit(300)
if self.game.historyCanBeReduced(): self.game.historyReduce()
# . PACKET_POKER_SIT_OUT
# .. Table.sitOutPlayer
self.game.sitOut(400)
if self.game.historyCanBeReduced(): self.game.historyReduce()
# 3 has to pay the blind now
self.game.blind(300)
if self.game.historyCanBeReduced(): self.game.historyReduce()
self.failUnless(self.game.isFirstRound())
history_reduced_should = [
('game', 0, 1, 0, 0, 'holdem', 'config', [100, 200, 300], 1, {200: 1600, 300: 1600, 100: 1600}),
('position', 1, 200), ('blind', 200, 500, 0),
('position', 2, 300),
('position', 0, 100),
('position', 2, 300), ('blind', 300, 1000, 0),
('position', -1, None),
('round', 'pre-flop', pokercards.PokerCards([]), {200: pokercards.PokerCards([193, 204]), 100: pokercards.PokerCards([237, 209]), 300: pokercards.PokerCards([243, 196])}),
('position', 0, 100)
]
history_reduced_is = self.game.historyGet()
self.assertEquals(
history_reduced_should, history_reduced_is,
"error in history reduction.\nreduced:\n %s\nshould_be:\n %s" % (
",\n ".join(map(str,history_reduced_is)),
",\n ".join(map(str,history_reduced_should))
)
)
def testHistoryReduceError(self):
self.game.variant = 'holdem'
self.game.setMaxPlayers(9)
player_serials = [100, 200, 300, 400, 500, 600, 700]
player_seats = [0, 1, 2, 3, 4, 5, 8]
players = {}
for (serial,seat) in zip(player_serials,player_seats):
players[serial] = self.AddPlayerAndSit(serial, seat)
self.game.noAutoBlindAnte(serial)
self.game.forced_dealer_seat = 2
self.game.beginTurn(1)
players[700].blind = 'late'
players[700].missed_blind = 'big'
self.game.blind(400)
if self.game.historyCanBeReduced(): self.game.historyReduce()
self.game.sitOutNextTurn(500)
if self.game.historyCanBeReduced(): self.game.historyReduce()
self.game.blind(600)
if self.game.historyCanBeReduced(): self.game.historyReduce()
self.game.blind(700)
if self.game.historyCanBeReduced(): self.game.historyReduce()
def testHistoryReduceWhenLeavingInBlind(self):
game = self.game
player_serials = [10,20]
game.variant = 'holdem'
game.setMaxPlayers(9)
players = {}
for serial in player_serials:
players[serial] = self.AddPlayerAndSit(serial)
game.noAutoBlindAnte(serial)
game.beginTurn(1)
game.blind(20)
game.sitOutNextTurn(20)
game.autoPlayer(20)
game.removePlayer(20)
game.blind(10)
game.historyReduce()
def testBlindAndAnteTogetherAllIn(self):
game = self.game
game.variant = 'holdem'
game.setMaxPlayers(9)
game.blind_info = False
game.blind_info = {'small': 20,'big': 40,'change': False}
game.ante_info = {'value': 1, 'bring-in': 5, 'change': False}
game.best_buy_in = 100
players = {}
serials = [10, 20]
money = [50, 100]
for s,m in zip(serials,money):
players[s] = self.AddPlayerAndSit(s)
game.autoBlindAnte(s)
players[s].money = m
game.beginTurn(1)
game.callNraise(20, 200)
game.call(10)
def testDistributeMoneyUnexpectedWinnerSerial(self):
game = self.game
game.variant = 'holdem'
game.setMaxPlayers(9)
game.blind_info = False
game.blind_info = {'small': 20,'big': 40,'change': False}
game.ante_info = None
game.best_buy_in = 100
players = {}
construction = {
1: {'seat':1, 'serial': 1, 'money': 18, 'blind':'big', 'missed_blind':None, 'wait_for':False},
3: {'seat':3, 'serial': 3, 'money': 2000, 'blind':'late', 'missed_blind':'small', 'wait_for':False},
4: {'seat':4, 'serial': 4, 'money': 2000, 'blind':False, 'missed_blind':None, 'wait_for':False},
5: {'seat':5, 'serial': 5, 'money': 2000, 'blind':'small', 'missed_blind':None, 'wait_for':False},
}
for info in construction.values():
s = info["serial"]
players[s] = self.AddPlayerAndSit(s, info['seat'])
players[s].money = info["money"]
players[s].missed_blind = info["missed_blind"]
game.dealer_seat = 3
game.first_turn = False
log_history.reset()
game.beginTurn(1)
for info in construction.values():
_p_ = game.serial2player[info['serial']]
self.assertEqual(_p_.blind, info['blind'], "player %s has blind %r but should have %r" % (_p_.serial, _p_.blind, info['blind']))
# Pay the blinds
i = 0
while game.state == "blindAnte":
i += 1
self.assertTrue(i <= 3, "Too many Blinds to pay")
player_serial = game.getSerialInPosition()
game.blind(player_serial)
self.assertTrue(players[player_serial].bet > 0)
game.fold(construction[3]['serial'])
game.fold(construction[4]['serial'])
game_state = game.showdown_stack[0]
self.assertEqual(game_state['type'], 'game_state')
self.assertEqual(len(game_state['side_pots']['contributions'][0].keys()), 3)
# the big blind wins twice his money minus the rake
self.assertEqual(game_state['serial2rake'][construction[1]['serial']], 1)
self.assertEqual(game_state['serial2delta'][construction[1]['serial']], 35)
self.assertEqual(game_state['serial2delta'][construction[5]['serial']], -17)
# the late blind only loses the small blind, because nobody called his late blind
self.assertEqual(game_state['serial2delta'][construction[3]['serial']], -20)
def testSitBeforeBlindAndAllSitOutAfterwards(self):
game = self.game
game.variant = 'holdem'
game.setMaxPlayers(9)
# add player 10
player10 = self.AddPlayerAndSit(10)
# add player 20, but don't get a seat just yet
self.assertTrue(game.addPlayer(20))
self.assertTrue(game.payBuyIn(20, game.bestBuyIn()))
player20 = self.GetPlayer(20)
# add player 30
player30 = self.AddPlayerAndSit(30)
# change the seat and begin the turn
game.forced_dealer_seat = 2
game.beginTurn(1)
# we did not activate autoblindante, so we are still in the blind ante round
self.assertTrue(game.isBlindAnteRound())
# before any blinds are payed, player 20 is seated
self.assertTrue(game.sit(20))
# pay small and big blinds
game.blind(10)
game.blind(30)
# the game should still be in the blindAnteRound, because player 20 is missing
self.assertTrue(game.isFirstRound())
# player 20 is set on auto, i.e. he folds, because we are still in blind/ante
game.autoPlayer(20)
# the game should be in its first round now
self.assertTrue(game.isFirstRound())
# the other players are set on autoplay and should now finish the round
game.fold(10)
self.assertTrue(game.isEndOrNull())
def _autoPlayTurn(self, actions={}, default_action='fold', additional_packets=None, expect=True):
state = self.game.state
if additional_packets:
for packet, args in additional_packets:
retval = getattr(self.game, packet)(*args)
self.game.log.debug( '%s > %s %r -> %r' % (state, packet, args, retval))
i = 0
while self.game.state == state:
i += 1
if i > 20: raise Exception('Loop')
player = self.game.getPlayerInPosition()
serial = player.serial
if isinstance(actions, dict):
action = actions.get(serial, default_action)
else:
action = actions[i]
if isinstance(action, (list, tuple)):
action, params = action
else:
params = ()
if action == 'raise':
action = 'callNraise'
retval = getattr(self.game,action)(serial,*params)
self.game.log.debug('%s > %s %s %r -> %s' %(state, action, serial, params, retval))
if retval in (True, False):
self.failUnless(retval == expect)
def _autoPlayInit(self):
clear_all_messages()
game = self.game
player_serials = [13,26]
game.variant = 'holdem'
game.setMaxPlayers(9)
players = {}
for serial in player_serials:
players[serial] = self.AddPlayerAndSit(serial)
players[serial].money = 2000000
players[serial].auto = False
game.noAutoBlindAnte(serial)
return players
def _autoPlay(self, additional_packets=(None, None, None, None), doitL=(None, None, None, None), expectedPlayers=2):
game = self.game
game.beginTurn(1)
self._autoPlayTurn(default_action='blind', expect=None)
doits = [
dict(actions={26:'autoPlayer', 13:('raise', (8,))}),
dict(actions={13:('raise', (9,)), 26:'call'}),
dict(actions={13:('raise', (19,)), 26:'call'}),
dict(actions={13:'check', 26:'check'}),
]
states = ['pre-flop','flop','turn','river']
for (doit,doitfallback,additional_packet,state) in zip(doitL,doits,additional_packets,states):
if state != game.state:
continue
doitdict = doit if doit else doitfallback
self._autoPlayTurn(additional_packets=additional_packet, **doitdict)
self.failUnless(expectedPlayers == self.game.sitCount())
def _didPlayerFold(self, player_id, allow_other_actions=True):
hist = self.game.historyGet()
player_folded = False
other_actions = False
for line in hist:
if line[1] == player_id:
if line[0] in ('call', 'check', 'raise'):
other_actions = True
if line[0] == 'fold':
player_folded = True
if player_folded:
if not allow_other_actions and other_actions:
return False
return True
return False
def testAutoPlayPlayerShouldFoldAsDefault(self):
self._autoPlayInit()
self._autoPlay(additional_packets=([('sitOutNextTurn',(26,)),],None,[('sit',(26,))]),expectedPlayers=1)
self.failIfEqual(self._didPlayerFold(26), False)
self.failUnless(self._didPlayerFold(26))
def testAutoPlayPlayerShouldBeAbleToGetBackToTheGameIfBotPolicyIsSet(self):
self._autoPlayInit()
self.game.serial2player[26].auto_policy = pokergame.AUTO_POLICY_BOT
self._autoPlay(additional_packets=([('sitOutNextTurn',(26,))],None,[('sit',(26,))]),expectedPlayers=2)
self.failIf(self._didPlayerFold(26))
def testAutoPlayShouldEndAfterOneHandTournament(self):
self._autoPlayInit()
self._autoPlay(expectedPlayers=2)
def testAutoPlayShouldEndAfterOneHand(self):
self._autoPlayInit()
self._autoPlay()
# ---------------------------------------------------------
def AddPlayerAndSit(self, serial, seat = -1):
self.failUnless(self.game.addPlayer(serial, seat))
self.failUnless(self.game.payBuyIn(serial,self.game.bestBuyIn()))
player = self.GetPlayer(serial)
self.failUnless(player.isBuyInPayed())
self.failUnless(self.game.sit(serial))
self.failUnless(self.game.isSit(serial))
return player
# ---------------------------------------------------------
def ModifyXMLFile(self, xml_file, parent, child, attributes = {}):
try:
doc = libxml2.parseFile(xml_file)
except libxml2.parserError:
return False
header = doc.xpathNewContext()
node_parent = doc.getRootElement()
if parent:
nodes = header.xpathEval(parent)
if nodes: node_parent = nodes[0]
else: return False
node = node_parent
if child:
node = node_parent.newChild(ns = None, name = child, content = None)
for attribute_name, attribute_value in attributes.items():
if not node.hasProp(attribute_name):
node.newProp(attribute_name,attribute_value)
else:
for property in node.properties:
if property.name == attribute_name: property.setContent(attribute_value)
doc.saveFile(xml_file)
doc.freeDoc()
header.xpathFreeContext()
return True
# ---------------------------------------------------------
def CopyFile(self, src_path, dst_path):
if src_path and not path.isfile(src_path):
return False
shutil.copyfile(src_path,dst_path)
if path.isfile(dst_path):
return True
return False
# ---------------------------------------------------------
def DeleteFile(self, file_path):
if path.isfile(file_path):
os.unlink(file_path)
# ---------------------------------------------------------
def GetPlayer(self, serial):
player = self.game.getPlayer(serial)
self.failIfEqual(player, None)
return player
# ---------------------------------------------------------
def CreateGameClient(self):
if not self.CopyFile(self.ConfigTmplFile, self.ConfigTempFile):
self.fail('Error during creation of configuration file ' + self.ConfigTempFile)
self.game = pokergame.PokerGameClient(PokerGameTestCase.TestUrl, [PokerGameTestCase.TestConfDirectory, tempfile.gettempdir()])
# ---------------------------------------------------------
def CreateGameServer(self):
if not self.CopyFile(self.ConfigTmplFile, self.ConfigTempFile):
self.fail('Error during creation of configuration file ' + self.ConfigTempFile)
self.game = pokergame.PokerGameServer(PokerGameTestCase.TestUrl, [PokerGameTestCase.TestConfDirectory, tempfile.gettempdir()])
# ---------------------------------------------------------
def InitGame(self):
self.game.setTime(0)
if not self.CopyFile(self.VariantTmplFile, self.VariantTempFile):
self.fail('Error during creation of variant file ' + self.VariantTempFile)
self.game.setVariant(PokerGameTestCase.TestVariantTemporaryFile)
# Reload the betting structure
self.game.setBettingStructure(PokerGameTestCase.TestConfigTemporaryFile)
self.game.setMaxPlayers(2)
self.game.id = 4
predefined_decks = string.split("8d 2h 2c 8c 4c Kc Ad 9d Ts Jd 5h Tc 4d 9h 8h 7h 9c 2s 3c Kd 5s Td 5d Th 3s Kh Js Qh 7d 2d 3d 9s Qd Ac Jh Jc Qc 6c 7s Ks 5c 4h 7c 4s Qs 6s 6h Ah 6d As 3h 8s")
shuffler = PokerPredefinedDecks([map(lambda card: self.game.eval.string2card(card), predefined_decks)])
self.game.deck = predefined_decks
self.game.shuffler = shuffler
# ---------------------------------------------------------
def GetTestSuite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(PokerGameTestCase))
# suite.addTest(unittest.makeSuite(PokerGameTestCase, prefix = "test2"))
return suite
# ---------------------------------------------------------
def GetTestedModule():
return pokergame
# ---------------------------------------------------------
def run():
return unittest.TextTestRunner().run(GetTestSuite())
# ---------------------------------------------------------
if __name__ == '__main__':
if run().wasSuccessful():
sys.exit(0)
else:
sys.exit(1)
# Interpreted by emacs
# Local Variables:
# compile-command: "( cd .. ; ./config.status tests/test-game.py ) ; ( cd ../tests ; make COVERAGE_FILES='../pokerengine/pokergame.py' TESTS='coverage-reset test-game.py coverage-report' check )"
# End:
| pokermania/pokerengine | tests/test_game.py | Python | gpl-3.0 | 244,876 | 0.009131 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import xmltodict
from bs4 import BeautifulSoup
from bs4 import CData
UPLOAD_DIR = '../html/uploads'
METADATA_NAME = 'metadata.xml'
PUBLISHER_NAME = 'Heidelberg University Press'
PUBLISHER_LOC = 'Heidelberg'
jsondata = [{'selected': True, 'type': 'book'}]
def predictTagset(d):
if(d.has_key('metadata')):
if (d['metadata'].has_key('front')):
return 'article'
elif(d['metadata'].has_key('book-meta')):
return 'book'
elif(d.has_key('article')):
return 'article'
elif(d.has_key('book')):
return 'book'
else:
return ''
def validate(xmldict):
if(xmldict['tagset'] == 'article'):
if not(xmldict['article']['front']['journal-meta'].has_key('publisher')):
xmldict['article']['front']['journal-meta']['publisher'] = {'publisher-name' : PUBLISHER_NAME, 'publisher-loc': PUBLISHER_LOC}
else:
if not (xmldict['article']['front']['journal-meta']['publisher'].has_key('publisher_loc')):
xmldict['article']['front']['journal-meta']['publisher']['publisher_loc'] = PUBLISHER_LOC
if not(xmldict['article']['front']['journal-meta'].has_key('journal-title-group')):
if (isinstance(xmldict['article']['front']['journal-meta']['journal-id'], str)):
xmldict['article']['front']['journal-meta']['journal-id'] = {'@pub-type': 'epub', '#text': xmldict['article']['front']['journal-meta']['journal-id']}
xmldict['article']['front']['journal-meta']['journal-title-group'] = {'journal-title': xmldict['article']['front']['journal-meta']['journal-id']['#text']}
if(xmldict['article']['front']['article-meta'].has_key('contrib-group')):
if not(isinstance(xmldict['article']['front']['article-meta']['contrib-group'], list)):
xmldict['article']['front']['article-meta']['contrib-group'] = [xmldict['article']['front']['article-meta']['contrib-group']]
elif(mxldict['tagset'] == 'book'):
if(xmldict['book']['book-meta'].has_key('contrib-group')):
if not(isinstance(xmldict['book']['book-meta']['contrib-group'], list)):
xmldict['book']['book-meta']['contrib-group'] = [xmldict['book']['book-meta']['contrib-group']]
return xmldict
def escape(xml):
soup = BeautifulSoup(xml, 'xml', from_encoding='utf-8')
for i in soup.find_all('p'):
if i.string is None:
string = ''.join([str(j) for j in i.contents])
cdata = CData(string)
i.string = ''
i.string.replace_with(cdata)
for i in soup.find_all('mixed-citation'):
if i.string is None:
string = ''.join([str(j) for j in i.contents])
cdata = CData(string)
i.string = ''
i.string.replace_with(cdata)
return str(soup)
for root, dirs, files in os.walk(UPLOAD_DIR):
if(METADATA_NAME in files):
xmldata = open(root+"/"+METADATA_NAME).read()
xmldata = escape(xmldata)
xmldict = xmltodict.parse(xmldata)
tagset = predictTagset(xmldict)
xmldict['tagset'] = tagset
xmldict['id'] = root.split('/')[-1]
xmldict[tagset] = xmldict['metadata']
del xmldict['metadata']
xmldict = validate(xmldict)
jsondata[0].update(xmldict)
if('xml' in dirs):
xmlfiles = os.listdir(root+"/xml")
for xml in xmlfiles:
xmldata = open(root+"/xml/"+xml)
xmldata = escape(xmldata)
xmldict = xmltodict.parse(xmldata)
xmldict['selected'] = False
xmldict['type'] = 'file'
xmldict['tagset'] = predictTagset(xmldict)
filename = os.path.splitext(xml)[0]
xmldict['id'] = filename
xmldict = validate(xmldict)
jsondata.append(xmldict)
break
#with open('test.json', 'w+') as f:
# json.dump(jsondata, f, sort_keys=False, indent=4)
print "Content-type: application/json\n\n"
print json.JSONEncoder().encode(jsondata)
print | withanage/HEIDIEditor | static/WysiwigEditor/cgi/createJSON.py | Python | gpl-3.0 | 4,094 | 0.006839 |
#!/usr/bin/env python
#
# Copyright 2016 Hannes Juutilainen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import subprocess
import json
import hashlib
import time
from autopkglib import Processor, ProcessorError
__all__ = ["VirusTotalAnalyzer"]
# VirusTotal was kind enough to give this processor its own API key so that it can be
# used as-is without further configuring. Please don't abuse this.
DEFAULT_API_KEY = "3858a94a911f47707717f6d090dbb8f86badb750b0f7bfe74a55c0c6143e3de6"
# Default options
DEFAULT_SLEEP = 15
ALWAYS_REPORT_DEFAULT = False
AUTO_SUBMIT_DEFAULT = False
AUTO_SUBMIT_MAX_SIZE_DEFAULT = 419430400 # 400MB
class VirusTotalAnalyzer(Processor):
"""Queries VirusTotal database for information about the given file"""
input_variables = {
"pathname": {
"required": False,
"description": "File path to analyze.",
},
"VIRUSTOTAL_ALWAYS_REPORT": {
"required": False,
"description": "Always request a report instead of only for new downloads",
},
"VIRUSTOTAL_AUTO_SUBMIT": {
"required": False,
"description": "If item is not found in VirusTotal database, automatically submit it for scanning.",
},
"CURL_PATH": {
"required": False,
"default": "/usr/bin/curl",
"description": "Path to curl binary. Defaults to /usr/bin/curl.",
},
}
output_variables = {
"virus_total_analyzer_summary_result": {
"description": "Description of interesting results."
},
}
description = __doc__
def fetch_content(self, url, headers=None, form_parameters=None, data_parameters=None, curl_options=None):
"""Returns content retrieved by curl, given an url and an optional
dictionaries of header-name/value mappings and parameters.
Logic here borrowed from URLTextSearcher processor.
Keyword arguments:
:param url: The URL to fetch
:type url: str None
:param headers: Dictionary of header-names and values
:type headers: dict None
:param form_parameters: Dictionary of items for '--form'
:type form_parameters: dict None
:param data_parameters: Dictionary of items for '--data'
:type data_parameters: dict None
:param curl_options: Array of arguments to pass to curl
:type curl_options: list None
:returns: content as string
"""
try:
cmd = [self.env['CURL_PATH'], '--location']
if curl_options:
cmd.extend(curl_options)
if headers:
for header, value in headers.items():
cmd.extend(['--header', '%s: %s' % (header, value)])
if form_parameters:
for form_parameter, value in form_parameters.items():
cmd.extend(['--form', '%s=%s' % (form_parameter, value)])
if data_parameters:
for data_parameter, value in data_parameters.items():
cmd.extend(['--data', '%s=%s' % (data_parameter, value)])
cmd.append(url)
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(data, stderr) = proc.communicate()
if proc.returncode:
raise ProcessorError(
'Could not retrieve URL %s: %s' % (url, stderr))
except OSError:
raise ProcessorError('Could not retrieve URL: %s' % url)
return data
def submit_file(self, file_path, api_key):
"""Submit a file to VirusTotal for scanning
:param file_path: Path to a file to upload
:param api_key: API key to use
:returns: JSON response
"""
url = "https://www.virustotal.com/vtapi/v2/file/scan/upload_url"
# Get the upload URL
parameters = {"apikey": api_key}
f = self.fetch_content(url, None, None, parameters, ["-G"])
try:
json_data = json.loads(f)
except (ValueError, KeyError, TypeError) as e:
self.output("Response was: %s" % f)
self.output("JSON format error: %s" % e)
json_data = json.loads(
'{"response_code": 999, "verbose_msg": "Requesting upload URL failed..."}')
return json_data
upload_url = json_data.get('upload_url', None)
if upload_url is None:
return None
# Upload the file
file_path_for_post = "@%s" % file_path
parameters = {"file": file_path_for_post, "apikey": api_key}
f = self.fetch_content(upload_url, None, parameters)
try:
json_data = json.loads(f)
except (ValueError, KeyError, TypeError) as e:
self.output("Response was: %s" % f)
self.output("JSON format error: %s" % e)
json_data = json.loads(
'{"response_code": 999, "verbose_msg": "Request failed, perhaps rate-limited..."}')
# print json.dumps(json_data, sort_keys=True, indent=4)
return json_data
def report_for_hash(self, file_hash, api_key):
"""Request a VirusTotal report for a hash
:param file_hash: md5, sha1 or sha256 hash
:param api_key: API key to use
:returns: JSON response
"""
url = "https://www.virustotal.com/vtapi/v2/file/report"
parameters = {"resource": file_hash, "apikey": api_key}
f = self.fetch_content(url, None, parameters)
try:
json_data = json.loads(f)
except (ValueError, KeyError, TypeError) as e:
self.output("JSON response was: %s" % f)
self.output("JSON format error: %s" % e)
json_data = json.loads(
'{"response_code": 999, "verbose_msg": "Request failed, perhaps rate-limited..."}')
# print json.dumps(json_data, sort_keys=True, indent=4)
return json_data
def calculate_sha256(self, file_path):
"""Calculates a SHA256 checksum
http://stackoverflow.com/a/3431838
:param file_path:
"""
hash_sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
def main(self):
if self.env.get("VIRUSTOTAL_DISABLED", False):
self.output("Skipped VirusTotal analysis...")
return
input_path = self.env.get("pathname", None)
if not input_path:
self.output("Skipping VirusTotal analysis: no input path defined.")
return
# Get variables and arguments
sleep_seconds = int(self.env.get("VIRUSTOTAL_SLEEP_SECONDS", DEFAULT_SLEEP))
auto_submit = self.env.get("VIRUSTOTAL_AUTO_SUBMIT", AUTO_SUBMIT_DEFAULT)
auto_submit_max_size = int(self.env.get("VIRUSTOTAL_AUTO_SUBMIT_MAX_SIZE", AUTO_SUBMIT_MAX_SIZE_DEFAULT))
api_key = self.env.get("VIRUSTOTAL_API_KEY", DEFAULT_API_KEY)
if not api_key or api_key == "":
raise ProcessorError("No API key available")
force_report = self.env.get("VIRUSTOTAL_ALWAYS_REPORT",
ALWAYS_REPORT_DEFAULT)
if "download_changed" in self.env:
if not self.env["download_changed"] and not force_report:
# URLDownloader did not download new items,
# so skip the analysis
self.output("Skipping VirusTotal analysis: no new download.")
self.env["virustotal_result"] = "SKIPPED"
return
# Calculate the SHA256 hash of the file for submitting
self.output("Calculating checksum for %s" % input_path)
input_path_hash = self.calculate_sha256(input_path)
try:
last_virus_total_request = int(
os.environ.get('AUTOPKG_VIRUSTOTAL_LAST_RUN_TIME', 0))
except ValueError:
last_virus_total_request = 0
if last_virus_total_request and sleep_seconds > 0:
now = int(time.time())
next_time = last_virus_total_request + sleep_seconds
if now < next_time:
sleep_time = next_time - now
self.output(
"Sleeping %s seconds before requesting report..."
% sleep_time)
time.sleep(sleep_time)
# Request details for the calculated hash
self.output("Requesting report...")
json_data = self.report_for_hash(input_path_hash, api_key)
# Parse the report
response_code = json_data.get("response_code", None)
self.output("Response code: %s" % response_code)
if response_code == 0:
# VirusTotal database did not have a match for this hash
self.output("No information found for %s" % input_path)
if not auto_submit:
self.output(
"Consider submitting the file for analysis at https://www.virustotal.com/")
else:
if os.path.getsize(input_path) < auto_submit_max_size:
self.output("Submitting the file for analysis...")
json_data = self.submit_file(input_path, api_key)
response_code = json_data.get("response_code", None)
self.output("Response code: %s" % response_code)
verbose_msg = json_data.get("verbose_msg", None)
scan_id = json_data.get("scan_id", None)
permalink = json_data.get("permalink", None)
self.output("Message: %s" % verbose_msg)
self.output("Scan ID: %s" % scan_id)
self.output("Permalink: %s" % permalink)
else:
self.output("File is too large to submit...")
elif response_code == 1:
# VirusTotal gave us details about the file
verbose_msg = json_data.get("verbose_msg", None)
scan_id = json_data.get("scan_id", None)
num_positives = json_data.get("positives", 0)
num_total = json_data.get("total", 0)
scan_date = json_data.get("scan_date", None)
permalink = json_data.get("permalink", None)
self.output("Message: %s" % verbose_msg)
self.output("Scan ID: %s" % scan_id)
self.output("Detection ratio: %s/%s" % (num_positives, num_total))
self.output("Scan date: %s" % scan_date)
self.output("Permalink: %s" % permalink)
elif response_code == -2:
# Requested item is still queued for analysis
verbose_msg = json_data.get("verbose_msg", None)
scan_id = json_data.get("scan_id", None)
permalink = json_data.get("permalink", None)
self.output("Message: %s" % verbose_msg)
self.output("Scan ID: %s" % scan_id)
self.output("Permalink: %s" % permalink)
# Extract the information we need for the summary results
num_positives = json_data.get("positives", 0)
num_total = json_data.get("total", 0)
permalink = json_data.get("permalink", "None")
# record our time -- we use this to throttle our frequency
os.environ['AUTOPKG_VIRUSTOTAL_LAST_RUN_TIME'] = str(int(time.time()))
# Save summary result
self.env["virus_total_analyzer_summary_result"] = {
'summary_text': 'The following items were queried from the VirusTotal database:',
'report_fields': [
'name',
'ratio',
'permalink',
],
'data': {
'name': os.path.basename(input_path),
'ratio': "%s/%s" % (num_positives, num_total),
'permalink': permalink,
}
}
if __name__ == "__main__":
processor = VirusTotalAnalyzer()
processor.execute_shell()
| hjuutilainen/autopkg-virustotalanalyzer | VirusTotalAnalyzer/VirusTotalAnalyzer.py | Python | apache-2.0 | 12,577 | 0.001193 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('builder', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='problem',
name='date_start',
field=models.DateTimeField(null=True, blank=True),
),
migrations.AlterField(
model_name='problem',
name='date_stop',
field=models.DateTimeField(null=True, blank=True),
),
]
| kopringo/Scarky2 | Scarky2/builder/migrations/0002_auto_20150505_2035.py | Python | mit | 577 | 0 |
from .... import base
from pulp.devel import mock_plugins
from pulp.plugins.conduits.dependency import DependencyResolutionConduit
from pulp.plugins.config import PluginCallConfiguration
from pulp.plugins.types import database, model
from pulp.server.db.model.criteria import UnitAssociationCriteria
from pulp.server.db.model.repository import Repo, RepoImporter, RepoContentUnit
from pulp.server.exceptions import MissingResource
from pulp.server.managers import factory as manager_factory
TYPE_1_DEF = model.TypeDefinition('type-1', 'Type 1', 'Test Definition One',
['key-1'], ['search-1'], [])
class DependencyManagerTests(base.PulpServerTests):
def setUp(self):
super(DependencyManagerTests, self).setUp()
mock_plugins.install()
database.update_database([TYPE_1_DEF])
self.repo_id = 'dep-repo'
self.manager = manager_factory.dependency_manager()
manager_factory.repo_manager().create_repo(self.repo_id)
manager_factory.repo_importer_manager().set_importer(self.repo_id, 'mock-importer', {})
def tearDown(self):
super(DependencyManagerTests, self).tearDown()
mock_plugins.reset()
def clean(self):
super(DependencyManagerTests, self).clean()
database.clean()
Repo.get_collection().remove()
RepoImporter.get_collection().remove()
RepoContentUnit.get_collection().remove()
mock_plugins.MOCK_IMPORTER.resolve_dependencies.return_value = None
def test_resolve_dependencies_by_unit(self):
# Setup
report = 'dep report'
mock_plugins.MOCK_IMPORTER.resolve_dependencies.return_value = report
unit_id_1 = manager_factory.content_manager().add_content_unit('type-1', None,
{'key-1': 'v1'})
unit_id_2 = manager_factory.content_manager().add_content_unit('type-1', None,
{'key-1': 'v2'})
association_manager = manager_factory.repo_unit_association_manager()
association_manager.associate_unit_by_id(self.repo_id, 'type-1', unit_id_1)
association_manager.associate_unit_by_id(self.repo_id, 'type-1', unit_id_2)
# Test
result = self.manager.resolve_dependencies_by_units(self.repo_id, [], {})
# Verify
self.assertEqual(result, report)
self.assertEqual(1, mock_plugins.MOCK_IMPORTER.resolve_dependencies.call_count)
args = mock_plugins.MOCK_IMPORTER.resolve_dependencies.call_args[0]
self.assertEqual(args[0].id, self.repo_id)
self.assertEqual(len(args[1]), 0)
self.assertTrue(isinstance(args[2], DependencyResolutionConduit))
self.assertTrue(isinstance(args[3], PluginCallConfiguration))
def test_resolve_dependencies_by_unit_no_repo(self):
# Test
self.assertRaises(MissingResource, self.manager.resolve_dependencies_by_units, 'foo', [],
{})
def test_resolve_dependencies_by_unit_no_importer(self):
# Setup
manager_factory.repo_manager().create_repo('empty')
# Test
self.assertRaises(MissingResource, self.manager.resolve_dependencies_by_units, 'empty', [],
{})
def test_resolve_dependencies_by_criteria(self):
# Setup
report = 'dep report'
mock_plugins.MOCK_IMPORTER.resolve_dependencies.return_value = report
unit_id_1 = manager_factory.content_manager().add_content_unit('type-1', None,
{'key-1': 'unit-id-1'})
unit_id_2 = manager_factory.content_manager().add_content_unit('type-1', None,
{'key-1': 'dep-1'})
association_manager = manager_factory.repo_unit_association_manager()
association_manager.associate_unit_by_id(self.repo_id, 'type-1', unit_id_1)
association_manager.associate_unit_by_id(self.repo_id, 'type-1', unit_id_2)
criteria = UnitAssociationCriteria(type_ids=['type-1'], unit_filters={'key-1': 'unit-id-1'})
# Test
result = self.manager.resolve_dependencies_by_criteria(self.repo_id, criteria, {})
# Verify
self.assertEqual(report, result)
self.assertEqual(1, mock_plugins.MOCK_IMPORTER.resolve_dependencies.call_count)
args = mock_plugins.MOCK_IMPORTER.resolve_dependencies.call_args[0]
self.assertEqual(1, len(args[1]))
| credativ/pulp | server/test/unit/server/managers/repo/test_dependency.py | Python | gpl-2.0 | 4,601 | 0.004347 |
#
# 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.
import os
from typing import Dict, Optional, Sequence
from airflow.compat.functools import cached_property
from airflow.exceptions import AirflowException, AirflowSkipException
from airflow.hooks.subprocess import SubprocessHook
from airflow.models import BaseOperator
from airflow.utils.context import Context
from airflow.utils.operator_helpers import context_to_airflow_vars
class BashOperator(BaseOperator):
r"""
Execute a Bash script, command or set of commands.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BashOperator`
If BaseOperator.do_xcom_push is True, the last line written to stdout
will also be pushed to an XCom when the bash command completes
:param bash_command: The command, set of commands or reference to a
bash script (must be '.sh') to be executed. (templated)
:type bash_command: str
:param env: If env is not None, it must be a dict that defines the
environment variables for the new process; these are used instead
of inheriting the current process environment, which is the default
behavior. (templated)
:type env: dict
:param append_env: If False(default) uses the environment variables passed in env params
and does not inherit the current process environment. If True, inherits the environment variables
from current passes and then environment variable passed by the user will either update the existing
inherited environment variables or the new variables gets appended to it
:type append_env: bool
:param output_encoding: Output encoding of bash command
:type output_encoding: str
:param skip_exit_code: If task exits with this exit code, leave the task
in ``skipped`` state (default: 99). If set to ``None``, any non-zero
exit code will be treated as a failure.
:type skip_exit_code: int
:param cwd: Working directory to execute the command in.
If None (default), the command is run in a temporary directory.
:type cwd: str
Airflow will evaluate the exit code of the bash command. In general, a non-zero exit code will result in
task failure and zero will result in task success. Exit code ``99`` (or another set in ``skip_exit_code``)
will throw an :class:`airflow.exceptions.AirflowSkipException`, which will leave the task in ``skipped``
state. You can have all non-zero exit codes be treated as a failure by setting ``skip_exit_code=None``.
.. list-table::
:widths: 25 25
:header-rows: 1
* - Exit code
- Behavior
* - 0
- success
* - `skip_exit_code` (default: 99)
- raise :class:`airflow.exceptions.AirflowSkipException`
* - otherwise
- raise :class:`airflow.exceptions.AirflowException`
.. note::
Airflow will not recognize a non-zero exit code unless the whole shell exit with a non-zero exit
code. This can be an issue if the non-zero exit arises from a sub-command. The easiest way of
addressing this is to prefix the command with ``set -e;``
Example:
.. code-block:: python
bash_command = "set -e; python3 script.py '{{ next_execution_date }}'"
.. note::
Add a space after the script name when directly calling a ``.sh`` script with the
``bash_command`` argument -- for example ``bash_command="my_script.sh "``. This
is because Airflow tries to apply load this file and process it as a Jinja template to
it ends with ``.sh``, which will likely not be what most users want.
.. warning::
Care should be taken with "user" input or when using Jinja templates in the
``bash_command``, as this bash operator does not perform any escaping or
sanitization of the command.
This applies mostly to using "dag_run" conf, as that can be submitted via
users in the Web UI. Most of the default template variables are not at
risk.
For example, do **not** do this:
.. code-block:: python
bash_task = BashOperator(
task_id="bash_task",
bash_command='echo "Here is the message: \'{{ dag_run.conf["message"] if dag_run else "" }}\'"',
)
Instead, you should pass this via the ``env`` kwarg and use double-quotes
inside the bash_command, as below:
.. code-block:: python
bash_task = BashOperator(
task_id="bash_task",
bash_command="echo \"here is the message: '$message'\"",
env={"message": '{{ dag_run.conf["message"] if dag_run else "" }}'},
)
"""
template_fields: Sequence[str] = ('bash_command', 'env')
template_fields_renderers = {'bash_command': 'bash', 'env': 'json'}
template_ext: Sequence[str] = (
'.sh',
'.bash',
)
ui_color = '#f0ede4'
def __init__(
self,
*,
bash_command: str,
env: Optional[Dict[str, str]] = None,
append_env: bool = False,
output_encoding: str = 'utf-8',
skip_exit_code: int = 99,
cwd: Optional[str] = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.bash_command = bash_command
self.env = env
self.output_encoding = output_encoding
self.skip_exit_code = skip_exit_code
self.cwd = cwd
self.append_env = append_env
if kwargs.get('xcom_push') is not None:
raise AirflowException("'xcom_push' was deprecated, use 'BaseOperator.do_xcom_push' instead")
@cached_property
def subprocess_hook(self):
"""Returns hook for running the bash command"""
return SubprocessHook()
def get_env(self, context):
"""Builds the set of environment variables to be exposed for the bash command"""
system_env = os.environ.copy()
env = self.env
if env is None:
env = system_env
else:
if self.append_env:
system_env.update(env)
env = system_env
airflow_context_vars = context_to_airflow_vars(context, in_env_var_format=True)
self.log.debug(
'Exporting the following env vars:\n%s',
'\n'.join(f"{k}={v}" for k, v in airflow_context_vars.items()),
)
env.update(airflow_context_vars)
return env
def execute(self, context: Context):
if self.cwd is not None:
if not os.path.exists(self.cwd):
raise AirflowException(f"Can not find the cwd: {self.cwd}")
if not os.path.isdir(self.cwd):
raise AirflowException(f"The cwd {self.cwd} must be a directory")
env = self.get_env(context)
result = self.subprocess_hook.run_command(
command=['bash', '-c', self.bash_command],
env=env,
output_encoding=self.output_encoding,
cwd=self.cwd,
)
if self.skip_exit_code is not None and result.exit_code == self.skip_exit_code:
raise AirflowSkipException(f"Bash command returned exit code {self.skip_exit_code}. Skipping.")
elif result.exit_code != 0:
raise AirflowException(
f'Bash command failed. The command returned a non-zero exit code {result.exit_code}.'
)
return result.output
def on_kill(self) -> None:
self.subprocess_hook.send_sigterm()
| mistercrunch/airflow | airflow/operators/bash.py | Python | apache-2.0 | 8,272 | 0.003264 |
# -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2013 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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 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 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/>.
#
from django.shortcuts import render_to_response, get_object_or_404
from django.views.decorators.cache import cache_page
from weblate.trans import appsettings
from django.core.servers.basehttp import FileWrapper
from django.utils.translation import ugettext as _
import django.utils.translation
from django.template import RequestContext, loader
from django.http import (
HttpResponse, HttpResponseRedirect, HttpResponseNotFound, Http404
)
from django.contrib import messages
from django.contrib.auth.decorators import (
login_required, permission_required, user_passes_test
)
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q, Count, Sum
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.utils.safestring import mark_safe
from weblate.trans.models import (
Project, SubProject, Translation, Unit, Suggestion, Check,
Dictionary, Change, Comment, get_versions
)
from weblate.lang.models import Language
from weblate.trans.checks import CHECKS
from weblate.trans.forms import (
TranslationForm, UploadForm, SimpleUploadForm, ExtraUploadForm, SearchForm,
MergeForm, AutoForm, WordForm, DictUploadForm, ReviewForm, LetterForm,
AntispamForm, CommentForm
)
from weblate.trans.util import join_plural
from weblate.accounts.models import Profile, send_notification_email
import weblate
from whoosh.analysis import StandardAnalyzer, StemmingAnalyzer
import datetime
import logging
import os.path
import json
import csv
from xml.etree import ElementTree
import urllib2
# See https://code.djangoproject.com/ticket/6027
class FixedFileWrapper(FileWrapper):
def __iter__(self):
self.filelike.seek(0)
return self
logger = logging.getLogger('weblate')
def home(request):
'''
Home page of Weblate showing list of projects, stats
and user links if logged in.
'''
projects = Project.objects.all_acl(request.user)
acl_projects = projects
if projects.count() == 1:
projects = SubProject.objects.filter(project=projects[0])
# Warn about not filled in username (usually caused by migration of
# users from older system
if not request.user.is_anonymous() and request.user.get_full_name() == '':
messages.warning(
request,
_('Please set your full name in your profile.')
)
# Load user translations if user is authenticated
usertranslations = None
if request.user.is_authenticated():
profile = request.user.get_profile()
usertranslations = Translation.objects.filter(
language__in=profile.languages.all()
).order_by(
'subproject__project__name', 'subproject__name'
)
# Some stats
top_translations = Profile.objects.order_by('-translated')[:10]
top_suggestions = Profile.objects.order_by('-suggested')[:10]
last_changes = Change.objects.filter(
translation__subproject__project__in=acl_projects,
).order_by( '-timestamp')[:10]
return render_to_response('index.html', RequestContext(request, {
'projects': projects,
'top_translations': top_translations,
'top_suggestions': top_suggestions,
'last_changes': last_changes,
'last_changes_rss': reverse('rss'),
'usertranslations': usertranslations,
}))
def show_checks(request):
'''
List of failing checks.
'''
allchecks = Check.objects.filter(
ignore=False
).values('check').annotate(count=Count('id'))
return render_to_response('checks.html', RequestContext(request, {
'checks': allchecks,
'title': _('Failing checks'),
}))
def show_check(request, name):
'''
Details about failing check.
'''
try:
check = CHECKS[name]
except KeyError:
raise Http404('No check matches the given query.')
checks = Check.objects.filter(
check=name, ignore=False
).values('project__slug').annotate(count=Count('id'))
return render_to_response('check.html', RequestContext(request, {
'checks': checks,
'title': check.name,
'check': check,
}))
def show_check_project(request, name, project):
'''
Show checks failing in a project.
'''
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
try:
check = CHECKS[name]
except KeyError:
raise Http404('No check matches the given query.')
units = Unit.objects.none()
if check.target:
langs = Check.objects.filter(
check=name, project=prj, ignore=False
).values_list('language', flat=True).distinct()
for lang in langs:
checks = Check.objects.filter(
check=name, project=prj, language=lang, ignore=False
).values_list('checksum', flat=True)
res = Unit.objects.filter(
checksum__in=checks,
translation__language=lang,
translation__subproject__project=prj,
translated=True
).values(
'translation__subproject__slug',
'translation__subproject__project__slug'
).annotate(count=Count('id'))
units |= res
if check.source:
checks = Check.objects.filter(
check=name,
project=prj,
language=None,
ignore=False
).values_list(
'checksum', flat=True
)
for subproject in prj.subproject_set.all():
lang = subproject.translation_set.all()[0].language
res = Unit.objects.filter(
checksum__in=checks,
translation__language=lang,
translation__subproject=subproject
).values(
'translation__subproject__slug',
'translation__subproject__project__slug'
).annotate(count=Count('id'))
units |= res
return render_to_response('check_project.html', RequestContext(request, {
'checks': units,
'title': '%s/%s' % (prj.__unicode__(), check.name),
'check': check,
'project': prj,
}))
def show_check_subproject(request, name, project, subproject):
'''
Show checks failing in a subproject.
'''
subprj = get_object_or_404(
SubProject,
slug=subproject,
project__slug=project
)
subprj.check_acl(request)
try:
check = CHECKS[name]
except KeyError:
raise Http404('No check matches the given query.')
units = Unit.objects.none()
if check.target:
langs = Check.objects.filter(
check=name,
project=subprj.project,
ignore=False
).values_list(
'language', flat=True
).distinct()
for lang in langs:
checks = Check.objects.filter(
check=name,
project=subprj.project,
language=lang,
ignore=False
).values_list('checksum', flat=True)
res = Unit.objects.filter(
translation__subproject=subprj,
checksum__in=checks,
translation__language=lang,
translated=True
).values(
'translation__language__code'
).annotate(count=Count('id'))
units |= res
source_checks = []
if check.source:
checks = Check.objects.filter(
check=name, project=subprj.project,
language=None,
ignore=False
).values_list('checksum', flat=True)
lang = subprj.translation_set.all()[0].language
res = Unit.objects.filter(
translation__subproject=subprj,
checksum__in=checks,
translation__language=lang
).count()
if res > 0:
source_checks.append(res)
return render_to_response(
'check_subproject.html',
RequestContext(request, {
'checks': units,
'source_checks': source_checks,
'anychecks': len(units) + len(source_checks) > 0,
'title': '%s/%s' % (subprj.__unicode__(), check.name),
'check': check,
'subproject': subprj,
})
)
def show_languages(request):
return render_to_response('languages.html', RequestContext(request, {
'languages': Language.objects.have_translation(),
'title': _('Languages'),
}))
def show_language(request, lang):
obj = get_object_or_404(Language, code=lang)
last_changes = Change.objects.filter(
translation__language=obj
).order_by('-timestamp')[:10]
dicts = Dictionary.objects.filter(
language=obj
).values_list('project', flat=True).distinct()
return render_to_response('language.html', RequestContext(request, {
'object': obj,
'last_changes': last_changes,
'last_changes_rss': reverse('rss-language', kwargs={'lang': obj.code}),
'dicts': Project.objects.filter(id__in=dicts),
}))
def show_dictionaries(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
dicts = Translation.objects.filter(
subproject__project=obj
).values_list('language', flat=True).distinct()
return render_to_response('dictionaries.html', RequestContext(request, {
'title': _('Dictionaries'),
'dicts': Language.objects.filter(id__in=dicts),
'project': obj,
}))
@login_required
@permission_required('trans.change_dictionary')
def edit_dictionary(request, project, lang):
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
word = get_object_or_404(
Dictionary,
project=prj,
language=lang,
id=request.GET.get('id')
)
if request.method == 'POST':
form = WordForm(request.POST)
if form.is_valid():
word.source = form.cleaned_data['source']
word.target = form.cleaned_data['target']
word.save()
return HttpResponseRedirect(reverse(
'weblate.trans.views.show_dictionary',
kwargs={'project': prj.slug, 'lang': lang.code}
))
else:
form = WordForm(
initial={'source': word.source, 'target': word.target}
)
return render_to_response('edit_dictionary.html', RequestContext(request, {
'title': _('%(language)s dictionary for %(project)s') %
{'language': lang, 'project': prj},
'project': prj,
'language': lang,
'form': form,
}))
@login_required
@permission_required('trans.delete_dictionary')
def delete_dictionary(request, project, lang):
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
word = get_object_or_404(
Dictionary,
project=prj,
language=lang,
id=request.POST.get('id')
)
word.delete()
return HttpResponseRedirect(reverse(
'weblate.trans.views.show_dictionary',
kwargs={'project': prj.slug, 'lang': lang.code})
)
@login_required
@permission_required('trans.upload_dictionary')
def upload_dictionary(request, project, lang):
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
if request.method == 'POST':
form = DictUploadForm(request.POST, request.FILES)
if form.is_valid():
try:
count = Dictionary.objects.upload(
prj,
lang,
request.FILES['file'],
form.cleaned_data['overwrite']
)
if count == 0:
messages.warning(
request,
_('No words to import found in file.')
)
else:
messages.info(
request,
_('Imported %d words from file.') % count
)
except Exception as e:
messages.error(
request,
_('File content merge failed: %s' % unicode(e))
)
else:
messages.error(request, _('Failed to process form!'))
else:
messages.error(request, _('Failed to process form!'))
return HttpResponseRedirect(reverse(
'weblate.trans.views.show_dictionary',
kwargs={'project': prj.slug, 'lang': lang.code}
))
def download_dictionary(request, project, lang):
'''
Exports dictionary.
'''
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
# Parse parameters
export_format = None
if 'format' in request.GET:
export_format = request.GET['format']
if not export_format in ['csv', 'po']:
export_format = 'csv'
# Grab all words
words = Dictionary.objects.filter(
project=prj,
language=lang
).order_by('source')
if export_format == 'csv':
response = HttpResponse(mimetype='text/csv; charset=utf-8')
filename = 'dictionary-%s-%s.csv' % (prj.slug, lang.code)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
writer = csv.writer(response)
for word in words.iterator():
writer.writerow((
word.source.encode('utf8'), word.target.encode('utf8')
))
return response
elif export_format == 'po':
from translate.storage.po import pounit, pofile
response = HttpResponse(mimetype='text/x-po; charset=utf-8')
filename = 'dictionary-%s-%s.po' % (prj.slug, lang.code)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
store = pofile()
site = Site.objects.get_current()
store.updateheader(
add=True,
language=lang.code,
x_generator='Weblate %s' % weblate.VERSION,
project_id_version='%s dictionary for %s' % (lang.name, prj.name),
language_team='%s <http://%s%s>' % (
lang.name,
site.domain,
reverse(
'weblate.trans.views.show_dictionary',
kwargs={'project': prj.slug, 'lang': lang.code}
),
)
)
for word in words.iterator():
unit = pounit(word.source)
unit.target = word.target
store.addunit(unit)
store.savefile(response)
return response
def show_dictionary(request, project, lang):
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
if (request.method == 'POST'
and request.user.has_perm('trans.add_dictionary')):
form = WordForm(request.POST)
if form.is_valid():
Dictionary.objects.create(
project=prj,
language=lang,
source=form.cleaned_data['source'],
target=form.cleaned_data['target']
)
return HttpResponseRedirect(request.get_full_path())
else:
form = WordForm()
uploadform = DictUploadForm()
words = Dictionary.objects.filter(
project=prj, language=lang
).order_by('source')
limit = request.GET.get('limit', 25)
page = request.GET.get('page', 1)
letterform = LetterForm(request.GET)
if letterform.is_valid() and letterform.cleaned_data['letter'] != '':
words = words.filter(
source__istartswith=letterform.cleaned_data['letter']
)
letter = letterform.cleaned_data['letter']
else:
letter = ''
paginator = Paginator(words, limit)
try:
words = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
words = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
words = paginator.page(paginator.num_pages)
return render_to_response('dictionary.html', RequestContext(request, {
'title': _('%(language)s dictionary for %(project)s') %
{'language': lang, 'project': prj},
'project': prj,
'language': lang,
'words': words,
'form': form,
'uploadform': uploadform,
'letterform': letterform,
'letter': letter,
}))
def show_engage(request, project, lang=None):
# Get project object
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
# Handle language parameter
language = None
if lang is not None:
try:
django.utils.translation.activate(lang)
except:
# Ignore failure on activating language
pass
try:
language = Language.objects.get(code=lang)
except Language.DoesNotExist:
pass
context = {
'object': obj,
'project': obj.name,
'languages': obj.get_language_count(),
'total': obj.get_total(),
'percent': obj.get_translated_percent(language),
'url': obj.get_absolute_url(),
'language': language,
}
# Render text
if language is None:
status_text = _(
'<a href="%(url)s">Translation project for %(project)s</a> '
'currently contains %(total)s strings for translation and is '
'<a href="%(url)s">being translated into %(languages)s languages'
'</a>. Overall, these translations are %(percent)s%% complete.'
)
else:
# Translators: line of text in engagement widget, please use your
# language name instead of English
status_text = _(
'<a href="%(url)s">Translation project for %(project)s</a> into '
'English currently contains %(total)s strings for translation and '
'is %(percent)s%% complete.'
)
if 'English' in status_text:
status_text = status_text.replace('English', language.name)
context['status_text'] = mark_safe(status_text % context)
return render_to_response('engage.html', RequestContext(request, context))
def show_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
dicts = Dictionary.objects.filter(
project=obj
).values_list(
'language', flat=True
).distinct()
last_changes = Change.objects.filter(
translation__subproject__project=obj
).order_by('-timestamp')[:10]
return render_to_response('project.html', RequestContext(request, {
'object': obj,
'dicts': Language.objects.filter(id__in=dicts),
'last_changes': last_changes,
'last_changes_rss': reverse(
'rss-project',
kwargs={'project': obj.slug}
),
}))
def show_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
last_changes = Change.objects.filter(
translation__subproject=obj
).order_by('-timestamp')[:10]
return render_to_response('subproject.html', RequestContext(request, {
'object': obj,
'last_changes': last_changes,
'last_changes_rss': reverse(
'rss-subproject',
kwargs={'subproject': obj.slug, 'project': obj.project.slug}
),
}))
@login_required
@permission_required('trans.automatic_translation')
def auto_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
obj.commit_pending()
autoform = AutoForm(obj, request.POST)
change = None
if not obj.subproject.locked and autoform.is_valid():
if autoform.cleaned_data['inconsistent']:
units = obj.unit_set.filter_type('inconsistent', obj)
elif autoform.cleaned_data['overwrite']:
units = obj.unit_set.all()
else:
units = obj.unit_set.filter(translated=False)
sources = Unit.objects.filter(
translation__language=obj.language,
translated=True
)
if autoform.cleaned_data['subproject'] == '':
sources = sources.filter(
translation__subproject__project=obj.subproject.project
).exclude(
translation=obj
)
else:
subprj = SubProject.objects.get(
project=obj.subproject.project,
slug=autoform.cleaned_data['subproject']
)
sources = sources.filter(translation__subproject=subprj)
for unit in units.iterator():
update = sources.filter(checksum=unit.checksum)
if update.exists():
# Get first entry
update = update[0]
# No save if translation is same
if unit.fuzzy == update.fuzzy and unit.target == update.target:
continue
# Copy translation
unit.fuzzy = update.fuzzy
unit.target = update.target
# Create signle change object for whole merge
if change is None:
change = Change.objects.create(
unit=unit,
translation=unit.translation,
user=request.user
)
# Save unit to backend
unit.save_backend(request, False, False)
messages.info(request, _('Automatic translation completed.'))
else:
messages.error(request, _('Failed to process form!'))
return HttpResponseRedirect(obj.get_absolute_url())
def review_source(request, project, subproject):
'''
Listing of source strings to review.
'''
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if not obj.translation_set.exists():
raise Http404('No translation exists in this subproject.')
# Grab first translation in subproject
# (this assumes all have same source strings)
source = obj.translation_set.all()[0]
# Grab search type and page number
rqtype = request.GET.get('type', 'all')
limit = request.GET.get('limit', 50)
page = request.GET.get('page', 1)
# Fiter units
sources = source.unit_set.filter_type(rqtype, source)
paginator = Paginator(sources, limit)
try:
sources = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
sources = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
sources = paginator.page(paginator.num_pages)
return render_to_response('source-review.html', RequestContext(request, {
'object': obj,
'source': source,
'sources': sources,
'title': _('Review source strings in %s') % obj.__unicode__(),
}))
def show_source(request, project, subproject):
'''
Show source strings summary and checks.
'''
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if not obj.translation_set.exists():
raise Http404('No translation exists in this subproject.')
# Grab first translation in subproject
# (this assumes all have same source strings)
source = obj.translation_set.all()[0]
return render_to_response('source.html', RequestContext(request, {
'object': obj,
'source': source,
'title': _('Source strings in %s') % obj.__unicode__(),
}))
def show_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
last_changes = Change.objects.filter(
translation=obj
).order_by('-timestamp')[:10]
# Check locks
obj.is_locked(request)
# How much is user allowed to configure upload?
if request.user.has_perm('trans.author_translation'):
form = ExtraUploadForm()
elif request.user.has_perm('trans.overwrite_translation'):
form = UploadForm()
else:
form = SimpleUploadForm()
# Is user allowed to do automatic translation?
if request.user.has_perm('trans.automatic_translation'):
autoform = AutoForm(obj)
else:
autoform = None
# Search form for everybody
search_form = SearchForm()
# Review form for logged in users
if request.user.is_anonymous():
review_form = None
else:
review_form = ReviewForm(
initial={
'date': datetime.date.today() - datetime.timedelta(days=31)
}
)
return render_to_response('translation.html', RequestContext(request, {
'object': obj,
'form': form,
'autoform': autoform,
'search_form': search_form,
'review_form': review_form,
'last_changes': last_changes,
'last_changes_rss': reverse(
'rss-translation',
kwargs={
'lang': obj.language.code,
'subproject': obj.subproject.slug,
'project': obj.subproject.project.slug
}
),
}))
@login_required
@permission_required('trans.commit_translation')
def commit_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
obj.commit_pending()
messages.info(request, _('All pending translations were committed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.commit_translation')
def commit_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
obj.commit_pending()
messages.info(request, _('All pending translations were committed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.commit_translation')
def commit_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
obj.commit_pending()
messages.info(request, _('All pending translations were committed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.update_translation')
def update_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
if obj.do_update(request):
messages.info(request, _('All repositories were updated.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.update_translation')
def update_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if obj.do_update(request):
messages.info(request, _('All repositories were updated.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.update_translation')
def update_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if obj.do_update(request):
messages.info(request, _('All repositories were updated.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.push_translation')
def push_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
if obj.do_push(request):
messages.info(request, _('All repositories were pushed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.push_translation')
def push_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if obj.do_push(request):
messages.info(request, _('All repositories were pushed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.push_translation')
def push_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if obj.do_push(request):
messages.info(request, _('All repositories were pushed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.reset_translation')
def reset_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
if obj.do_reset(request):
messages.info(request, _('All repositories have been reset.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.reset_translation')
def reset_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if obj.do_reset(request):
messages.info(request, _('All repositories have been reset.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.reset_translation')
def reset_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if obj.do_reset(request):
messages.info(request, _('All repositories have been reset.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_translation')
def lock_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if not obj.is_user_locked(request):
obj.create_lock(request.user, True)
messages.info(request, _('Translation is now locked for you.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
def update_lock(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if not obj.is_user_locked(request):
obj.update_lock_time()
return HttpResponse('ok')
@login_required
@permission_required('trans.lock_translation')
def unlock_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if not obj.is_user_locked(request):
obj.create_lock(None)
messages.info(
request,
_('Translation is now open for translation updates.')
)
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_subproject')
def lock_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
obj.commit_pending()
obj.locked = True
obj.save()
messages.info(
request,
_('Subproject is now locked for translation updates!')
)
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_subproject')
def unlock_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
obj.locked = False
obj.save()
messages.info(
request,
_('Subproject is now open for translation updates.')
)
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_subproject')
def lock_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
obj.commit_pending()
for subproject in obj.subproject_set.all():
subproject.locked = True
subproject.save()
messages.info(
request,
_('All subprojects are now locked for translation updates!')
)
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_subproject')
def unlock_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
for subproject in obj.subproject_set.all():
subproject.locked = False
subproject.save()
messages.info(request, _('Project is now open for translation updates.'))
return HttpResponseRedirect(obj.get_absolute_url())
def download_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
# Retrieve ttkit store to get extension and mime type
store = obj.get_store()
srcfilename = obj.get_filename()
if store.Mimetypes is None:
# Properties files do not expose mimetype
mime = 'text/plain'
else:
mime = store.Mimetypes[0]
if store.Extensions is None:
# Typo in translate-toolkit 1.9, see
# https://github.com/translate/translate/pull/10
if hasattr(store, 'Exensions'):
ext = store.Exensions[0]
else:
ext = 'txt'
else:
ext = store.Extensions[0]
# Construct file name (do not use real filename as it is usually not
# that useful)
filename = '%s-%s-%s.%s' % (project, subproject, lang, ext)
# Django wrapper for sending file
wrapper = FixedFileWrapper(file(srcfilename))
response = HttpResponse(wrapper, mimetype=mime)
# Fill in response headers
response['Content-Disposition'] = 'attachment; filename=%s' % filename
response['Content-Length'] = os.path.getsize(srcfilename)
return response
def bool2str(val):
if val:
return 'on'
return ''
def parse_search_url(request):
# Check where we are
rqtype = request.REQUEST.get('type', 'all')
direction = request.REQUEST.get('dir', 'forward')
pos = request.REQUEST.get('pos', '-1')
try:
pos = int(pos)
except:
pos = -1
# Pre-process search form
if request.method == 'POST':
search_form = SearchForm(request.POST)
else:
search_form = SearchForm(request.GET)
if search_form.is_valid():
search_query = search_form.cleaned_data['q']
search_type = search_form.cleaned_data['search']
if search_type == '':
search_type = 'ftx'
search_source = search_form.cleaned_data['src']
search_target = search_form.cleaned_data['tgt']
search_context = search_form.cleaned_data['ctx']
# Sane defaults
if not search_context and not search_source and not search_target:
search_source = True
search_target = True
search_url = '&q=%s&src=%s&tgt=%s&ctx=%s&search=%s' % (
search_query,
bool2str(search_source),
bool2str(search_target),
bool2str(search_context),
search_type,
)
else:
search_query = ''
search_type = 'ftx'
search_source = True
search_target = True
search_context = False
search_url = ''
if 'date' in request.REQUEST:
search_url += '&date=%s' % request.REQUEST['date']
return (
rqtype,
direction,
pos,
search_query,
search_type,
search_source,
search_target,
search_context,
search_url
)
def get_filter_name(rqtype, search_query):
'''
Returns name of current filter.
'''
if search_query != '':
return _('Search for "%s"') % search_query
if rqtype == 'all':
return None
elif rqtype == 'fuzzy':
return _('Fuzzy strings')
elif rqtype == 'untranslated':
return _('Untranslated strings')
elif rqtype == 'suggestions':
return _('Strings with suggestions')
elif rqtype == 'allchecks':
return _('Strings with any failing checks')
elif rqtype in CHECKS:
return CHECKS[rqtype].name
else:
return None
def translate(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
# Check locks
project_locked, user_locked, own_lock = obj.is_locked(request, True)
locked = project_locked or user_locked
if request.user.is_authenticated():
profile = request.user.get_profile()
antispam = None
else:
profile = None
antispam = AntispamForm()
secondary = None
unit = None
rqtype, direction, pos, search_query, search_type, search_source, search_target, search_context, search_url = parse_search_url(request)
# Any form submitted?
if request.method == 'POST':
# Antispam protection
if not request.user.is_authenticated():
antispam = AntispamForm(request.POST)
if not antispam.is_valid():
# Silently redirect to next entry
return HttpResponseRedirect('%s?type=%s&pos=%d%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
form = TranslationForm(request.POST)
if form.is_valid() and not project_locked:
# Check whether translation is not outdated
obj.check_sync()
try:
try:
unit = Unit.objects.get(
checksum=form.cleaned_data['checksum'],
translation=obj
)
except Unit.MultipleObjectsReturned:
# Possible temporary inconsistency caused by ongoing update
# of repo, let's pretend everyting is okay
unit = Unit.objects.filter(
checksum=form.cleaned_data['checksum'],
translation=obj
)[0]
if 'suggest' in request.POST:
# Handle suggesion saving
user = request.user
if isinstance(user, AnonymousUser):
user = None
if form.cleaned_data['target'] == len(form.cleaned_data['target']) * ['']:
messages.error(request, _('Your suggestion is empty!'))
# Stay on same entry
return HttpResponseRedirect(
'%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
)
)
# Create the suggestion
sug = Suggestion.objects.create(
target=join_plural(form.cleaned_data['target']),
checksum=unit.checksum,
language=unit.translation.language,
project=unit.translation.subproject.project,
user=user)
# Record in change
Change.objects.create(
unit=unit,
action=Change.ACTION_SUGGESTION,
translation=unit.translation,
user=user
)
# Invalidate counts cache
unit.translation.invalidate_cache('suggestions')
# Invite user to become translator if there is nobody else
recent_changes = Change.objects.content().filter(
translation=unit.translation,
).exclude(
user=None
).order_by('-timestamp')
if recent_changes.count() == 0 or True:
messages.info(
request,
_('There is currently no active translator for this translation, please consider becoming a translator as your suggestion might otherwise remain unreviewed.')
)
# Notify subscribed users
subscriptions = Profile.objects.subscribed_new_suggestion(
obj.subproject.project,
obj.language,
request.user
)
for subscription in subscriptions:
subscription.notify_new_suggestion(obj, sug, unit)
# Update suggestion stats
if profile is not None:
profile.suggested += 1
profile.save()
elif not request.user.is_authenticated():
# We accept translations only from authenticated
messages.error(
request,
_('You need to log in to be able to save translations!')
)
elif not request.user.has_perm('trans.save_translation'):
# Need privilege to save
messages.error(
request,
_('You don\'t have privileges to save translations!')
)
elif not user_locked:
# Remember old checks
oldchecks = set(
unit.active_checks().values_list('check', flat=True)
)
# Update unit and save it
unit.target = join_plural(form.cleaned_data['target'])
unit.fuzzy = form.cleaned_data['fuzzy']
saved = unit.save_backend(request)
if saved:
# Get new set of checks
newchecks = set(
unit.active_checks().values_list('check', flat=True)
)
# Did we introduce any new failures?
if newchecks > oldchecks:
# Show message to user
messages.error(
request,
_('Some checks have failed on your translation!')
)
# Stay on same entry
return HttpResponseRedirect(
'%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
)
)
# Redirect to next entry
return HttpResponseRedirect('%s?type=%s&pos=%d%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
except Unit.DoesNotExist:
logger.error(
'message %s disappeared!',
form.cleaned_data['checksum']
)
messages.error(
request,
_('Message you wanted to translate is no longer available!')
)
# Handle translation merging
if 'merge' in request.GET and not locked:
if not request.user.has_perm('trans.save_translation'):
# Need privilege to save
messages.error(
request,
_('You don\'t have privileges to save translations!')
)
else:
try:
mergeform = MergeForm(request.GET)
if mergeform.is_valid():
try:
unit = Unit.objects.get(
checksum=mergeform.cleaned_data['checksum'],
translation=obj
)
except Unit.MultipleObjectsReturned:
# Possible temporary inconsistency caused by ongoing
# update of repo, let's pretend everyting is okay
unit = Unit.objects.filter(
checksum=mergeform.cleaned_data['checksum'],
translation=obj
)[0]
merged = Unit.objects.get(
pk=mergeform.cleaned_data['merge']
)
if unit.checksum != merged.checksum:
messages.error(
request,
_('Can not merge different messages!')
)
else:
# Store unit
unit.target = merged.target
unit.fuzzy = merged.fuzzy
saved = unit.save_backend(request)
# Update stats if there was change
if saved:
profile.translated += 1
profile.save()
# Redirect to next entry
return HttpResponseRedirect('%s?type=%s&pos=%d%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
except Unit.DoesNotExist:
logger.error(
'message %s disappeared!',
form.cleaned_data['checksum']
)
messages.error(
request,
_('Message you wanted to translate is no longer available!')
)
# Handle accepting/deleting suggestions
if not locked and ('accept' in request.GET or 'delete' in request.GET):
# Check for authenticated users
if not request.user.is_authenticated():
messages.error(request, _('You need to log in to be able to manage suggestions!'))
return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
# Parse suggestion ID
if 'accept' in request.GET:
if not request.user.has_perm('trans.accept_suggestion'):
messages.error(request, _('You do not have privilege to accept suggestions!'))
return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
sugid = request.GET['accept']
else:
if not request.user.has_perm('trans.delete_suggestion'):
messages.error(request, _('You do not have privilege to delete suggestions!'))
return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
sugid = request.GET['delete']
try:
sugid = int(sugid)
suggestion = Suggestion.objects.get(pk=sugid)
except:
suggestion = None
if suggestion is not None:
if 'accept' in request.GET:
# Accept suggesiont
suggestion.accept(request)
# Invalidate caches
for unit in Unit.objects.filter(checksum=suggestion.checksum):
unit.translation.invalidate_cache('suggestions')
# Delete suggestion in both cases (accepted ones are no longer
# needed)
suggestion.delete()
else:
messages.error(request, _('Invalid suggestion!'))
# Redirect to same entry for possible editing
return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
reviewform = ReviewForm(request.GET)
if reviewform.is_valid():
allunits = obj.unit_set.review(
reviewform.cleaned_data['date'],
request.user
)
# Review
if direction == 'stay':
units = allunits.filter(position=pos)
elif direction == 'back':
units = allunits.filter(position__lt=pos).order_by('-position')
else:
units = allunits.filter(position__gt=pos)
elif search_query != '':
# Apply search conditions
if search_type == 'exact':
query = Q()
if search_source:
query |= Q(source=search_query)
if search_target:
query |= Q(target=search_query)
if search_context:
query |= Q(context=search_query)
allunits = obj.unit_set.filter(query)
elif search_type == 'substring':
query = Q()
if search_source:
query |= Q(source__icontains=search_query)
if search_target:
query |= Q(target__icontains=search_query)
if search_context:
query |= Q(context__icontains=search_query)
allunits = obj.unit_set.filter(query)
else:
allunits = obj.unit_set.search(
search_query,
search_source,
search_context,
search_target
)
if direction == 'stay':
units = obj.unit_set.filter(position=pos)
elif direction == 'back':
units = allunits.filter(position__lt=pos).order_by('-position')
else:
units = allunits.filter(position__gt=pos)
elif 'checksum' in request.GET:
allunits = obj.unit_set.filter(checksum=request.GET['checksum'])
units = allunits
else:
allunits = obj.unit_set.filter_type(rqtype, obj)
# What unit set is about to show
if direction == 'stay':
units = obj.unit_set.filter(position=pos)
elif direction == 'back':
units = allunits.filter(position__lt=pos).order_by('-position')
else:
units = allunits.filter(position__gt=pos)
# If we failed to get unit above or on no POST
if unit is None:
# Grab actual unit
try:
unit = units[0]
except IndexError:
messages.info(request, _('You have reached end of translating.'))
return HttpResponseRedirect(obj.get_absolute_url())
# Show secondary languages for logged in users
if profile:
secondary_langs = profile.secondary_languages.exclude(
id=unit.translation.language.id
)
project = unit.translation.subproject.project
secondary = Unit.objects.filter(
checksum=unit.checksum,
translated=True,
translation__subproject__project=project,
translation__language__in=secondary_langs,
)
# distinct('target') works with Django 1.4 so let's emulate that
# based on presumption we won't get too many results
targets = {}
res = []
for lang in secondary:
if lang.target in targets:
continue
targets[lang.target] = 1
res.append(lang)
secondary = res
# Prepare form
form = TranslationForm(initial={
'checksum': unit.checksum,
'target': (unit.translation.language, unit.get_target_plurals()),
'fuzzy': unit.fuzzy,
})
total = obj.unit_set.all().count()
filter_count = allunits.count()
return render_to_response(
'translate.html',
RequestContext(request, {
'object': obj,
'unit': unit,
'last_changes': unit.change_set.all()[:10],
'total': total,
'type': rqtype,
'filter_name': get_filter_name(rqtype, search_query),
'filter_count': filter_count,
'filter_pos': filter_count + 1 - units.count(),
'form': form,
'antispam': antispam,
'comment_form': CommentForm(),
'target_language': obj.language.code.replace('_', '-').lower(),
'update_lock': own_lock,
'secondary': secondary,
'search_query': search_query,
'search_url': search_url,
'search_source': bool2str(search_source),
'search_type': search_type,
'search_target': bool2str(search_target),
'search_context': bool2str(search_context),
'locked': locked,
'user_locked': user_locked,
'project_locked': project_locked,
},
))
@login_required
def comment(request, pk):
'''
Adds new comment.
'''
obj = get_object_or_404(Unit, pk=pk)
obj.check_acl(request)
if request.POST.get('type', '') == 'source':
lang = None
else:
lang = obj.translation.language
form = CommentForm(request.POST)
if form.is_valid():
new_comment = Comment.objects.create(
user=request.user,
checksum=obj.checksum,
project=obj.translation.subproject.project,
comment=form.cleaned_data['comment'],
language=lang
)
Change.objects.create(
unit=obj,
action=Change.ACTION_COMMENT,
translation=obj.translation,
user=request.user
)
# Invalidate counts cache
if lang is None:
obj.translation.invalidate_cache('sourcecomments')
else:
obj.translation.invalidate_cache('targetcomments')
messages.info(request, _('Posted new comment'))
# Notify subscribed users
subscriptions = Profile.objects.subscribed_new_comment(
obj.translation.subproject.project,
lang,
request.user
)
for subscription in subscriptions:
subscription.notify_new_comment(obj, new_comment)
# Notify upstream
if lang is None and obj.translation.subproject.report_source_bugs != '':
send_notification_email(
'en',
obj.translation.subproject.report_source_bugs,
'new_comment',
obj.translation,
{
'unit': obj,
'comment': new_comment,
'subproject': obj.translation.subproject,
},
from_email=request.user.email,
)
else:
messages.error(request, _('Failed to add comment!'))
return HttpResponseRedirect(obj.get_absolute_url())
def get_string(request, checksum):
'''
AJAX handler for getting raw string.
'''
units = Unit.objects.filter(checksum=checksum)
if units.count() == 0:
return HttpResponse('')
units[0].check_acl(request)
return HttpResponse(units[0].get_source_plurals()[0])
def get_similar(request, unit_id):
'''
AJAX handler for getting similar strings.
'''
unit = get_object_or_404(Unit, pk=int(unit_id))
unit.check_acl(request)
similar_units = Unit.objects.similar(unit)
# distinct('target') works with Django 1.4 so let's emulate that
# based on presumption we won't get too many results
targets = {}
res = []
for similar in similar_units:
if similar.target in targets:
continue
targets[similar.target] = 1
res.append(similar)
similar = res
return render_to_response('js/similar.html', RequestContext(request, {
'similar': similar,
}))
def get_other(request, unit_id):
'''
AJAX handler for same strings in other subprojects.
'''
unit = get_object_or_404(Unit, pk=int(unit_id))
unit.check_acl(request)
other = Unit.objects.same(unit)
rqtype, direction, pos, search_query, search_type, search_source, search_target, search_context, search_url = parse_search_url(request)
return render_to_response('js/other.html', RequestContext(request, {
'other': other,
'unit': unit,
'type': rqtype,
'search_url': search_url,
}))
def get_dictionary(request, unit_id):
'''
Lists words from dictionary for current translation.
'''
unit = get_object_or_404(Unit, pk=int(unit_id))
unit.check_acl(request)
words = set()
# Prepare analyzers
# - standard analyzer simply splits words
# - stemming extracts stems, to catch things like plurals
analyzers = (StandardAnalyzer(), StemmingAnalyzer())
# Extract words from all plurals and from context
for text in unit.get_source_plurals() + [unit.context]:
for analyzer in analyzers:
words = words.union([token.text for token in analyzer(text)])
# Grab all words in the dictionary
dictionary = Dictionary.objects.filter(
project = unit.translation.subproject.project,
language = unit.translation.language
)
if len(words) == 0:
# No extracted words, no dictionary
dictionary = dictionary.none()
else:
# Build the query (can not use __in as we want case insensitive lookup)
query = Q()
for word in words:
query |= Q(source__iexact=word)
# Filter dictionary
dictionary = dictionary.filter(query)
return render_to_response('js/dictionary.html', RequestContext(request, {
'dictionary': dictionary,
}))
@login_required
@permission_required('trans.ignore_check')
def ignore_check(request, check_id):
obj = get_object_or_404(Check, pk=int(check_id))
obj.project.check_acl(request)
# Mark check for ignoring
obj.ignore = True
obj.save()
# Invalidate caches
for unit in Unit.objects.filter(checksum=obj.checksum):
unit.translation.invalidate_cache()
# response for AJAX
return HttpResponse('ok')
@login_required
@permission_required('trans.upload_translation')
def upload_translation(request, project, subproject, lang):
'''
Handling of translation uploads.
'''
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if not obj.is_locked(request) and request.method == 'POST':
if request.user.has_perm('trans.author_translation'):
form = ExtraUploadForm(request.POST, request.FILES)
elif request.user.has_perm('trans.overwrite_translation'):
form = UploadForm(request.POST, request.FILES)
else:
form = SimpleUploadForm(request.POST, request.FILES)
if form.is_valid():
if request.user.has_perm('trans.author_translation') and form.cleaned_data['author_name'] != '' and form.cleaned_data['author_email'] != '':
author = '%s <%s>' % (form.cleaned_data['author_name'], form.cleaned_data['author_email'])
else:
author = None
if request.user.has_perm('trans.overwrite_translation'):
overwrite = form.cleaned_data['overwrite']
else:
overwrite = False
try:
ret = obj.merge_upload(request, request.FILES['file'], overwrite, author, merge_header=form.cleaned_data['merge_header'])
if ret:
messages.info(request, _('File content successfully merged into translation.'))
else:
messages.info(request, _('There were no new strings in uploaded file.'))
except Exception as e:
messages.error(request, _('File content merge failed: %s' % unicode(e)))
return HttpResponseRedirect(obj.get_absolute_url())
def not_found(request):
'''
Error handler showing list of available projects.
'''
template = loader.get_template('404.html')
return HttpResponseNotFound(
template.render(RequestContext(request, {
'request_path': request.path,
'title': _('Page Not Found'),
'projects': Project.objects.all_acl(request.user),
}
)))
# Cache this page for one month, it should not really change much
@cache_page(30 * 24 * 3600)
def js_config(request):
'''
Generates settings for javascript. Includes things like
API keys for translaiton services or list of languages they
support.
'''
# Apertium support
if appsettings.MT_APERTIUM_KEY is not None and appsettings.MT_APERTIUM_KEY != '':
try:
listpairs = urllib2.urlopen('http://api.apertium.org/json/listPairs?key=%s' % appsettings.MT_APERTIUM_KEY)
pairs = listpairs.read()
parsed = json.loads(pairs)
apertium_langs = [p['targetLanguage'] for p in parsed['responseData'] if p['sourceLanguage'] == 'en']
except Exception as e:
logger.error('failed to get supported languages from Apertium, using defaults (%s)', str(e))
apertium_langs = ['gl', 'ca', 'es', 'eo']
else:
apertium_langs = None
# Microsoft translator support
if appsettings.MT_MICROSOFT_KEY is not None and appsettings.MT_MICROSOFT_KEY != '':
try:
listpairs = urllib2.urlopen('http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appID=%s' % appsettings.MT_MICROSOFT_KEY)
data = listpairs.read()
parsed = ElementTree.fromstring(data)
microsoft_langs = [p.text for p in parsed.getchildren()]
except Exception as e:
logger.error('failed to get supported languages from Microsoft, using defaults (%s)', str(e))
microsoft_langs = [
'ar', 'bg', 'ca', 'zh-CHS', 'zh-CHT', 'cs', 'da', 'nl', 'en',
'et', 'fi', 'fr', 'de', 'el', 'ht', 'he', 'hi', 'mww', 'hu',
'id', 'it', 'ja', 'ko', 'lv', 'lt', 'no', 'fa', 'pl', 'pt',
'ro', 'ru', 'sk', 'sl', 'es', 'sv', 'th', 'tr', 'uk', 'vi'
]
else:
microsoft_langs = None
return render_to_response('js/config.js', RequestContext(request, {
'apertium_langs': apertium_langs,
'microsoft_langs': microsoft_langs,
}),
mimetype = 'application/javascript')
def about(request):
context = {}
versions = get_versions()
totals = Profile.objects.aggregate(Sum('translated'), Sum('suggested'))
total_strings = 0
for project in SubProject.objects.iterator():
try:
total_strings += project.translation_set.all()[0].total
except Translation.DoesNotExist:
pass
context['title'] = _('About Weblate')
context['total_translations'] = totals['translated__sum']
context['total_suggestions'] = totals['suggested__sum']
context['total_users'] = Profile.objects.count()
context['total_strings'] = total_strings
context['total_languages'] = Language.objects.filter(
translation__total__gt=0
).distinct().count()
context['total_checks'] = Check.objects.count()
context['ignored_checks'] = Check.objects.filter(ignore=True).count()
context['versions'] = versions
return render_to_response('about.html', RequestContext(request, context))
@user_passes_test(lambda u: u.has_perm('trans.commit_translation') or u.has_perm('trans.update_translation'))
def git_status_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
return render_to_response('js/git-status.html', RequestContext(request, {
'object': obj,
}))
@user_passes_test(lambda u: u.has_perm('trans.commit_translation') or u.has_perm('trans.update_translation'))
def git_status_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
return render_to_response('js/git-status.html', RequestContext(request, {
'object': obj,
}))
@user_passes_test(lambda u: u.has_perm('trans.commit_translation') or u.has_perm('trans.update_translation'))
def git_status_translation(request, project, subproject, lang):
obj = get_object_or_404(Translation, language__code=lang, subproject__slug=subproject, subproject__project__slug=project, enabled=True)
obj.check_acl(request)
return render_to_response('js/git-status.html', RequestContext(request, {
'object': obj,
}))
def data_root(request):
site = Site.objects.get_current()
return render_to_response('data-root.html', RequestContext(request, {
'site_domain': site.domain,
'api_docs': weblate.get_doc_url('api', 'exports'),
'rss_docs': weblate.get_doc_url('api', 'rss'),
'projects': Project.objects.all_acl(request.user),
}))
def data_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
site = Site.objects.get_current()
return render_to_response('data.html', RequestContext(request, {
'object': obj,
'site_domain': site.domain,
'api_docs': weblate.get_doc_url('api', 'exports'),
'rss_docs': weblate.get_doc_url('api', 'rss'),
}))
| power12317/weblate | weblate/trans/views.py | Python | gpl-3.0 | 68,329 | 0.000688 |
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import datetime
import threading
import traceback
import sickbeard
from sickbeard import logger
from sickbeard import db
from sickbeard import common
from sickbeard import helpers
from sickbeard import exceptions
from sickbeard import network_timezones
from sickbeard.exceptions import ex
from sickbeard.common import SKIPPED
from common import Quality, qualityPresetStrings, statusStrings
class DailySearcher():
def __init__(self):
self.lock = threading.Lock()
self.amActive = False
def run(self, force=False):
if self.amActive:
return
self.amActive = True
logger.log(u"Searching for new released episodes ...")
if not network_timezones.network_dict:
network_timezones.update_network_dict()
if network_timezones.network_dict:
curDate = (datetime.date.today() + datetime.timedelta(days=1)).toordinal()
else:
curDate = (datetime.date.today() + datetime.timedelta(days=2)).toordinal()
curTime = datetime.datetime.now(network_timezones.sb_timezone)
myDB = db.DBConnection()
sqlResults = myDB.select("SELECT * FROM tv_episodes WHERE status = ? AND season > 0 AND (airdate <= ? and airdate > 1)",
[common.UNAIRED, curDate])
sql_l = []
show = None
for sqlEp in sqlResults:
try:
if not show or int(sqlEp["showid"]) != show.indexerid:
show = helpers.findCertainShow(sickbeard.showList, int(sqlEp["showid"]))
# for when there is orphaned series in the database but not loaded into our showlist
if not show or show.paused:
continue
except exceptions.MultipleShowObjectsException:
logger.log(u"ERROR: expected to find a single show matching " + str(sqlEp['showid']))
continue
try:
end_time = network_timezones.parse_date_time(sqlEp['airdate'], show.airs,
show.network) + datetime.timedelta(
minutes=helpers.tryInt(show.runtime, 60))
# filter out any episodes that haven't aried yet
if end_time > curTime:
continue
except:
# if an error occured assume the episode hasn't aired yet
continue
UpdateWantedList = 0
ep = show.getEpisode(int(sqlEp["season"]), int(sqlEp["episode"]))
with ep.lock:
if ep.season == 0:
logger.log(u"New episode " + ep.prettyName() + " airs today, setting status to SKIPPED because is a special season")
ep.status = common.SKIPPED
elif sickbeard.TRAKT_USE_ROLLING_DOWNLOAD and sickbeard.USE_TRAKT:
ep.status = common.SKIPPED
UpdateWantedList = 1
else:
logger.log(u"New episode %s airs today, setting to default episode status for this show: %s" % (ep.prettyName(), common.statusStrings[ep.show.default_ep_status]))
ep.status = ep.show.default_ep_status
sql_l.append(ep.get_sql())
if len(sql_l) > 0:
myDB = db.DBConnection()
myDB.mass_action(sql_l)
else:
logger.log(u"No new released episodes found ...")
sickbeard.traktRollingScheduler.action.updateWantedList()
# queue episode for daily search
dailysearch_queue_item = sickbeard.search_queue.DailySearchQueueItem()
sickbeard.searchQueueScheduler.action.add_item(dailysearch_queue_item)
self.amActive = False
| keen99/SickRage | sickbeard/dailysearcher.py | Python | gpl-3.0 | 4,533 | 0.002647 |
# 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 Keras backend."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
import scipy.sparse
from tensorflow.core.protobuf import config_pb2
from tensorflow.python import keras
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.util import tf_inspect
def compare_single_input_op_to_numpy(keras_op,
np_op,
input_shape,
dtype='float32',
negative_values=True,
keras_args=None,
keras_kwargs=None,
np_args=None,
np_kwargs=None):
keras_args = keras_args or []
keras_kwargs = keras_kwargs or {}
np_args = np_args or []
np_kwargs = np_kwargs or {}
inputs = 2. * np.random.random(input_shape)
if negative_values:
inputs -= 1.
keras_output = keras_op(keras.backend.variable(inputs, dtype=dtype),
*keras_args, **keras_kwargs)
keras_output = keras.backend.eval(keras_output)
np_output = np_op(inputs.astype(dtype), *np_args, **np_kwargs)
try:
np.testing.assert_allclose(keras_output, np_output, atol=1e-4)
except AssertionError:
raise AssertionError('Test for op `' + str(keras_op.__name__) + '` failed; '
'Expected ' + str(np_output) + ' but got ' +
str(keras_output))
def compare_two_inputs_op_to_numpy(keras_op,
np_op,
input_shape_a,
input_shape_b,
dtype='float32',
keras_args=None,
keras_kwargs=None,
np_args=None,
np_kwargs=None):
keras_args = keras_args or []
keras_kwargs = keras_kwargs or {}
np_args = np_args or []
np_kwargs = np_kwargs or {}
input_a = np.random.random(input_shape_a)
input_b = np.random.random(input_shape_b)
keras_output = keras_op(keras.backend.variable(input_a, dtype=dtype),
keras.backend.variable(input_b, dtype=dtype),
*keras_args, **keras_kwargs)
keras_output = keras.backend.eval(keras_output)
np_output = np_op(input_a.astype(dtype), input_b.astype(dtype),
*np_args, **np_kwargs)
try:
np.testing.assert_allclose(keras_output, np_output, atol=1e-4)
except AssertionError:
raise AssertionError('Test for op `' + str(keras_op.__name__) + '` failed; '
'Expected ' + str(np_output) + ' but got ' +
str(keras_output))
@test_util.run_all_in_graph_and_eager_modes
class BackendUtilsTest(test.TestCase):
def test_backend(self):
self.assertEqual(keras.backend.backend(), 'tensorflow')
def test_get_reset_uids(self):
self.assertEqual(keras.backend.get_uid('foo'), 1)
self.assertEqual(keras.backend.get_uid('foo'), 2)
keras.backend.reset_uids()
self.assertEqual(keras.backend.get_uid('foo'), 1)
def test_learning_phase(self):
with self.cached_session() as sess:
keras.backend.set_learning_phase(1)
self.assertEqual(keras.backend.learning_phase(), 1)
with self.assertRaises(ValueError):
keras.backend.set_learning_phase(2)
# Test running with a learning-phase-consuming layer
keras.backend.set_learning_phase(0)
x = keras.Input((3,))
y = keras.layers.BatchNormalization()(x)
if not context.executing_eagerly():
self.evaluate(variables.global_variables_initializer())
sess.run(y, feed_dict={x: np.random.random((2, 3))})
def test_learning_phase_scope(self):
initial_learning_phase = keras.backend.learning_phase()
with keras.backend.learning_phase_scope(1) as lp:
self.assertEqual(lp, 1)
self.assertEqual(keras.backend.learning_phase(), 1)
self.assertEqual(keras.backend.learning_phase(), initial_learning_phase)
with keras.backend.learning_phase_scope(0) as lp:
self.assertEqual(lp, 0)
self.assertEqual(keras.backend.learning_phase(), 0)
self.assertEqual(keras.backend.learning_phase(), initial_learning_phase)
with self.assertRaises(ValueError):
with keras.backend.learning_phase_scope(None):
pass
self.assertEqual(keras.backend.learning_phase(), initial_learning_phase)
def test_int_shape(self):
x = keras.backend.ones(shape=(3, 4))
self.assertEqual(keras.backend.int_shape(x), (3, 4))
if not context.executing_eagerly():
x = keras.backend.placeholder(shape=(None, 4))
self.assertEqual(keras.backend.int_shape(x), (None, 4))
def test_in_train_phase(self):
y1 = keras.backend.variable(1)
y2 = keras.backend.variable(2)
if context.executing_eagerly():
with keras.backend.learning_phase_scope(0):
y_val_test = keras.backend.in_train_phase(y1, y2).numpy()
with keras.backend.learning_phase_scope(1):
y_val_train = keras.backend.in_train_phase(y1, y2).numpy()
else:
y = keras.backend.in_train_phase(y1, y2)
f = keras.backend.function([keras.backend.learning_phase()], [y])
y_val_test = f([0])[0]
y_val_train = f([1])[0]
self.assertAllClose(y_val_test, 2)
self.assertAllClose(y_val_train, 1)
def test_is_keras_tensor(self):
x = keras.backend.variable(1)
self.assertEqual(keras.backend.is_keras_tensor(x), False)
x = keras.Input(shape=(1,))
self.assertEqual(keras.backend.is_keras_tensor(x), True)
with self.assertRaises(ValueError):
keras.backend.is_keras_tensor(0)
def test_stop_gradient(self):
x = keras.backend.variable(1)
y = keras.backend.stop_gradient(x)
if not context.executing_eagerly():
self.assertEqual(y.op.name[:12], 'StopGradient')
xs = [keras.backend.variable(1) for _ in range(3)]
ys = keras.backend.stop_gradient(xs)
if not context.executing_eagerly():
for y in ys:
self.assertEqual(y.op.name[:12], 'StopGradient')
@test_util.run_all_in_graph_and_eager_modes
class BackendVariableTest(test.TestCase):
def test_zeros(self):
x = keras.backend.zeros((3, 4))
val = keras.backend.eval(x)
self.assertAllClose(val, np.zeros((3, 4)))
def test_ones(self):
x = keras.backend.ones((3, 4))
val = keras.backend.eval(x)
self.assertAllClose(val, np.ones((3, 4)))
def test_eye(self):
x = keras.backend.eye(4)
val = keras.backend.eval(x)
self.assertAllClose(val, np.eye(4))
def test_zeros_like(self):
x = keras.backend.zeros((3, 4))
y = keras.backend.zeros_like(x)
val = keras.backend.eval(y)
self.assertAllClose(val, np.zeros((3, 4)))
def test_ones_like(self):
x = keras.backend.zeros((3, 4))
y = keras.backend.ones_like(x)
val = keras.backend.eval(y)
self.assertAllClose(val, np.ones((3, 4)))
def test_random_uniform_variable(self):
x = keras.backend.random_uniform_variable((30, 20), low=1, high=2, seed=0)
val = keras.backend.eval(x)
self.assertAllClose(val.mean(), 1.5, atol=1e-1)
self.assertAllClose(val.max(), 2., atol=1e-1)
self.assertAllClose(val.min(), 1., atol=1e-1)
def test_random_normal_variable(self):
x = keras.backend.random_normal_variable((30, 20), 1., 0.5, seed=0)
val = keras.backend.eval(x)
self.assertAllClose(val.mean(), 1., atol=1e-1)
self.assertAllClose(val.std(), 0.5, atol=1e-1)
def test_count_params(self):
x = keras.backend.zeros((4, 5))
val = keras.backend.count_params(x)
self.assertAllClose(val, 20)
def test_constant(self):
ref_val = np.random.random((3, 4)).astype('float32')
x = keras.backend.constant(ref_val)
val = keras.backend.eval(x)
self.assertAllClose(val, ref_val)
def test_sparse_variable(self):
val = scipy.sparse.eye(10)
x = keras.backend.variable(val)
self.assertTrue(isinstance(x, sparse_tensor.SparseTensor))
y = keras.backend.to_dense(x)
self.assertFalse(keras.backend.is_sparse(y))
@test_util.run_all_in_graph_and_eager_modes
class BackendLinearAlgebraTest(test.TestCase):
def test_dot(self):
x = keras.backend.ones(shape=(2, 3))
y = keras.backend.ones(shape=(3, 4))
xy = keras.backend.dot(x, y)
self.assertEqual(xy.get_shape().as_list(), [2, 4])
x = keras.backend.ones(shape=(32, 28, 3))
y = keras.backend.ones(shape=(3, 4))
xy = keras.backend.dot(x, y)
self.assertEqual(xy.get_shape().as_list(), [32, 28, 4])
def test_batch_dot(self):
x = keras.backend.ones(shape=(32, 20, 1))
y = keras.backend.ones(shape=(32, 30, 20))
xy = keras.backend.batch_dot(x, y, axes=[1, 2])
self.assertEqual(xy.get_shape().as_list(), [32, 1, 30])
# TODO(fchollet): insufficiently tested.
def test_reduction_ops(self):
ops_to_test = [
(keras.backend.max, np.max),
(keras.backend.min, np.min),
(keras.backend.sum, np.sum),
(keras.backend.prod, np.prod),
(keras.backend.var, np.var),
(keras.backend.std, np.std),
(keras.backend.mean, np.mean),
(keras.backend.argmin, np.argmin),
(keras.backend.argmax, np.argmax),
]
for keras_op, np_op in ops_to_test:
compare_single_input_op_to_numpy(keras_op, np_op, input_shape=(4, 7, 5),
keras_kwargs={'axis': 1},
np_kwargs={'axis': 1})
compare_single_input_op_to_numpy(keras_op, np_op, input_shape=(4, 7, 5),
keras_kwargs={'axis': -1},
np_kwargs={'axis': -1})
if 'keepdims' in tf_inspect.getargspec(keras_op).args:
compare_single_input_op_to_numpy(keras_op, np_op,
input_shape=(4, 7, 5),
keras_kwargs={'axis': 1,
'keepdims': True},
np_kwargs={'axis': 1,
'keepdims': True})
def test_elementwise_ops(self):
ops_to_test = [
(keras.backend.square, np.square),
(keras.backend.abs, np.abs),
(keras.backend.round, np.round),
(keras.backend.sign, np.sign),
(keras.backend.sin, np.sin),
(keras.backend.cos, np.cos),
(keras.backend.exp, np.exp),
]
for keras_op, np_op in ops_to_test:
compare_single_input_op_to_numpy(keras_op, np_op, input_shape=(4, 7))
ops_to_test = [
(keras.backend.sqrt, np.sqrt),
(keras.backend.log, np.log),
]
for keras_op, np_op in ops_to_test:
compare_single_input_op_to_numpy(keras_op, np_op,
input_shape=(4, 7),
negative_values=False)
compare_single_input_op_to_numpy(
keras.backend.clip, np.clip,
input_shape=(6, 4),
keras_kwargs={'min_value': 0.1, 'max_value': 2.4},
np_kwargs={'a_min': 0.1, 'a_max': 1.4})
compare_single_input_op_to_numpy(
keras.backend.pow, np.power,
input_shape=(6, 4),
keras_args=[3],
np_args=[3])
def test_two_tensor_ops(self):
ops_to_test = [
(keras.backend.equal, np.equal),
(keras.backend.not_equal, np.not_equal),
(keras.backend.greater, np.greater),
(keras.backend.greater_equal, np.greater_equal),
(keras.backend.less, np.less),
(keras.backend.less_equal, np.less_equal),
(keras.backend.maximum, np.maximum),
(keras.backend.minimum, np.minimum),
]
for keras_op, np_op in ops_to_test:
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 7),
input_shape_b=(4, 7))
def test_relu(self):
x = ops.convert_to_tensor([[-4, 0], [2, 7]], 'float32')
# standard relu
relu_op = keras.backend.relu(x)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 7]])
# alpha (leaky relu used)
relu_op = keras.backend.relu(x, alpha=0.5)
if not context.executing_eagerly():
self.assertTrue('LeakyRelu' in relu_op.name)
self.assertAllClose(keras.backend.eval(relu_op), [[-2, 0], [2, 7]])
# max_value < some elements
relu_op = keras.backend.relu(x, max_value=5)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 5]])
# nn.relu6 used
relu_op = keras.backend.relu(x, max_value=6)
if not context.executing_eagerly():
self.assertTrue('Relu6' in relu_op.name) # uses tf.nn.relu6
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 6]])
# max value > 6
relu_op = keras.backend.relu(x, max_value=10)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 7]])
# max value is float
relu_op = keras.backend.relu(x, max_value=4.3)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 4.3]])
# max value == 0
relu_op = keras.backend.relu(x, max_value=0)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [0, 0]])
# alpha and max_value
relu_op = keras.backend.relu(x, alpha=0.25, max_value=3)
self.assertAllClose(keras.backend.eval(relu_op), [[-1, 0], [2, 3]])
# threshold
relu_op = keras.backend.relu(x, threshold=3)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [0, 7]])
# threshold is float
relu_op = keras.backend.relu(x, threshold=1.5)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 7]])
# threshold is negative
relu_op = keras.backend.relu(x, threshold=-5)
self.assertAllClose(keras.backend.eval(relu_op), [[-4, 0], [2, 7]])
# threshold and max_value
relu_op = keras.backend.relu(x, threshold=3, max_value=5)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [0, 5]])
# threshold and alpha
relu_op = keras.backend.relu(x, alpha=0.25, threshold=4)
self.assertAllClose(keras.backend.eval(relu_op), [[-2, -1], [-0.5, 7]])
# threshold, alpha, and max_value
relu_op = keras.backend.relu(x, alpha=0.25, threshold=4, max_value=5)
self.assertAllClose(keras.backend.eval(relu_op), [[-2, -1], [-0.5, 5]])
@test_util.run_all_in_graph_and_eager_modes
class BackendShapeOpsTest(test.TestCase):
def test_reshape(self):
compare_single_input_op_to_numpy(keras.backend.reshape, np.reshape,
input_shape=(4, 7),
keras_args=[(2, 14)],
np_args=[(2, 14)])
def test_concatenate(self):
a = keras.backend.variable(np.ones((1, 2, 3)))
b = keras.backend.variable(np.ones((1, 2, 2)))
y = keras.backend.concatenate([a, b], axis=-1)
self.assertEqual(y.get_shape().as_list(), [1, 2, 5])
def test_permute_dimensions(self):
compare_single_input_op_to_numpy(keras.backend.permute_dimensions,
np.transpose,
input_shape=(4, 7),
keras_args=[(1, 0)],
np_args=[(1, 0)])
def test_resize_images(self):
height_factor = 2
width_factor = 2
data_format = 'channels_last'
x = keras.backend.variable(np.ones((1, 2, 2, 3)))
y = keras.backend.resize_images(x,
height_factor,
width_factor,
data_format)
self.assertEqual(y.get_shape().as_list(), [1, 4, 4, 3])
data_format = 'channels_first'
x = keras.backend.variable(np.ones((1, 3, 2, 2)))
y = keras.backend.resize_images(x,
height_factor,
width_factor,
data_format)
self.assertEqual(y.get_shape().as_list(), [1, 3, 4, 4])
# Invalid use:
with self.assertRaises(ValueError):
keras.backend.resize_images(x,
height_factor,
width_factor,
data_format='unknown')
def test_resize_volumes(self):
height_factor = 2
width_factor = 2
depth_factor = 2
data_format = 'channels_last'
x = keras.backend.variable(np.ones((1, 2, 2, 2, 3)))
y = keras.backend.resize_volumes(x,
depth_factor,
height_factor,
width_factor,
data_format)
self.assertEqual(y.get_shape().as_list(), [1, 4, 4, 4, 3])
data_format = 'channels_first'
x = keras.backend.variable(np.ones((1, 3, 2, 2, 2)))
y = keras.backend.resize_volumes(x,
depth_factor,
height_factor,
width_factor,
data_format)
self.assertEqual(y.get_shape().as_list(), [1, 3, 4, 4, 4])
# Invalid use:
with self.assertRaises(ValueError):
keras.backend.resize_volumes(x,
depth_factor,
height_factor,
width_factor,
data_format='unknown')
def test_repeat_elements(self):
x = keras.backend.variable(np.ones((1, 3, 2)))
y = keras.backend.repeat_elements(x, 3, axis=1)
self.assertEqual(y.get_shape().as_list(), [1, 9, 2])
# Use with a dynamic axis:
if not context.executing_eagerly():
x = keras.backend.placeholder(shape=(2, None, 2))
y = keras.backend.repeat_elements(x, 3, axis=1)
self.assertEqual(y.get_shape().as_list(), [2, None, 2])
def test_repeat(self):
x = keras.backend.variable(np.ones((1, 3)))
y = keras.backend.repeat(x, 2)
self.assertEqual(y.get_shape().as_list(), [1, 2, 3])
def test_flatten(self):
compare_single_input_op_to_numpy(keras.backend.flatten,
np.reshape,
input_shape=(4, 7, 6),
np_args=[(4 * 7 * 6,)])
def test_batch_flatten(self):
compare_single_input_op_to_numpy(keras.backend.batch_flatten,
np.reshape,
input_shape=(4, 7, 6),
np_args=[(4, 7 * 6)])
def test_temporal_padding(self):
def ref_op(x, padding):
shape = list(x.shape)
shape[1] += padding[0] + padding[1]
y = np.zeros(tuple(shape))
y[:, padding[0]:-padding[1], :] = x
return y
compare_single_input_op_to_numpy(keras.backend.temporal_padding,
ref_op,
input_shape=(4, 7, 6),
keras_args=[(2, 3)],
np_args=[(2, 3)])
def test_spatial_2d_padding(self):
def ref_op(x, padding, data_format='channels_last'):
shape = list(x.shape)
if data_format == 'channels_last':
shape[1] += padding[0][0] + padding[0][1]
shape[2] += padding[1][0] + padding[1][1]
y = np.zeros(tuple(shape))
y[:, padding[0][0]:-padding[0][1], padding[1][0]:-padding[1][1], :] = x
else:
shape[2] += padding[0][0] + padding[0][1]
shape[3] += padding[1][0] + padding[1][1]
y = np.zeros(tuple(shape))
y[:, :, padding[0][0]:-padding[0][1], padding[1][0]:-padding[1][1]] = x
return y
compare_single_input_op_to_numpy(
keras.backend.spatial_2d_padding,
ref_op,
input_shape=(2, 3, 2, 3),
keras_args=[((2, 3), (1, 2))],
keras_kwargs={'data_format': 'channels_last'},
np_args=[((2, 3), (1, 2))],
np_kwargs={'data_format': 'channels_last'})
compare_single_input_op_to_numpy(
keras.backend.spatial_2d_padding,
ref_op,
input_shape=(2, 3, 2, 3),
keras_args=[((2, 3), (1, 2))],
keras_kwargs={'data_format': 'channels_first'},
np_args=[((2, 3), (1, 2))],
np_kwargs={'data_format': 'channels_first'})
def test_spatial_3d_padding(self):
def ref_op(x, padding, data_format='channels_last'):
shape = list(x.shape)
if data_format == 'channels_last':
shape[1] += padding[0][0] + padding[0][1]
shape[2] += padding[1][0] + padding[1][1]
shape[3] += padding[2][0] + padding[2][1]
y = np.zeros(tuple(shape))
y[:,
padding[0][0]:-padding[0][1],
padding[1][0]:-padding[1][1],
padding[2][0]:-padding[2][1],
:] = x
else:
shape[2] += padding[0][0] + padding[0][1]
shape[3] += padding[1][0] + padding[1][1]
shape[4] += padding[2][0] + padding[2][1]
y = np.zeros(tuple(shape))
y[:, :,
padding[0][0]:-padding[0][1],
padding[1][0]:-padding[1][1],
padding[2][0]:-padding[2][1]] = x
return y
compare_single_input_op_to_numpy(
keras.backend.spatial_3d_padding,
ref_op,
input_shape=(2, 3, 2, 3, 2),
keras_args=[((2, 3), (1, 2), (2, 3))],
keras_kwargs={'data_format': 'channels_last'},
np_args=[((2, 3), (1, 2), (2, 3))],
np_kwargs={'data_format': 'channels_last'})
compare_single_input_op_to_numpy(
keras.backend.spatial_3d_padding,
ref_op,
input_shape=(2, 3, 2, 3, 2),
keras_args=[((2, 3), (1, 2), (2, 3))],
keras_kwargs={'data_format': 'channels_first'},
np_args=[((2, 3), (1, 2), (2, 3))],
np_kwargs={'data_format': 'channels_first'})
@test_util.run_all_in_graph_and_eager_modes
class BackendNNOpsTest(test.TestCase, parameterized.TestCase):
def test_bias_add(self):
keras_op = keras.backend.bias_add
np_op = np.add
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 7),
input_shape_b=(7,))
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 7),
input_shape_b=(7,))
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 5, 7),
input_shape_b=(7,))
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 5, 2, 7),
input_shape_b=(7,))
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
x = keras.backend.variable((3, 4))
b = keras.backend.variable((3, 4))
keras.backend.bias_add(x, b)
with self.assertRaises(ValueError):
x = keras.backend.variable((3, 4))
b = keras.backend.variable((4,))
keras.backend.bias_add(x, b, data_format='unknown')
def test_bias_add_channels_first(self):
def keras_op(x, b):
return keras.backend.bias_add(x, b, data_format='channels_first')
def np_op(x, b):
if x.ndim == 3:
b = b.reshape((1, b.shape[0], 1))
if x.ndim == 4:
b = b.reshape((1, b.shape[0], 1, 1))
return x + b
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 7),
input_shape_b=(3,))
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 5, 7),
input_shape_b=(3,))
def test_pool2d(self):
val = np.random.random((10, 3, 10, 10))
x = keras.backend.variable(val)
y = keras.backend.pool2d(x, (2, 2), strides=(1, 1),
padding='valid', data_format='channels_first',
pool_mode='max')
self.assertEqual(y.get_shape().as_list(), [10, 3, 9, 9])
y = keras.backend.pool2d(x, (2, 2), strides=(1, 1),
padding='valid', data_format='channels_first',
pool_mode='avg')
self.assertEqual(y.get_shape().as_list(), [10, 3, 9, 9])
val = np.random.random((10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool2d(x, (2, 2), strides=(1, 1),
padding='valid', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 9, 9, 3])
val = np.random.random((10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool2d(x, (2, 2), strides=(1, 1),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 10, 10, 3])
val = np.random.random((10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 5, 5, 3])
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2),
padding='other', data_format='channels_last')
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2),
data_format='other')
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2, 2), strides=(2, 2))
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2, 2))
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2), pool_mode='other')
def test_pool3d(self):
val = np.random.random((10, 3, 10, 10, 10))
x = keras.backend.variable(val)
y = keras.backend.pool3d(x, (2, 2, 2), strides=(1, 1, 1),
padding='valid', data_format='channels_first',
pool_mode='max')
self.assertEqual(y.get_shape().as_list(), [10, 3, 9, 9, 9])
y = keras.backend.pool3d(x, (2, 2, 2), strides=(1, 1, 1),
padding='valid', data_format='channels_first',
pool_mode='avg')
self.assertEqual(y.get_shape().as_list(), [10, 3, 9, 9, 9])
val = np.random.random((10, 10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool3d(x, (2, 2, 2), strides=(1, 1, 1),
padding='valid', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 9, 9, 9, 3])
val = np.random.random((10, 10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool3d(x, (2, 2, 2), strides=(1, 1, 1),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 10, 10, 10, 3])
val = np.random.random((10, 10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool3d(x, (2, 2, 2), strides=(2, 2, 2),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 5, 5, 5, 3])
def test_conv1d(self):
val = np.random.random((10, 4, 10))
x = keras.backend.variable(val)
kernel_val = np.random.random((3, 4, 5))
k = keras.backend.variable(kernel_val)
y = keras.backend.conv1d(x, k, strides=(1,),
padding='valid', data_format='channels_first')
self.assertEqual(y.get_shape().as_list(), [10, 5, 8])
val = np.random.random((10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv1d(x, k, strides=(1,),
padding='valid', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 8, 5])
val = np.random.random((10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv1d(x, k, strides=(1,),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 10, 5])
val = np.random.random((10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv1d(x, k, strides=(2,),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 5, 5])
def test_local_conv_channels_dim(self):
filters = 3
batch_size = 2
for input_shape in [(3, 5), (2, 3, 5), (2, 5, 3, 4)]:
channels_in = input_shape[0]
input_spatial_shape = input_shape[1:]
dim = len(input_spatial_shape)
inputs = np.random.normal(0, 1, (batch_size,) + input_shape)
inputs_cf = keras.backend.variable(inputs)
for kernel_size in [1, 2]:
for stride in [1, 2]:
kernel_sizes = (kernel_size,) * dim
strides = (stride,) * dim
output_shape = tuple([(i - kernel_size + stride) // stride
for i in input_spatial_shape])
kernel_shape = (np.prod(output_shape),
np.prod(kernel_sizes) * channels_in,
filters)
kernel = np.random.normal(
0,
1,
output_shape + (channels_in, np.prod(kernel_sizes), filters)
)
kernel_cf = np.reshape(kernel, kernel_shape)
kernel_cf = keras.backend.variable(kernel_cf)
conv_cf = keras.backend.local_conv(inputs_cf,
kernel_cf,
kernel_sizes,
strides,
output_shape,
'channels_first')
inputs_cl = np.transpose(inputs, [0, 2] + list(range(3, dim + 2)) +
[1])
inputs_cl = keras.backend.variable(inputs_cl)
kernel_cl = np.reshape(
np.transpose(kernel, list(range(dim)) + [dim + 1, dim, dim + 2]),
kernel_shape
)
kernel_cl = keras.backend.variable(kernel_cl)
conv_cl = keras.backend.local_conv(inputs_cl,
kernel_cl,
kernel_sizes,
strides,
output_shape,
'channels_last')
conv_cf = keras.backend.eval(conv_cf)
conv_cl = keras.backend.eval(conv_cl)
self.assertAllCloseAccordingToType(
conv_cf,
np.transpose(conv_cl,
[0, dim + 1] + list(range(1, dim + 1))),
atol=1e-5
)
@parameterized.named_parameters(
('local_conv1d', (5, 6), (3,), (1,), (3,)),
('local_conv2d', (4, 5, 6), (3, 3), (1, 1), (2, 3)))
def test_local_conv_1d_and_2d(self,
input_shape,
kernel_sizes,
strides,
output_shape):
filters = 3
batch_size = 2
inputs = np.random.normal(0, 1, (batch_size,) + input_shape)
inputs = keras.backend.variable(inputs)
kernel = np.random.normal(0, 1, (np.prod(output_shape),
np.prod(kernel_sizes) * input_shape[-1],
filters))
kernel = keras.backend.variable(kernel)
local_conv = keras.backend.local_conv(inputs,
kernel,
kernel_sizes,
strides,
output_shape,
'channels_last')
if len(output_shape) == 1:
local_conv_dim = keras.backend.local_conv1d(inputs,
kernel,
kernel_sizes,
strides,
'channels_last')
else:
local_conv_dim = keras.backend.local_conv2d(inputs,
kernel,
kernel_sizes,
strides,
output_shape,
'channels_last')
local_conv = keras.backend.eval(local_conv)
local_conv_dim = keras.backend.eval(local_conv_dim)
self.assertAllCloseAccordingToType(local_conv, local_conv_dim)
def test_conv2d(self):
val = np.random.random((10, 4, 10, 10))
x = keras.backend.variable(val)
kernel_val = np.random.random((3, 3, 4, 5))
k = keras.backend.variable(kernel_val)
y = keras.backend.conv2d(x, k,
padding='valid', data_format='channels_first')
self.assertEqual(y.get_shape().as_list(), [10, 5, 8, 8])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv2d(x, k, strides=(1, 1),
padding='valid', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 8, 8, 5])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv2d(x, k, strides=(1, 1),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 10, 10, 5])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv2d(x, k, strides=(2, 2),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 5, 5, 5])
with self.assertRaises(ValueError):
y = keras.backend.conv2d(x, k, (2, 2),
padding='other', data_format='channels_last')
with self.assertRaises(ValueError):
y = keras.backend.conv2d(x, k, (2, 2),
data_format='other')
with self.assertRaises(ValueError):
y = keras.backend.conv2d(x, k, (2, 2, 2))
def test_separable_conv2d(self):
val = np.random.random((10, 4, 10, 10))
x = keras.backend.variable(val)
depthwise_kernel_val = np.random.random((3, 3, 4, 1))
pointwise_kernel_val = np.random.random((1, 1, 4, 5))
dk = keras.backend.variable(depthwise_kernel_val)
pk = keras.backend.variable(pointwise_kernel_val)
y = keras.backend.separable_conv2d(
x, dk, pk, padding='valid', data_format='channels_first')
self.assertEqual(y.get_shape().as_list(), [10, 5, 8, 8])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.separable_conv2d(
x, dk, pk, strides=(1, 1), padding='valid', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 8, 8, 5])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.separable_conv2d(
x, dk, pk, strides=(1, 1), padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 10, 10, 5])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.separable_conv2d(
x, dk, pk, strides=(2, 2), padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 5, 5, 5])
with self.assertRaises(ValueError):
y = keras.backend.separable_conv2d(
x, dk, pk, (2, 2), padding='other', data_format='channels_last')
with self.assertRaises(ValueError):
y = keras.backend.separable_conv2d(
x, dk, pk, (2, 2), data_format='other')
with self.assertRaises(ValueError):
y = keras.backend.separable_conv2d(x, dk, pk, (2, 2, 2))
def test_conv3d(self):
val = np.random.random((10, 4, 10, 10, 10))
x = keras.backend.variable(val)
kernel_val = np.random.random((3, 3, 3, 4, 5))
k = keras.backend.variable(kernel_val)
y = keras.backend.conv3d(x, k,
padding='valid', data_format='channels_first')
self.assertEqual(y.get_shape().as_list(), [10, 5, 8, 8, 8])
val = np.random.random((10, 10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv3d(x, k, strides=(1, 1, 1),
padding='valid', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 8, 8, 8, 5])
val = np.random.random((10, 10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv3d(x, k, strides=(1, 1, 1),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 10, 10, 10, 5])
val = np.random.random((10, 10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv3d(x, k, strides=(2, 2, 2),
padding='same', data_format='channels_last')
self.assertEqual(y.get_shape().as_list(), [10, 5, 5, 5, 5])
with self.assertRaises(ValueError):
y = keras.backend.conv3d(x, k, (2, 2, 2),
padding='other', data_format='channels_last')
with self.assertRaises(ValueError):
y = keras.backend.conv3d(x, k, (2, 2, 2),
data_format='other')
with self.assertRaises(ValueError):
y = keras.backend.conv3d(x, k, (2, 2))
def test_rnn(self):
# implement a simple RNN
num_samples = 4
input_dim = 5
output_dim = 3
timesteps = 6
input_val = np.random.random(
(num_samples, timesteps, input_dim)).astype(np.float32)
init_state_val = np.random.random(
(num_samples, output_dim)).astype(np.float32)
w_i_val = np.random.random((input_dim, output_dim)).astype(np.float32)
w_o_val = np.random.random((output_dim, output_dim)).astype(np.float32)
np_mask = np.random.randint(2, size=(num_samples, timesteps))
def rnn_step_fn():
w_i = keras.backend.variable(w_i_val)
w_o = keras.backend.variable(w_o_val)
def step_function(x, states):
assert len(states) == 1
prev_output = states[0]
output = keras.backend.dot(x, w_i) + keras.backend.dot(prev_output, w_o)
return output, [output]
return step_function
# test default setup
last_output_list = [[], [], [], [], [], []]
outputs_list = [[], [], [], [], [], []]
state_list = [[], [], [], [], [], []]
rnn_fn = rnn_step_fn()
inputs = keras.backend.variable(input_val)
initial_states = [keras.backend.variable(init_state_val)]
mask = keras.backend.variable(np_mask)
kwargs_list = [
{'go_backwards': False, 'mask': None},
{'go_backwards': False, 'mask': None, 'unroll': True},
{'go_backwards': True, 'mask': None},
{'go_backwards': True, 'mask': None, 'unroll': True},
{'go_backwards': False, 'mask': mask},
{'go_backwards': False, 'mask': mask, 'unroll': True},
]
for i, kwargs in enumerate(kwargs_list):
last_output, outputs, new_states = keras.backend.rnn(rnn_fn, inputs,
initial_states,
**kwargs)
# check static shape inference
self.assertEqual(last_output.get_shape().as_list(),
[num_samples, output_dim])
self.assertEqual(outputs.get_shape().as_list(),
[num_samples, timesteps, output_dim])
for state in new_states:
self.assertEqual(state.get_shape().as_list(),
[num_samples, output_dim])
last_output_list[i].append(keras.backend.eval(last_output))
outputs_list[i].append(keras.backend.eval(outputs))
self.assertLen(new_states, 1)
state_list[i].append(keras.backend.eval(new_states[0]))
def assert_list_pairwise(z_list, atol=1e-05):
for (z1, z2) in zip(z_list[1:], z_list[:-1]):
self.assertAllClose(z1, z2, atol=atol)
assert_list_pairwise(last_output_list[0], atol=1e-04)
assert_list_pairwise(outputs_list[0], atol=1e-04)
assert_list_pairwise(state_list[0], atol=1e-04)
assert_list_pairwise(last_output_list[2], atol=1e-04)
assert_list_pairwise(outputs_list[2], atol=1e-04)
assert_list_pairwise(state_list[2], atol=1e-04)
for l, u_l in zip(last_output_list[0], last_output_list[1]):
self.assertAllClose(l, u_l, atol=1e-04)
for o, u_o in zip(outputs_list[0], outputs_list[1]):
self.assertAllClose(o, u_o, atol=1e-04)
for s, u_s in zip(state_list[0], state_list[1]):
self.assertAllClose(s, u_s, atol=1e-04)
for b_l, b_u_l in zip(last_output_list[2], last_output_list[3]):
self.assertAllClose(b_l, b_u_l, atol=1e-04)
for b_o, b_u_o in zip(outputs_list[2], outputs_list[3]):
self.assertAllClose(b_o, b_u_o, atol=1e-04)
for b_s, b_u_s in zip(state_list[2], state_list[3]):
self.assertAllClose(b_s, b_u_s, atol=1e-04)
def test_rnn_additional_states(self):
# implement a simple RNN
num_samples = 4
input_dim = 5
output_dim = 3
timesteps = 6
input_val = np.random.random(
(num_samples, timesteps, input_dim)).astype(np.float32)
init_state_val = np.random.random(
(num_samples, output_dim)).astype(np.float32)
w_i_val = np.random.random((input_dim, output_dim)).astype(np.float32)
w_o_val = np.random.random((output_dim, output_dim)).astype(np.float32)
np_mask = np.random.randint(2, size=(num_samples, timesteps))
def rnn_step_fn():
w_i = keras.backend.variable(w_i_val)
w_o = keras.backend.variable(w_o_val)
def step_function(x, states):
assert len(states) == 2
prev_output = states[0]
output = keras.backend.dot(x, w_i) + keras.backend.dot(prev_output, w_o)
return output, [output,
keras.backend.concatenate([output, output], axis=-1)]
return step_function
# test default setup
last_output_list = [[], [], [], [], [], []]
outputs_list = [[], [], [], [], [], []]
state_list = [[], [], [], [], [], []]
additional_state_list = [[], [], [], [], [], []]
rnn_fn = rnn_step_fn()
inputs = keras.backend.variable(input_val)
initial_states = [
keras.backend.variable(init_state_val),
ops.convert_to_tensor(
np.concatenate([init_state_val, init_state_val], axis=-1))
]
mask = keras.backend.variable(np_mask)
kwargs_list = [
{'go_backwards': False, 'mask': None},
{'go_backwards': False, 'mask': None, 'unroll': True},
{'go_backwards': True, 'mask': None},
{'go_backwards': True, 'mask': None, 'unroll': True},
{'go_backwards': False, 'mask': mask},
{'go_backwards': False, 'mask': mask, 'unroll': True},
]
for i, kwargs in enumerate(kwargs_list):
last_output, outputs, new_states = keras.backend.rnn(rnn_fn, inputs,
initial_states,
**kwargs)
# check static shape inference
self.assertEqual(last_output.get_shape().as_list(),
[num_samples, output_dim])
self.assertEqual(outputs.get_shape().as_list(),
[num_samples, timesteps, output_dim])
# for state in new_states:
# self.assertEqual(state.get_shape().as_list(),
# [num_samples, output_dim])
self.assertEqual(new_states[0].get_shape().as_list(),
[num_samples, output_dim])
self.assertEqual(new_states[1].get_shape().as_list(),
[num_samples, 2 * output_dim])
last_output_list[i].append(keras.backend.eval(last_output))
outputs_list[i].append(keras.backend.eval(outputs))
self.assertLen(new_states, 2)
state_list[i].append(keras.backend.eval(new_states[0]))
additional_state_list[i].append(keras.backend.eval(new_states[1]))
def assert_list_pairwise(z_list, atol=1e-05):
for (z1, z2) in zip(z_list[1:], z_list[:-1]):
self.assertAllClose(z1, z2, atol=atol)
assert_list_pairwise(last_output_list[0], atol=1e-04)
assert_list_pairwise(outputs_list[0], atol=1e-04)
assert_list_pairwise(state_list[0], atol=1e-04)
assert_list_pairwise(additional_state_list[0], atol=1e-04)
assert_list_pairwise(last_output_list[2], atol=1e-04)
assert_list_pairwise(outputs_list[2], atol=1e-04)
assert_list_pairwise(state_list[2], atol=1e-04)
assert_list_pairwise(additional_state_list[2], atol=1e-04)
for l, u_l in zip(last_output_list[0], last_output_list[1]):
self.assertAllClose(l, u_l, atol=1e-04)
for o, u_o in zip(outputs_list[0], outputs_list[1]):
self.assertAllClose(o, u_o, atol=1e-04)
for s, u_s in zip(state_list[0], state_list[1]):
self.assertAllClose(s, u_s, atol=1e-04)
for s, u_s in zip(additional_state_list[0], additional_state_list[1]):
self.assertAllClose(s, u_s, atol=1e-04)
for b_l, b_u_l in zip(last_output_list[2], last_output_list[3]):
self.assertAllClose(b_l, b_u_l, atol=1e-04)
for b_o, b_u_o in zip(outputs_list[2], outputs_list[3]):
self.assertAllClose(b_o, b_u_o, atol=1e-04)
for b_s, b_u_s in zip(state_list[2], state_list[3]):
self.assertAllClose(b_s, b_u_s, atol=1e-04)
for s, u_s in zip(additional_state_list[2], additional_state_list[3]):
self.assertAllClose(s, u_s, atol=1e-04)
def test_rnn_output_and_state_masking_independent(self):
num_samples = 2
num_timesteps = 4
state_and_io_size = 2
mask_last_num_timesteps = 2 # for second sample only
# a step function that just outputs inputs,
# but increments states +1 per timestep
def step_function(inputs, states):
return inputs, [s + 1 for s in states]
inputs_vals = np.random.random((num_samples, num_timesteps,
state_and_io_size))
initial_state_vals = np.random.random((num_samples, state_and_io_size))
# masking of two last timesteps for second sample only
mask_vals = np.ones((num_samples, num_timesteps))
mask_vals[1, -mask_last_num_timesteps:] = 0
# outputs expected to be same as inputs for the first sample
expected_outputs = inputs_vals.copy()
# but for the second sample all outputs in masked region should be the same
# as last output before masked region
expected_outputs[1, -mask_last_num_timesteps:] = \
expected_outputs[1, -(mask_last_num_timesteps + 1)]
expected_last_state = initial_state_vals.copy()
# first state should be incremented for every timestep (no masking)
expected_last_state[0] += num_timesteps
# second state should not be incremented for last two timesteps
expected_last_state[1] += (num_timesteps - mask_last_num_timesteps)
# verify same expected output for `unroll=true/false`
inputs = keras.backend.variable(inputs_vals)
initial_states = [keras.backend.variable(initial_state_vals)]
mask = keras.backend.variable(mask_vals)
for unroll in [True, False]:
_, outputs, last_states = keras.backend.rnn(
step_function,
inputs,
initial_states,
mask=mask,
unroll=unroll,
input_length=num_timesteps if unroll else None)
self.assertAllClose(keras.backend.eval(outputs), expected_outputs)
self.assertAllClose(
keras.backend.eval(last_states[0]), expected_last_state)
def test_rnn_output_num_dim_larger_than_2_masking(self):
num_samples = 3
num_timesteps = 4
num_features = 5
def step_function(inputs, states):
outputs = keras.backend.tile(keras.backend.expand_dims(inputs), [1, 1, 2])
return outputs, [keras.backend.identity(s) for s in states]
# Note: cannot just return states (which can be a problem) ->
# tensorflow/python/ops/resource_variable_ops.py", line 824, in set_shape
# NotImplementedError: ResourceVariable does not implement set_shape()
inputs_vals = np.random.random((num_samples, num_timesteps, num_features))
initial_state_vals = np.random.random((num_samples, 6))
mask_vals = np.ones((num_samples, num_timesteps))
mask_vals[-1, -1] = 0 # final timestep masked for last sample
expected_outputs = np.repeat(inputs_vals[..., None], repeats=2, axis=-1)
# for the last sample, the final timestep (in masked region) should be the
# same as the second to final output (before masked region)
expected_outputs[-1, -1] = expected_outputs[-1, -2]
inputs = keras.backend.variable(inputs_vals)
initial_states = [keras.backend.variable(initial_state_vals)]
mask = keras.backend.variable(mask_vals)
for unroll in [True, False]:
_, outputs, _ = keras.backend.rnn(
step_function,
inputs,
initial_states,
mask=mask,
unroll=unroll,
input_length=num_timesteps if unroll else None)
self.assertAllClose(keras.backend.eval(outputs), expected_outputs)
def test_rnn_state_num_dim_larger_than_2_masking(self):
num_samples = 3
num_timesteps = 4
def step_function(inputs, states):
return inputs, [s + 1 for s in states]
inputs_vals = np.random.random((num_samples, num_timesteps, 5))
initial_state_vals = np.random.random((num_samples, 6, 7))
mask_vals = np.ones((num_samples, num_timesteps))
mask_vals[0, -2:] = 0 # final two timesteps masked for first sample
expected_last_state = initial_state_vals.copy()
expected_last_state[0] += (num_timesteps - 2)
expected_last_state[1:] += num_timesteps
inputs = keras.backend.variable(inputs_vals)
initial_states = [keras.backend.variable(initial_state_vals)]
mask = keras.backend.variable(mask_vals)
for unroll in [True, False]:
_, _, last_states = keras.backend.rnn(
step_function,
inputs,
initial_states,
mask=mask,
unroll=unroll,
input_length=num_timesteps if unroll else None)
self.assertAllClose(
keras.backend.eval(last_states[0]), expected_last_state)
def test_normalize_batch_in_training(self):
val = np.random.random((10, 3, 10, 10))
x = keras.backend.variable(val)
reduction_axes = (0, 2, 3)
g_val = np.random.random((3,))
b_val = np.random.random((3,))
gamma = keras.backend.variable(g_val)
beta = keras.backend.variable(b_val)
normed, mean, var = keras.backend.normalize_batch_in_training(
x, gamma, beta, reduction_axes, epsilon=1e-3)
self.assertEqual(normed.get_shape().as_list(), [10, 3, 10, 10])
self.assertEqual(mean.get_shape().as_list(), [3,])
self.assertEqual(var.get_shape().as_list(), [3,])
# case: gamma=None
gamma = None
normed, mean, var = keras.backend.normalize_batch_in_training(
x, gamma, beta, reduction_axes, epsilon=1e-3)
self.assertEqual(normed.get_shape().as_list(), [10, 3, 10, 10])
self.assertEqual(mean.get_shape().as_list(), [3,])
self.assertEqual(var.get_shape().as_list(), [3,])
# case: beta=None
beta = None
normed, mean, var = keras.backend.normalize_batch_in_training(
x, gamma, beta, reduction_axes, epsilon=1e-3)
self.assertEqual(normed.get_shape().as_list(), [10, 3, 10, 10])
self.assertEqual(mean.get_shape().as_list(), [3,])
self.assertEqual(var.get_shape().as_list(), [3,])
@test_util.run_all_in_graph_and_eager_modes
class TestCTC(test.TestCase):
def test_ctc_decode(self):
depth = 6
seq_len_0 = 5
input_prob_matrix_0 = np.asarray(
[[0.30999, 0.309938, 0.0679938, 0.0673362, 0.0708352, 0.173908],
[0.215136, 0.439699, 0.0370931, 0.0393967, 0.0381581, 0.230517],
[0.199959, 0.489485, 0.0233221, 0.0251417, 0.0233289, 0.238763],
[0.279611, 0.452966, 0.0204795, 0.0209126, 0.0194803, 0.20655],
[0.51286, 0.288951, 0.0243026, 0.0220788, 0.0219297, 0.129878],
# Random entry added in at time=5
[0.155251, 0.164444, 0.173517, 0.176138, 0.169979, 0.160671]],
dtype=np.float32)
# len max_time_steps array of batch_size x depth matrices
inputs = ([input_prob_matrix_0[t, :][np.newaxis, :]
for t in range(seq_len_0)] + # Pad to max_time_steps = 8
2 * [np.zeros((1, depth), dtype=np.float32)])
inputs = keras.backend.variable(np.asarray(inputs).transpose((1, 0, 2)))
# batch_size length vector of sequence_lengths
input_length = keras.backend.variable(
np.array([seq_len_0], dtype=np.int32))
# batch_size length vector of negative log probabilities
log_prob_truth = np.array([
-3.5821197, # output beam 0
-3.777835 # output beam 1
], np.float32)[np.newaxis, :]
decode_truth = [np.array([1, 0]), np.array([0, 1, 0])]
beam_width = 2
top_paths = 2
decode_pred_tf, log_prob_pred_tf = keras.backend.ctc_decode(
inputs,
input_length,
greedy=False,
beam_width=beam_width,
top_paths=top_paths)
self.assertEqual(len(decode_pred_tf), top_paths)
log_prob_pred = keras.backend.eval(log_prob_pred_tf)
for i in range(top_paths):
self.assertTrue(
np.alltrue(
decode_truth[i] == keras.backend.eval(decode_pred_tf[i])))
self.assertAllClose(log_prob_truth, log_prob_pred)
@test_util.run_v1_only('b/120545219')
def test_ctc_batch_cost(self):
with self.cached_session():
label_lens = np.expand_dims(np.asarray([5, 4]), 1)
input_lens = np.expand_dims(np.asarray([5, 5]), 1) # number of timesteps
loss_log_probs = [3.34211, 5.42262]
# dimensions are batch x time x categories
labels = np.asarray([[0, 1, 2, 1, 0], [0, 1, 1, 0, -1]])
inputs = np.asarray(
[[[0.633766, 0.221185, 0.0917319, 0.0129757, 0.0142857, 0.0260553],
[0.111121, 0.588392, 0.278779, 0.0055756, 0.00569609, 0.010436],
[0.0357786, 0.633813, 0.321418, 0.00249248, 0.00272882, 0.0037688],
[0.0663296, 0.643849, 0.280111, 0.00283995, 0.0035545, 0.00331533],
[0.458235, 0.396634, 0.123377, 0.00648837, 0.00903441, 0.00623107]],
[[0.30176, 0.28562, 0.0831517, 0.0862751, 0.0816851, 0.161508],
[0.24082, 0.397533, 0.0557226, 0.0546814, 0.0557528, 0.19549],
[0.230246, 0.450868, 0.0389607, 0.038309, 0.0391602, 0.202456],
[0.280884, 0.429522, 0.0326593, 0.0339046, 0.0326856, 0.190345],
[0.423286, 0.315517, 0.0338439, 0.0393744, 0.0339315, 0.154046]]],
dtype=np.float32)
labels = keras.backend.variable(labels, dtype='int32')
inputs = keras.backend.variable(inputs, dtype='float32')
input_lens = keras.backend.variable(input_lens, dtype='int32')
label_lens = keras.backend.variable(label_lens, dtype='int32')
res = keras.backend.eval(
keras.backend.ctc_batch_cost(labels, inputs, input_lens, label_lens))
self.assertAllClose(res[:, 0], loss_log_probs, atol=1e-05)
# test when batch_size = 1, that is, one sample only
ref = [3.34211]
input_lens = np.expand_dims(np.asarray([5]), 1)
label_lens = np.expand_dims(np.asarray([5]), 1)
labels = np.asarray([[0, 1, 2, 1, 0]])
inputs = np.asarray(
[[[0.633766, 0.221185, 0.0917319, 0.0129757, 0.0142857, 0.0260553], [
0.111121, 0.588392, 0.278779, 0.0055756, 0.00569609, 0.010436
], [0.0357786, 0.633813, 0.321418, 0.00249248, 0.00272882, 0.0037688],
[0.0663296, 0.643849, 0.280111, 0.00283995, 0.0035545, 0.00331533],
[0.458235, 0.396634, 0.123377, 0.00648837, 0.00903441, 0.00623107]]
],
dtype=np.float32)
k_labels = keras.backend.variable(labels, dtype='int32')
k_inputs = keras.backend.variable(inputs, dtype='float32')
k_input_lens = keras.backend.variable(input_lens, dtype='int32')
k_label_lens = keras.backend.variable(label_lens, dtype='int32')
res = keras.backend.eval(
keras.backend.ctc_batch_cost(k_labels, k_inputs, k_input_lens,
k_label_lens))
self.assertAllClose(res[:, 0], ref, atol=1e-05)
@test_util.run_all_in_graph_and_eager_modes
class TestRandomOps(test.TestCase):
def test_random_binomial(self):
np.random.seed(123)
x = keras.backend.random_binomial((1000, 1000), p=0.5)
self.assertAllClose(np.mean(keras.backend.eval(x)), 0.5, atol=0.1)
def test_truncated_normal(self):
np.random.seed(123)
x = keras.backend.truncated_normal((1000, 1000), mean=0.0, stddev=1.0)
y = keras.backend.eval(x)
self.assertAllClose(np.mean(y), 0., atol=0.1)
self.assertAllClose(np.std(y), 0.88, atol=0.1)
self.assertAllClose(np.max(y), 2., atol=0.1)
self.assertAllClose(np.min(y), -2., atol=0.1)
def test_string_input(self):
seq = keras.Sequential([
keras.layers.InputLayer(input_shape=(1,), dtype=dtypes.string),
keras.layers.Lambda(lambda x: x[0])
])
preds = seq.predict([['tensorflow eager']])
self.assertEqual(preds.shape, (1,))
class BackendGraphTests(test.TestCase):
@test_util.run_deprecated_v1
def test_is_placeholder(self):
x = keras.backend.placeholder(shape=(1,))
self.assertEqual(keras.backend.is_placeholder(x), True)
# Test with TF placeholder
x = keras.backend.array_ops.placeholder(dtype='float32', shape=(1,))
self.assertEqual(keras.backend.is_placeholder(x), True)
x = keras.backend.variable(1)
self.assertEqual(keras.backend.is_placeholder(x), False)
@test_util.run_in_graph_and_eager_modes
def test_function_basics(self):
x1 = keras.backend.placeholder(shape=(), dtype='float32')
x2 = keras.backend.placeholder(shape=(), dtype='int32')
v = keras.backend.variable(10.)
with keras.backend.get_graph().as_default():
y1 = x1 + keras.backend.cast(x2, 'float32') + v
y2 = x1 * keras.backend.cast(x2, 'float32')
with ops.control_dependencies([y1]):
u = keras.backend.update(v, 5.)
f = keras.backend.function([x1, x2], [y1, y2], updates=[u])
output_values = f([2, 3])
self.assertEqual(output_values, [15., 6.])
self.assertEqual(keras.backend.eval(v), 5.)
@test_util.run_in_graph_and_eager_modes
def test_function_placeholder_with_default(self):
with keras.backend.get_graph().as_default():
x1 = array_ops.placeholder_with_default(
np.array(2., dtype='float32'), shape=())
x2 = array_ops.placeholder_with_default(
np.array(3, dtype='int32'), shape=())
y1 = x1 + keras.backend.cast(x2, 'float32')
y2 = x1 * keras.backend.cast(x2, 'float32')
f = keras.backend.function([x1, x2], [y1, y2])
output_values = f([4, 5])
self.assertEqual(output_values, [9., 20.])
output_values = f([None, None])
self.assertEqual(output_values, [5., 6.])
@test_util.run_deprecated_v1
def test_function_tf_feed_symbols(self):
# Test Keras backend functions with TF tensor inputs.
with self.cached_session():
# Test feeding a resource variable to `function`.
x1 = keras.backend.placeholder(shape=())
x2 = keras.backend.placeholder(shape=())
lr = keras.backend.learning_phase() # Include a placeholder_with_default.
y1 = keras.backend.variable(10.)
y2 = 3
f = keras.backend.function(
inputs=[x1, x2, lr],
outputs=[x1 + 1, keras.backend.in_train_phase(x2 + 2, x2 - 1)])
outs = f([y1, y2, None]) # Use default learning_phase value.
self.assertEqual(outs, [11., 2.])
outs = f([y1, y2, 1]) # Set learning phase value.
self.assertEqual(outs, [11., 5.])
# Test triggering a callable refresh by changing the input.
y3 = keras.backend.constant(20.) # Test with tensor
outs = f([y3, y2, None])
self.assertEqual(outs, [21., 2.])
y4 = 4 # Test with non-symbol
outs = f([y4, y2, None])
self.assertEqual(outs, [5., 2.])
# Test with a different dtype
y5 = keras.backend.constant(10., dtype='float64')
outs = f([y5, y2, None])
self.assertEqual(outs, [11., 2.])
@test_util.run_deprecated_v1
def test_function_tf_fetches(self):
# Additional operations can be passed to tf.Session().run() via its
# `fetches` arguments. In contrast to `updates` argument of
# keras.backend.function() these do not have control dependency on `outputs`
# so they can run in parallel. Also they should not contribute to output of
# keras.backend.function().
with self.cached_session():
x = keras.backend.variable(0.)
y = keras.backend.variable(0.)
x_placeholder = keras.backend.placeholder(shape=())
y_placeholder = keras.backend.placeholder(shape=())
f = keras.backend.function(
inputs=[x_placeholder, y_placeholder],
outputs=[x_placeholder + y_placeholder],
updates=[(x, x_placeholder + 1.)],
fetches=[keras.backend.update(y, 5.)])
output = f([10., 20.])
self.assertEqual(output, [30.])
self.assertEqual(keras.backend.get_session().run(fetches=[x, y]),
[11., 5.])
@test_util.run_deprecated_v1
def test_function_tf_feed_dict(self):
# Additional substitutions can be passed to `tf.Session().run()` via its
# `feed_dict` arguments. Note that the feed_dict is passed once in the
# constructor but we can modify the values in the dictionary. Through
# this feed_dict we can provide additional substitutions besides Keras
# inputs.
with self.cached_session():
x = keras.backend.variable(0.)
y = keras.backend.variable(0.)
x_placeholder = keras.backend.placeholder(shape=())
y_placeholder = keras.backend.placeholder(shape=())
feed_dict = {y_placeholder: 3.}
fetches = [keras.backend.update(y, y_placeholder * 10.)]
f = keras.backend.function(
inputs=[x_placeholder],
outputs=[x_placeholder + 1.],
updates=[(x, x_placeholder + 10.)],
feed_dict=feed_dict,
fetches=fetches)
output = f([10.])
self.assertEqual(output, [11.])
self.assertEqual(keras.backend.get_session().run(fetches=[x, y]),
[20., 30.])
# updated value in feed_dict will be modified within the K.function()
feed_dict[y_placeholder] = 4.
output = f([20.])
self.assertEqual(output, [21.])
self.assertEqual(keras.backend.get_session().run(fetches=[x, y]),
[30., 40.])
@test_util.run_deprecated_v1
def test_function_tf_run_options_with_run_metadata(self):
with self.cached_session():
x_placeholder = keras.backend.placeholder(shape=())
y_placeholder = keras.backend.placeholder(shape=())
run_options = config_pb2.RunOptions(output_partition_graphs=True)
run_metadata = config_pb2.RunMetadata()
# enable run_options.
f = keras.backend.function(
inputs=[x_placeholder, y_placeholder],
outputs=[x_placeholder + y_placeholder],
options=run_options,
run_metadata=run_metadata)
output = f([10., 20.])
self.assertEqual(output, [30.])
self.assertGreater(len(run_metadata.partition_graphs), 0)
# disable run_options.
f1 = keras.backend.function(
inputs=[x_placeholder, y_placeholder],
outputs=[x_placeholder + y_placeholder],
run_metadata=run_metadata)
output1 = f1([10., 20.])
self.assertEqual(output1, [30.])
self.assertEqual(len(run_metadata.partition_graphs), 0)
@test_util.run_deprecated_v1
def test_function_fetch_callbacks(self):
class CallbackStub(object):
def __init__(self):
self.times_called = 0
self.callback_result = 0
def _fetch_callback(self, result):
self.times_called += 1
self.callback_result = result
with self.cached_session():
callback = CallbackStub()
x_placeholder = keras.backend.placeholder(shape=())
y_placeholder = keras.backend.placeholder(shape=())
callback_op = x_placeholder * y_placeholder
f = keras.backend.function(
inputs=[x_placeholder, y_placeholder],
outputs=[x_placeholder + y_placeholder])
f.fetches.append(callback_op)
f.fetch_callbacks[callback_op] = callback._fetch_callback
_ = f([10., 20.])
self.assertEqual(callback.times_called, 1)
self.assertEqual(callback.callback_result, 200)
@test_util.run_in_graph_and_eager_modes
def test_function_dict_outputs(self):
x_ph = keras.backend.placeholder(shape=(), name='x')
y_ph = keras.backend.placeholder(shape=(), name='y')
outputs = {'x*y': y_ph * x_ph, 'x*x': x_ph * x_ph}
f = keras.backend.function(inputs=[x_ph, y_ph], outputs=outputs)
x, y = 2., 5.
results = f([x, y])
self.assertEqual(results['x*y'], 10.)
self.assertEqual(results['x*x'], 4)
@test_util.run_in_graph_and_eager_modes
def test_function_dict_inputs(self):
placeholders = {
'x': keras.backend.placeholder(shape=()),
'y': keras.backend.placeholder(shape=())
}
outputs = [placeholders['x'] * placeholders['y']]
f = keras.backend.function(inputs=placeholders, outputs=outputs)
results = f({'x': 2., 'y': 3.})
self.assertEqual(results[0], 6.)
@test_util.run_in_graph_and_eager_modes
def test_function_single_input_output(self):
x_ph = keras.backend.placeholder(shape=(), name='x')
output = x_ph * x_ph
f = keras.backend.function(x_ph, output)
result = f(2.)
self.assertEqual(result, 4.)
def test_placeholder(self):
x = keras.backend.placeholder(shape=(3, 4))
self.assertEqual(x.get_shape().as_list(), [3, 4])
x = keras.backend.placeholder(shape=(3, 4), sparse=True)
self.assertEqual(x.get_shape().as_list(), [3, 4])
@test_util.run_deprecated_v1
def test_batch_normalization(self):
# No eager CPU kernel.
g_val = np.random.random((3,))
b_val = np.random.random((3,))
gamma = keras.backend.variable(g_val)
beta = keras.backend.variable(b_val)
# 3D NHC case
val = np.random.random((10, 5, 3))
x = keras.backend.variable(val)
mean, var = nn.moments(x, (0, 1), None, None, False)
normed = keras.backend.batch_normalization(
x, mean, var, beta, gamma, axis=-1, epsilon=1e-3)
self.assertEqual(normed.shape.as_list(), [10, 5, 3])
# 4D NHWC case
val = np.random.random((10, 5, 5, 3))
x = keras.backend.variable(val)
mean, var = nn.moments(x, (0, 1, 2), None, None, False)
normed = keras.backend.batch_normalization(
x, mean, var, beta, gamma, axis=-1, epsilon=1e-3)
self.assertEqual(normed.shape.as_list(), [10, 5, 5, 3])
# 4D NCHW case
val = np.random.random((10, 3, 5, 5))
x = keras.backend.variable(val)
mean, var = nn.moments(x, (0, 2, 3), None, None, False)
normed = keras.backend.batch_normalization(
x, mean, var, beta, gamma, axis=1, epsilon=1e-3)
self.assertEqual(normed.shape.as_list(), [10, 3, 5, 5])
if __name__ == '__main__':
test.main()
| gautam1858/tensorflow | tensorflow/python/keras/backend_test.py | Python | apache-2.0 | 68,908 | 0.005819 |
# (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris 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 3 of the License, or
# (at your option) any later version.
#
# Iris 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 Iris. If not, see <http://www.gnu.org/licenses/>.
"""Unit tests for the `iris.plot.pcolor` function."""
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests
from iris.tests.unit.plot import TestGraphicStringCoord
if tests.MPL_AVAILABLE:
import iris.plot as iplt
@tests.skip_plot
class TestStringCoordPlot(TestGraphicStringCoord):
def test_yaxis_labels(self):
iplt.pcolor(self.cube, coords=('bar', 'str_coord'))
self.assertBoundsTickLabels('yaxis')
def test_xaxis_labels(self):
iplt.pcolor(self.cube, coords=('str_coord', 'bar'))
self.assertBoundsTickLabels('xaxis')
if __name__ == "__main__":
tests.main()
| scollis/iris | lib/iris/tests/unit/plot/test_pcolor.py | Python | gpl-3.0 | 1,395 | 0 |
"""XML parser package.
This package parses the XML file returned by the Graffiti tracker.
"""
from xmlparser import XMLParser
from xmlgenerator import XMLGenerator
from exceptions import *
__all__ = ["XMLParser", "XMLGenerator", "XMLException", "InvalidXML"]
| huanchenz/STX-h-store | tests/scripts/xml2/__init__.py | Python | gpl-3.0 | 262 | 0 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Casacore(CMakePackage):
"""A suite of c++ libraries for radio astronomy data processing."""
homepage = "https://github.com/casacore/casacore"
url = "https://github.com/casacore/casacore/archive/v2.4.1.tar.gz"
maintainers = ['mpokorny']
version('3.4.0', sha256='31f02ad2e26f29bab4a47a2a69e049d7bc511084a0b8263360e6157356f92ae1')
version('3.3.0', sha256='3a714644b908ef6e81489b792cc9b80f6d8267a275e15d38a42a6a5137d39d3d')
version('3.2.0', sha256='ae5d3786cb6dfdd7ebc5eecc0c724ff02bbf6929720bc23be43a027978e79a5f')
version('3.1.2', sha256='ac94f4246412eb45d503f1019cabe2bb04e3861e1f3254b832d9b1164ea5f281')
version('3.1.1', sha256='85d2b17d856592fb206b17e0a344a29330650a4269c80b87f8abb3eaf3dadad4')
version('3.1.0', sha256='a6adf2d77ad0d6f32995b1e297fd88d31ded9c3e0bb8f28966d7b35a969f7897')
version('3.0.0', sha256='6f0e68fd77b5c96299f7583a03a53a90980ec347bff9dfb4c0abb0e2933e6bcb')
version('2.4.1', sha256='58eccc875053b2c6fe44fe53b6463030ef169597ec29926936f18d27b5087d63')
depends_on('cmake@3.7.1:', type='build')
variant('openmp', default=False, description='Build OpenMP support')
variant('shared', default=True, description='Build shared libraries')
variant('readline', default=True, description='Build readline support')
# see note below about the reason for disabling the "sofa" variant
# variant('sofa', default=False, description='Build SOFA support')
variant('adios2', default=False, description='Build ADIOS2 support')
variant('fftpack', default=False, description='Build FFTPack')
variant('hdf5', default=False, description='Build HDF5 support')
variant('python', default=False, description='Build python support')
# Force dependency on readline in v3.2 and earlier. Although the
# presence of readline is tested in CMakeLists.txt, and casacore
# can be built without it, there's no way to control that
# dependency at build time; since many systems come with readline,
# it's better to explicitly depend on it here always.
depends_on('readline', when='@:3.2.0')
depends_on('readline', when='+readline')
depends_on('flex', type='build')
depends_on('bison', type='build')
depends_on('blas')
depends_on('lapack')
depends_on('cfitsio')
depends_on('wcslib@4.20:+cfitsio')
depends_on('fftw@3.0.0: precision=float,double', when='@3.4.0:')
depends_on('fftw@3.0.0: precision=float,double', when='~fftpack')
# SOFA dependency suffers the same problem in CMakeLists.txt as readline;
# force a dependency when building unit tests
depends_on('sofa-c', type='test')
depends_on('hdf5', when='+hdf5')
depends_on('adios2+mpi', when='+adios2')
depends_on('mpi', when='+adios2')
depends_on('python@2.6:', when='+python')
depends_on('boost+python', when='+python')
depends_on('py-numpy', when='+python')
def cmake_args(self):
args = []
spec = self.spec
args.append(self.define_from_variant('ENABLE_SHARED', 'shared'))
args.append(self.define_from_variant('USE_OPENMP', 'openmp'))
args.append(self.define_from_variant('USE_READLINE', 'readline'))
args.append(self.define_from_variant('USE_HDF5', 'hdf5'))
args.append(self.define_from_variant('USE_ADIOS2', 'adios2'))
args.append(self.define_from_variant('USE_MPI', 'adios2'))
if spec.satisfies('+adios2'):
args.append(self.define('ENABLE_TABLELOCKING', False))
# fftw3 is required by casacore starting with v3.4.0, but the
# old fftpack is still available. For v3.4.0 and later, we
# always require FFTW3 dependency with the optional addition
# of FFTPack. In older casacore versions, only one of FFTW3 or
# FFTPack can be selected.
if spec.satisfies('@3.4.0:'):
if spec.satisfies('+fftpack'):
args.append('-DBUILD_FFTPACK_DEPRECATED=YES')
args.append(self.define('USE_FFTW3', True))
else:
args.append(self.define('USE_FFTW3', spec.satisfies('~fftpack')))
# Python2 and Python3 binding
if spec.satisfies('~python'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=NO'])
elif spec.satisfies('^python@3.0.0:'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=YES'])
else:
args.extend(['-DBUILD_PYTHON=YES', '-DBUILD_PYTHON3=NO'])
args.append('-DBUILD_TESTING=OFF')
return args
def patch(self):
# Rely on CMake ability to find hdf5, available since CMake 3.7.X
os.remove('cmake/FindHDF5.cmake')
| LLNL/spack | var/spack/repos/builtin/packages/casacore/package.py | Python | lgpl-2.1 | 4,875 | 0.001846 |
"""Test ghost object support in VTK-Python
When PyVTKObject is destroyed, the vtkObjectBase that it
contained often continues to exist because references to
it still exist within VTK. When that vtkObjectBase is
returned to python, a new PyVTKObject is created.
If the PyVTKObject has a custom class or a custom dict,
then we make a "ghost" of the PyVTKObject when it is
destroyed, so that if its vtkObjectBase returns to python,
the PyVTKObject can be restored with the proper class and
dict. Each ghost has a weak pointer to its vtkObjectBase
so that it can be erased if the vtkObjectBase is destroyed.
To be tested:
- make sure custom dicts are restored
- make sure custom classes are restored
Created on Aug 19, 2010 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
class vtkCustomObject(vtk.vtkObject):
pass
class TestGhost(Testing.vtkTest):
def testGhostForDict(self):
"""Ghost an object to save the dict"""
o = vtk.vtkObject()
o.customattr = 'hello'
a = vtk.vtkVariantArray()
a.InsertNextValue(o)
i = id(o)
del o
o = vtk.vtkObject()
o = a.GetValue(0).ToVTKObject()
# make sure the id has changed, but dict the same
self.assertEqual(o.customattr, 'hello')
self.assertNotEqual(i, id(o))
def testGhostForClass(self):
"""Ghost an object to save the class"""
o = vtkCustomObject()
a = vtk.vtkVariantArray()
a.InsertNextValue(o)
i = id(o)
del o
o = vtk.vtkObject()
o = a.GetValue(0).ToVTKObject()
# make sure the id has changed, but class the same
self.assertEqual(o.__class__, vtkCustomObject)
self.assertNotEqual(i, id(o))
if __name__ == "__main__":
Testing.main([(TestGhost, 'test')])
| timkrentz/SunTracker | IMU/VTK-6.2.0/Common/Core/Testing/Python/TestGhost.py | Python | mit | 1,901 | 0.001578 |
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: OpenDrive Ltda
# Copyright (c) 2013 Opendrive Ltda
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# 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.
#
##############################################################################
from openerp.osv import osv, fields
from openerp.tools.translate import _
class Partner(osv.osv):
_inherit = 'res.partner'
_columns = {
'legal_representative': fields.char(
'Legal Representative',
),
}
| kailIII/emaresa | rent.resp/partner.py | Python | agpl-3.0 | 1,548 | 0.008398 |
'''
Created on 23/mag/2015
@author: koala
'''
import Cript
key = b'dfdfjdnjnjvnfkjn vnfj vjfk d nvkfd j'
plaintext = b'jfghksdjfghksdjfgksdhgljdkghjh fgh fhg jfhgdkjfkjg hkdfjg hkdfj ghkdf ghfdjk ghfdjkg hkdfjg h'
testoCriptato, seme, orLen = Cript.criptIt(plaintext, key)
testoDecriptato = Cript.deCriptIt(testoCriptato, key, seme, orLen)
# dec = cipher.decrypt(msg)
# def pr(iStr):
# l = len(iStr)
# print l
# r = range(l)
# print r
# for i in r:
# print i,iStr[i]
# print (Cript.hashIt("pippa"))
print (plaintext)
Cript.printHex(plaintext)
print ("seme")
Cript.printHex(seme)
print ("Testo Criptato")
Cript.printHex(testoCriptato)
print ("Testo decriptato")
print(testoDecriptato)
Cript.printHex(testoDecriptato)
if (plaintext != testoDecriptato):
print ("Errore")
| koalakoker/knote_gcrypt | GCryptNote/PyMyPackage.py | Python | gpl-2.0 | 807 | 0.007435 |
import csv
from subprocess import call#
from datetime import datetime#Importing various libraries
call(["color","F9"], shell=True)#
call(["cls"], shell = True)#Setting colour for shell
import sys, time#
import time#More libraries
prog=True#creating variable prog and assigning it as true
time.sleep(1)#
def typing(string):#Creating a function that types letter by letter
for c in string:#
sys.stdout.write(c)#
sys.stdout.flush()#
time.sleep(0.05)#
print#
def printing(string):#Creating another function that does the same, but faster
for c in string:#
sys.stdout.write(c)#
sys.stdout.flush()#
time.sleep(0.01)#<== Faster
print#
while prog==True:#
cid={
}
now=datetime.now()#variable to make time work
printing("=============================================")#using function "printing" to make text appear 1 character at a time
print "=== The time is currently ",'%s:%s:%s' % (now.hour, now.minute, now.second)," ==="#Printing the time
printing("=============================================")#
time.sleep(0.5)#
printing("=| WELCOME TO THE TILE SHOP! |=")#
time.sleep(0.5)#
printing("=| |=")#
time.sleep(0.5)#
printing("=| |=======================")#
time.sleep(0.5)#
name = raw_input ("=|What is your name? |= ")#asks for name
time.sleep(0.5)#
print "=|Welcome",name,"to the tile shop!!!!|="#greets user
time.sleep(0.5)
isCorrectNumber = False#=============================
while isCorrectNumber == False: # This loop checks is the input for length and width is float or int, not str
length = raw_input("=|Length of area in metres|= ") #
width = raw_input("=|Width of area in metres|= ") #
try:#
width = float(width)#
length = float(length)#
isCorrectNumber=True#
except ValueError:#
print "=|Invalid dimensions!|=" #
pass #==========================================
size = float(length)*float(width)#works out size
print "=|The room is",size,"metres squared, there are 4 types of tiles|="#
time.sleep(0.5)#
printing("=|Economy (asbestos) $1 per square metre|=")#
time.sleep(0.5)#
printing("=|Standard (granite) $5 per square metre|=")#
time.sleep(0.5)#
printing("=|Premium (marble) $10 per square metre|=")#
time.sleep(0.5)#
printing("=|Luxury (plutonium)$5000 per square metre|=")#
time.sleep(0.5)#
prog2=True#
while prog2==True:#This loop displays prices for room size
tileq=raw_input("=|Which type would you like?|= ").lower()#
if tileq=="economy":#
price = size*1#probably unnecessary as x*1=x
print "=|That will be $"+str(price)+"|="#
prog2=False#
elif tileq=="standard":#
price = size*5#
print "=|That will be $"+str(price)+"|="#
prog2=False#
elif tileq=="premium":#
price = size*10#
print "=|That will be $"+str(price)+"|="#
prog2=False#
elif tileq=="luxury":#
price = size*50000#
print "=|That will be $"+str(price)+"|="#
prog2=False#
prog3=True#
time.sleep(0.5)#
while prog3==True:#This loop is used to add the price of plaster if the user wants it.
tilep=raw_input("=|Would you like to buy plaster as well? It is $1 per square metre.|=").lower()#.lower is used to convert the input into lower case
time.sleep(0.5)#
if tilep=="yes":#
price = price+price*1#
print "=|That will be $"+str(price)+"|="#
prog3=False#
elif tilep=="no":#
prog3=False#
time.sleep(0.5)#
typing("Generating Unique Custom ID")#
customid=name+str(len(name))+str(len(tileq))+str(len(tilep))+str(length)+str(width)#The ID is name[lengthofname][lengthofquality][lengthofprice][length][width]
print "Your Customer ID is",str(customid)#print ID
with open ("Tiledetails.csv","ab") as csvfile:
usr=csv.writer (csvfile, delimiter=",",
quotechar=",", quoting=csv.QUOTE_MINIMAL)
usr.writerow([name,customid,tileq,size,tilep,price])
cid[len(cid)+1]=(str(name)+str(customid))
print cid
typing("=|Thanks for tiling!|=")
time.sleep(120)
call(["cls"], shell = True)
time.sleep (10)#waits 10 seconds then restarts
| husky-prophet/personal-backup | PRETEND assessment/PRETEND assessment csv.py | Python | mit | 4,661 | 0.039262 |
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implementer
from typing import Callable, List, Optional, Tuple
# Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html
irc.RPL_LOGGEDIN = "900"
irc.RPL_LOGGEDOUT = "901"
@implementer(IPlugin, IModuleData)
class AccountMetadata(ModuleData):
name = "AccountData"
core = True
def actions(self) -> List[Tuple[str, int, Callable]]:
return [ ("usermetadataupdate", 10, self.sendLoginNumeric) ]
def sendLoginNumeric(self, user: "IRCUser", key: str, oldValue: str, value: str, fromServer: Optional["IRCServer"]) -> None:
if key == "account":
if value is None:
user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out")
else:
user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value))
accounts = AccountMetadata()
| Heufneutje/txircd | txircd/modules/core/accountdata.py | Python | bsd-3-clause | 1,023 | 0.021505 |
from __future__ import absolute_import, print_function, division
import argparse
import sys
class GPUCommand:
def __init__(self, logger):
self.logger = logger
self.client = None
self.registered = False
self.active = True
def main(self, args):
import aetros.cuda_gpu
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
prog=aetros.const.__prog__ + ' gpu')
try:
print("CUDA version: " +str(aetros.cuda_gpu.get_version()))
except aetros.cuda_gpu.CudaNotImplementedException:
sys.stderr.write('It seems you dont have NVIDIA CUDA not installed properly.')
sys.exit(2)
for gpu in aetros.cuda_gpu.get_ordered_devices():
properties = aetros.cuda_gpu.get_device_properties(gpu['device'], all=True)
free, total = aetros.cuda_gpu.get_memory(gpu['device'])
print("%s GPU id=%s %s (memory %.2fGB, free %.2fGB)" %(gpu['fullId'], str(gpu['id']), properties['name'], total/1024/1024/1024, free/1024/1024/1024))
| aetros/aetros-cli | aetros/commands/GPUCommand.py | Python | mit | 1,123 | 0.005343 |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
urlpatterns = [
url(r'^', include('gsn.urls')),
]
| LSIR/gsn | gsn-webui/app/urls.py | Python | gpl-3.0 | 712 | 0 |
# Copyright 2008 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.
# Django settings for google-app-engine-django project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'dummy' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'UTC'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'hvhxfm5u=^*v&doo#oq8x*eg8+1&9sxbye@=umutgn^t_sg_nx'
# Ensure that email is not sent via SMTP by default to match the standard App
# Engine SDK behaviour. If you want to sent email via SMTP then add the name of
# your mailserver here.
EMAIL_HOST = ''
TEMPLATE_DIRS = ("mysite.templates")
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'google.appengine.ext.ndb.django_middleware.NdbDjangoMiddleware',
# 'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.middleware.doc.XViewMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
# 'django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
# 'django.core.context_processors.media', # 0.97 only.
# 'django.core.context_processors.request',
)
ROOT_URLCONF = 'urls'
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(ROOT_PATH, 'templates')
)
INSTALLED_APPS = (
'astro',
'astro.location',
'astro.chart',
# 'appengine_django',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
)
| sandeva/appspot | settings.py | Python | apache-2.0 | 3,965 | 0.002774 |
#!/usr/bin/python
from setuptools import setup, find_packages
setup(
name = "testkit-lite",
description = "Test runner for test execution",
url = "https://github.com/testkit/testkit-lite",
author = "Cathy Shen",
author_email = "cathy.shen@intel.com",
version = "2.3.4",
include_package_data = True,
data_files = [('/opt/testkit/lite/',
('VERSION', 'doc/testkit-lite_user_guide_for_tct.pdf'))],
scripts = ('testkit-lite',),
packages = find_packages(),
)
| borqsat/TCT-lite | setup.py | Python | gpl-2.0 | 506 | 0.047431 |
from PyQt4.QtGui import *
from PyQt4.QtCore import Qt
from aqt.utils import tooltip
from TranslatorAddon.Parser.PONSParser import PONSParser
# This class describes the Dialog Window in which a vocable can be translated
class TranslatorDialog(QDialog):
col0Width = 40
def __init__(self, vocable, defaultSourceLanguage, defaultTargetLanguage, defaultLoadGrammarInfos):
super(TranslatorDialog, self).__init__()
# save default values
self.defaultSrc = defaultSourceLanguage
self.defaultTgt = defaultTargetLanguage
self.defaultGram = defaultLoadGrammarInfos
# Save the looked up vocable (not updated -> use lineEdit to get current value)
self.editorVocable = vocable
self.translations = []
self.parser = PONSParser()
# set up gui
self.setupUi()
# setting up ui elements
def setupUi(self):
# Set up window
self.setWindowTitle("Translator")
self.setModal(True)
self.resize(800, 600)
self.createSettings()
# create vocab line edit, translations table etc.
self.createTranslContent()
# Add Ok and Cancel buttons
self.createButtonBox()
# bring ui elements together in main layout
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.settingsBox)
mainLayout.addWidget(self.translContentLayout)
mainLayout.addWidget(self.buttonBox)
self.setLayout(mainLayout)
self.lineEditVocable.setFocus()
def createSettings(self):
self.settingsBox = QGroupBox("Settings")
self.cmbBoxSourceLang = QComboBox()
self.cmbBoxSourceLang.addItems(sorted(self.parser.getSourceLanguages().values()))
try:
defaultLangCode = self.parser.getSourceLanguages()[self.defaultSrc]
except Exception:
defaultLangCode = ""
index = self.cmbBoxSourceLang.findText(defaultLangCode)
if index >= 0:
self.cmbBoxSourceLang.setCurrentIndex(index)
self.cmbBoxTargetLang = QComboBox()
self.updateTargetLanguages()
self.cmbBoxSourceLang.currentIndexChanged.connect(self.updateTargetLanguages)
self.chkBoxGrammarInfo = QCheckBox()
self.chkBoxGrammarInfo.setChecked(self.defaultGram)
layout = QHBoxLayout()
layout.addWidget(QLabel("Source Language"))
layout.addWidget(self.cmbBoxSourceLang)
layout.addStretch(1)
layout.addWidget(QLabel("Target Language"))
layout.addWidget(self.cmbBoxTargetLang)
layout.addStretch(1)
layout.addWidget(self.chkBoxGrammarInfo)
layout.addWidget(QLabel("Load Grammar Infos"))
self.settingsBox.setLayout(layout)
# creates all the gui elements except for the button box on the bottom
def createTranslContent(self):
self.translContentLayout = QGroupBox("Translations")
layout = QFormLayout()
# translate button
self.buttonTranslate = QPushButton("Translate")
self.buttonTranslate.clicked.connect(self.translate)
# vocabulary line edit
self.lineEditVocable = QLineEdit(self.editorVocable)
self.lineEditVocable.returnPressed.connect(self.buttonTranslate.click)
# translations table
self.tableTranslations = QTableWidget()
self.tableTranslations.setColumnCount(3)
self.tableTranslations.setHorizontalHeaderLabels(["Use", "Vocable", "Translation"])
self.tableTranslations.horizontalHeader().setResizeMode(QHeaderView.Interactive)
self.tableTranslations.horizontalHeader().setStretchLastSection(True)
self.tableTranslations.horizontalHeader().resizeSection(0, self.col0Width)
self.tableTranslations.horizontalHeader().resizeSection(1, (self.tableTranslations.size().width() - self.col0Width) / 2)
self.tableTranslations.verticalHeader().hide()
policy = QSizePolicy()
policy.setHorizontalPolicy(policy.Expanding)
policy.setVerticalPolicy(policy.Expanding)
policy.setVerticalStretch(1)
self.tableTranslations.setSizePolicy(policy)
layout.addRow(QLabel("Vocable"), self.lineEditVocable)
layout.addRow(None, self.buttonTranslate)
layout.addRow(QLabel("Translations"), self.tableTranslations)
self.translContentLayout.setLayout(layout)
# creates the 'Ok' and 'Cancel' buttons
def createButtonBox(self):
self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
QDialogButtonBox.Cancel)
self.buttonBox.accepted.connect(self.setFieldsAndAccept)
self.buttonBox.rejected.connect(self.reject)
# called function on click on translate button
def translate(self):
vocab = self.lineEditVocable.text()
src = self.parser.getLangCode(str(self.cmbBoxSourceLang.currentText()))
tgt = self.parser.getLangCode(str(self.cmbBoxTargetLang.currentText()))
grammarInfos = self.chkBoxGrammarInfo.isChecked()
translations = self.parser.getTranslation(vocab, src, tgt, grammarInfos)
self.setTableContent(translations)
# updating the content of the table
def setTableContent(self, content):
if content is None:
return
if len(content) == 0:
tooltip("No translations found.")
return
self.tableTranslations.setRowCount(len(content))
for i, row in enumerate(content):
for j, col in enumerate(row):
if j == 0:
chkBoxItem = QTableWidgetItem()
chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
chkBoxItem.setCheckState(Qt.Unchecked)
self.tableTranslations.setItem(i, j, chkBoxItem)
item = QTableWidgetItem(col)
self.tableTranslations.setItem(i, j + 1, item)
# collect selected translations and return to editor window
def setFieldsAndAccept(self):
rows = self.tableTranslations.rowCount()
for i in range(rows):
if self.tableTranslations.item(i, 0).checkState() == Qt.Checked:
self.translations.append(
[self.tableTranslations.item(i, 1).text(),
self.tableTranslations.item(i, 2).text()])
self.accept()
# Prevent the dialog from closing on enter pressed
def keyPressEvent(self, QKeyEvent):
if QKeyEvent.key() == Qt.Key_Enter or QKeyEvent.key() == Qt.Key_Return:
return
# Update the target languages in the target combo box
def updateTargetLanguages(self):
self.cmbBoxTargetLang.clear()
current = str(self.cmbBoxSourceLang.currentText())
key = self.parser.getLangCode(current)
self.cmbBoxTargetLang.addItems(sorted(self.parser.getTargetLanguages(key).values()))
try:
defaultLangCode = self.parser.getSourceLanguages()[self.defaultTgt]
except Exception:
defaultLangCode = ""
index = self.cmbBoxTargetLang.findText(defaultLangCode)
if index >= 0:
self.cmbBoxTargetLang.setCurrentIndex(index) | jannewulf/Anki-Translator | TranslatorAddon/GUI/TranslatorDialog.py | Python | gpl-3.0 | 7,181 | 0.004178 |
# (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 OpenStack Foundation
#
# 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.
#
"""
ZoneManager is responsible to manage access control using FC zoning
when zoning mode is set as 'fabric'.
ZoneManager provides interfaces to add connection and remove connection
for given initiator and target list associated with a FC volume attach and
detach operation.
**Related Flags**
:zone_driver: Used by:class:`ZoneManager`.
Defaults to
`cinder.zonemanager.drivers.brocade.brcd_fc_zone_driver.BrcdFCZoneDriver`
:zoning_policy: Used by: class: 'ZoneManager'. Defaults to 'none'
"""
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils
import six
from cinder import exception
from cinder.i18n import _, _LI
from cinder.volume import configuration as config
from cinder.zonemanager import fc_common
import cinder.zonemanager.fczm_constants as zone_constant
LOG = logging.getLogger(__name__)
zone_manager_opts = [
cfg.StrOpt('zone_driver',
default='cinder.zonemanager.drivers.brocade.brcd_fc_zone_driver'
'.BrcdFCZoneDriver',
help='FC Zone Driver responsible for zone management'),
cfg.StrOpt('zoning_policy',
default='initiator-target',
help='Zoning policy configured by user; valid values include '
'"initiator-target" or "initiator"'),
cfg.StrOpt('fc_fabric_names',
help='Comma separated list of Fibre Channel fabric names.'
' This list of names is used to retrieve other SAN credentials'
' for connecting to each SAN fabric'),
cfg.StrOpt('fc_san_lookup_service',
default='cinder.zonemanager.drivers.brocade'
'.brcd_fc_san_lookup_service.BrcdFCSanLookupService',
help='FC SAN Lookup Service')
]
CONF = cfg.CONF
CONF.register_opts(zone_manager_opts, group='fc-zone-manager')
class ZoneManager(fc_common.FCCommon):
"""Manages Connection control during attach/detach.
Version History:
1.0 - Initial version
1.0.1 - Added __new__ for singleton
1.0.2 - Added friendly zone name
"""
VERSION = "1.0.2"
driver = None
fabric_names = []
def __new__(class_, *args, **kwargs):
if not hasattr(class_, "_instance"):
class_._instance = object.__new__(class_)
return class_._instance
def __init__(self, **kwargs):
"""Load the driver from the one specified in args, or from flags."""
super(ZoneManager, self).__init__(**kwargs)
self.configuration = config.Configuration(zone_manager_opts,
'fc-zone-manager')
self._build_driver()
def _build_driver(self):
zone_driver = self.configuration.zone_driver
LOG.debug("Zone driver from config: %(driver)s",
{'driver': zone_driver})
zm_config = config.Configuration(zone_manager_opts, 'fc-zone-manager')
# Initialize vendor specific implementation of FCZoneDriver
self.driver = importutils.import_object(
zone_driver,
configuration=zm_config)
def get_zoning_state_ref_count(self, initiator_wwn, target_wwn):
"""Zone management state check.
Performs state check for given I-T pair to return the current count of
active attach for the pair.
"""
# TODO(sk): ref count state management
count = 0
# check the state for I-T pair
return count
def add_connection(self, conn_info):
"""Add connection control.
Adds connection control for the given initiator target map.
initiator_target_map - each initiator WWN mapped to a list of one
or more target WWN:
eg:
{
'10008c7cff523b01': ['20240002ac000a50', '20240002ac000a40']
}
"""
connected_fabric = None
host_name = None
storage_system = None
try:
initiator_target_map = (
conn_info[zone_constant.DATA][zone_constant.IT_MAP])
if zone_constant.HOST in conn_info[zone_constant.DATA]:
host_name = conn_info[
zone_constant.DATA][
zone_constant.HOST].replace(" ", "_")
if zone_constant.STORAGE in conn_info[zone_constant.DATA]:
storage_system = (
conn_info[
zone_constant.DATA][
zone_constant.STORAGE].replace(" ", "_"))
for initiator in initiator_target_map.keys():
target_list = initiator_target_map[initiator]
LOG.debug("Target list : %(targets)s",
{'targets': target_list})
# get SAN context for the target list
fabric_map = self.get_san_context(target_list)
LOG.debug("Fabric map after context lookup: %(fabricmap)s",
{'fabricmap': fabric_map})
# iterate over each SAN and apply connection control
for fabric in fabric_map.keys():
connected_fabric = fabric
t_list = fabric_map[fabric]
# get valid I-T map to add connection control
i_t_map = {initiator: t_list}
valid_i_t_map = self.get_valid_initiator_target_map(
i_t_map, True)
LOG.info(_LI("Final filtered map for fabric: %(i_t_map)s"),
{'i_t_map': valid_i_t_map})
# Call driver to add connection control
self.driver.add_connection(fabric, valid_i_t_map,
host_name, storage_system)
LOG.info(_LI("Add connection: finished iterating "
"over all target list"))
except Exception as e:
msg = _("Failed adding connection for fabric=%(fabric)s: "
"Error: %(err)s") % {'fabric': connected_fabric,
'err': six.text_type(e)}
LOG.error(msg)
raise exception.ZoneManagerException(reason=msg)
def delete_connection(self, conn_info):
"""Delete connection.
Updates/deletes connection control for the given initiator target map.
initiator_target_map - each initiator WWN mapped to a list of one
or more target WWN:
eg:
{
'10008c7cff523b01': ['20240002ac000a50', '20240002ac000a40']
}
"""
connected_fabric = None
host_name = None
storage_system = None
try:
initiator_target_map = (
conn_info[zone_constant.DATA][zone_constant.IT_MAP])
if zone_constant.HOST in conn_info[zone_constant.DATA]:
host_name = conn_info[zone_constant.DATA][zone_constant.HOST]
if zone_constant.STORAGE in conn_info[zone_constant.DATA]:
storage_system = (
conn_info[
zone_constant.DATA][
zone_constant.STORAGE].replace(" ", "_"))
for initiator in initiator_target_map.keys():
target_list = initiator_target_map[initiator]
LOG.info(_LI("Delete connection target list: %(targets)s"),
{'targets': target_list})
# get SAN context for the target list
fabric_map = self.get_san_context(target_list)
LOG.debug("Delete connection fabric map from SAN "
"context: %(fabricmap)s", {'fabricmap': fabric_map})
# iterate over each SAN and apply connection control
for fabric in fabric_map.keys():
connected_fabric = fabric
t_list = fabric_map[fabric]
# get valid I-T map to add connection control
i_t_map = {initiator: t_list}
valid_i_t_map = self.get_valid_initiator_target_map(
i_t_map, False)
LOG.info(_LI("Final filtered map for delete connection: "
"%(i_t_map)s"), {'i_t_map': valid_i_t_map})
# Call driver to delete connection control
if len(valid_i_t_map) > 0:
self.driver.delete_connection(fabric,
valid_i_t_map,
host_name,
storage_system)
LOG.debug("Delete connection - finished iterating over all"
" target list")
except Exception as e:
msg = _("Failed removing connection for fabric=%(fabric)s: "
"Error: %(err)s") % {'fabric': connected_fabric,
'err': six.text_type(e)}
LOG.error(msg)
raise exception.ZoneManagerException(reason=msg)
def get_san_context(self, target_wwn_list):
"""SAN lookup for end devices.
Look up each SAN configured and return a map of SAN (fabric IP)
to list of target WWNs visible to the fabric.
"""
fabric_map = self.driver.get_san_context(target_wwn_list)
LOG.debug("Got SAN context: %(fabricmap)s", {'fabricmap': fabric_map})
return fabric_map
def get_valid_initiator_target_map(self, initiator_target_map,
add_control):
"""Reference count check for end devices.
Looks up the reference count for each initiator-target pair from the
map and returns a filtered list based on the operation type
add_control - operation type can be true for add connection control
and false for remove connection control
"""
filtered_i_t_map = {}
for initiator in initiator_target_map.keys():
t_list = initiator_target_map[initiator]
for target in t_list:
count = self.get_zoning_state_ref_count(initiator, target)
if add_control:
if count > 0:
t_list.remove(target)
# update count = count + 1
else:
if count > 1:
t_list.remove(target)
# update count = count - 1
if t_list:
filtered_i_t_map[initiator] = t_list
else:
LOG.info(_LI("No targets to add or remove connection for "
"initiator: %(init_wwn)s"),
{'init_wwn': initiator})
return filtered_i_t_map
| dims/cinder | cinder/zonemanager/fc_zone_manager.py | Python | apache-2.0 | 11,517 | 0 |
"""empty message
Revision ID: b5abafa45063
Revises: 4e5dd0df14b5
Create Date: 2016-08-06 22:29:36.948000
"""
# revision identifiers, used by Alembic.
revision = 'b5abafa45063'
down_revision = '4e5dd0df14b5'
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('stripe_authorizations',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('stripe_secret_key', sa.String(), nullable=True),
sa.Column('stripe_refresh_token', sa.String(), nullable=True),
sa.Column('stripe_publishable_key', sa.String(), nullable=True),
sa.Column('stripe_user_id', sa.String(), nullable=True),
sa.Column('stripe_email', sa.String(), nullable=True),
sa.Column('event_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['event_id'], ['events.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('stripe_authorizations')
### end Alembic commands ###
| Princu7/open-event-orga-server | migrations/versions/b5abafa45063_.py | Python | gpl-3.0 | 1,145 | 0.013974 |
"""This module include console commands for DanceCat."""
from __future__ import print_function
import datetime
import sqlalchemy.exc
from dateutil.relativedelta import relativedelta
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from DanceCat import app, db, Models, Constants
# pylint: disable=C0103
migrate = Migrate(app, db)
manager = Manager(app)
# pylint: enable=C0103
@manager.command
def list_all():
"""List all commands."""
print('Init database:')
print('- db_create_all')
print('Migrate Database')
print('- db init')
print('- db migrate')
print('- db upgrade')
print('- db downgrade')
print('Scheduling')
print('- schedule_update')
return True
@manager.command
def db_create_all():
"""DanceCat database initial."""
db.create_all()
@manager.command
def schedule_update():
"""Update outdated schedules on offline time."""
schedules = Models.Schedule.query.filter(
Models.Schedule.is_active,
Models.Schedule.schedule_type != Constants.SCHEDULE_ONCE,
Models.Schedule.next_run <= datetime.datetime.now()
).all()
while len(schedules) > 0:
for schedule in schedules:
print(
"Update next run time for schedule with id {id}.".format(
id=schedule.schedule_id
)
)
schedule.update_next_run(True)
schedule.next_run += relativedelta(minutes=1)
db.session.commit()
schedules = Models.Schedule.query.filter(
Models.Schedule.is_active,
Models.Schedule.next_run < datetime.datetime.now()
).all()
print("Finished!")
@manager.command
def add_allowed_user(email):
"""
Add given email to allowed_email table.
:param email: Given email that will be allowed to create new user.
:return: None.
"""
try:
allowed_email = Models.AllowedEmail(email)
db.session.add(allowed_email)
db.session.commit()
print("Added \"{email}\" to allowed users list.".format(
email=email
))
except sqlalchemy.exc.IntegrityError:
print("\"{email}\" was already in the allowed users list.".format(
email=email
))
db.session.close()
# Add Migrate commands.
manager.add_command('db', MigrateCommand)
| scattm/DanceCat | DanceCat/Console/__init__.py | Python | mit | 2,383 | 0 |
from __future__ import unicode_literals
from netaddr import EUI, AddrFormatError
from django import forms
from django.core.exceptions import ValidationError
#
# Form fields
#
class MACAddressFormField(forms.Field):
default_error_messages = {
'invalid': "Enter a valid MAC address.",
}
def to_python(self, value):
if not value:
return None
if isinstance(value, EUI):
return value
try:
return EUI(value, version=48)
except AddrFormatError:
raise ValidationError("Please specify a valid MAC address.")
| snazy2000/netbox | netbox/dcim/formfields.py | Python | apache-2.0 | 607 | 0 |
# Test the windows specific win32reg module.
# Only win32reg functions not hit here: FlushKey, LoadKey and SaveKey
import os, sys, errno
import unittest
from test import support
import threading
from platform import machine
# Do this first so test will be skipped if module doesn't exist
support.import_module('winreg', required_on=['win'])
# Now import everything
from winreg import *
try:
REMOTE_NAME = sys.argv[sys.argv.index("--remote")+1]
except (IndexError, ValueError):
REMOTE_NAME = None
# tuple of (major, minor)
WIN_VER = sys.getwindowsversion()[:2]
# Some tests should only run on 64-bit architectures where WOW64 will be.
WIN64_MACHINE = True if machine() == "AMD64" else False
# Starting with Windows 7 and Windows Server 2008 R2, WOW64 no longer uses
# registry reflection and formerly reflected keys are shared instead.
# Windows 7 and Windows Server 2008 R2 are version 6.1. Due to this, some
# tests are only valid up until 6.1
HAS_REFLECTION = True if WIN_VER < (6, 1) else False
# Use a per-process key to prevent concurrent test runs (buildbot!) from
# stomping on each other.
test_key_base = "Python Test Key [%d] - Delete Me" % (os.getpid(),)
test_key_name = "SOFTWARE\\" + test_key_base
# On OS'es that support reflection we should test with a reflected key
test_reflect_key_name = "SOFTWARE\\Classes\\" + test_key_base
test_data = [
("Int Value", 45, REG_DWORD),
("Qword Value", 0x1122334455667788, REG_QWORD),
("String Val", "A string value", REG_SZ),
("StringExpand", "The path is %path%", REG_EXPAND_SZ),
("Multi-string", ["Lots", "of", "string", "values"], REG_MULTI_SZ),
("Raw Data", b"binary\x00data", REG_BINARY),
("Big String", "x"*(2**14-1), REG_SZ),
("Big Binary", b"x"*(2**14), REG_BINARY),
# Two and three kanjis, meaning: "Japan" and "Japanese")
("Japanese 日本", "日本語", REG_SZ),
]
class BaseWinregTests(unittest.TestCase):
def setUp(self):
# Make sure that the test key is absent when the test
# starts.
self.delete_tree(HKEY_CURRENT_USER, test_key_name)
def delete_tree(self, root, subkey):
try:
hkey = OpenKey(root, subkey, 0, KEY_ALL_ACCESS)
except OSError:
# subkey does not exist
return
while True:
try:
subsubkey = EnumKey(hkey, 0)
except OSError:
# no more subkeys
break
self.delete_tree(hkey, subsubkey)
CloseKey(hkey)
DeleteKey(root, subkey)
def _write_test_data(self, root_key, subkeystr="sub_key",
CreateKey=CreateKey):
# Set the default value for this key.
SetValue(root_key, test_key_name, REG_SZ, "Default value")
key = CreateKey(root_key, test_key_name)
self.assertTrue(key.handle != 0)
# Create a sub-key
sub_key = CreateKey(key, subkeystr)
# Give the sub-key some named values
for value_name, value_data, value_type in test_data:
SetValueEx(sub_key, value_name, 0, value_type, value_data)
# Check we wrote as many items as we thought.
nkeys, nvalues, since_mod = QueryInfoKey(key)
self.assertEqual(nkeys, 1, "Not the correct number of sub keys")
self.assertEqual(nvalues, 1, "Not the correct number of values")
nkeys, nvalues, since_mod = QueryInfoKey(sub_key)
self.assertEqual(nkeys, 0, "Not the correct number of sub keys")
self.assertEqual(nvalues, len(test_data),
"Not the correct number of values")
# Close this key this way...
# (but before we do, copy the key as an integer - this allows
# us to test that the key really gets closed).
int_sub_key = int(sub_key)
CloseKey(sub_key)
try:
QueryInfoKey(int_sub_key)
self.fail("It appears the CloseKey() function does "
"not close the actual key!")
except OSError:
pass
# ... and close that key that way :-)
int_key = int(key)
key.Close()
try:
QueryInfoKey(int_key)
self.fail("It appears the key.Close() function "
"does not close the actual key!")
except OSError:
pass
def _read_test_data(self, root_key, subkeystr="sub_key", OpenKey=OpenKey):
# Check we can get default value for this key.
val = QueryValue(root_key, test_key_name)
self.assertEqual(val, "Default value",
"Registry didn't give back the correct value")
key = OpenKey(root_key, test_key_name)
# Read the sub-keys
with OpenKey(key, subkeystr) as sub_key:
# Check I can enumerate over the values.
index = 0
while 1:
try:
data = EnumValue(sub_key, index)
except OSError:
break
self.assertEqual(data in test_data, True,
"Didn't read back the correct test data")
index = index + 1
self.assertEqual(index, len(test_data),
"Didn't read the correct number of items")
# Check I can directly access each item
for value_name, value_data, value_type in test_data:
read_val, read_typ = QueryValueEx(sub_key, value_name)
self.assertEqual(read_val, value_data,
"Could not directly read the value")
self.assertEqual(read_typ, value_type,
"Could not directly read the value")
sub_key.Close()
# Enumerate our main key.
read_val = EnumKey(key, 0)
self.assertEqual(read_val, subkeystr, "Read subkey value wrong")
try:
EnumKey(key, 1)
self.fail("Was able to get a second key when I only have one!")
except OSError:
pass
key.Close()
def _delete_test_data(self, root_key, subkeystr="sub_key"):
key = OpenKey(root_key, test_key_name, 0, KEY_ALL_ACCESS)
sub_key = OpenKey(key, subkeystr, 0, KEY_ALL_ACCESS)
# It is not necessary to delete the values before deleting
# the key (although subkeys must not exist). We delete them
# manually just to prove we can :-)
for value_name, value_data, value_type in test_data:
DeleteValue(sub_key, value_name)
nkeys, nvalues, since_mod = QueryInfoKey(sub_key)
self.assertEqual(nkeys, 0, "subkey not empty before delete")
self.assertEqual(nvalues, 0, "subkey not empty before delete")
sub_key.Close()
DeleteKey(key, subkeystr)
try:
# Shouldn't be able to delete it twice!
DeleteKey(key, subkeystr)
self.fail("Deleting the key twice succeeded")
except OSError:
pass
key.Close()
DeleteKey(root_key, test_key_name)
# Opening should now fail!
try:
key = OpenKey(root_key, test_key_name)
self.fail("Could open the non-existent key")
except OSError: # Use this error name this time
pass
def _test_all(self, root_key, subkeystr="sub_key"):
self._write_test_data(root_key, subkeystr)
self._read_test_data(root_key, subkeystr)
self._delete_test_data(root_key, subkeystr)
def _test_named_args(self, key, sub_key):
with CreateKeyEx(key=key, sub_key=sub_key, reserved=0,
access=KEY_ALL_ACCESS) as ckey:
self.assertTrue(ckey.handle != 0)
with OpenKeyEx(key=key, sub_key=sub_key, reserved=0,
access=KEY_ALL_ACCESS) as okey:
self.assertTrue(okey.handle != 0)
class LocalWinregTests(BaseWinregTests):
def test_registry_works(self):
self._test_all(HKEY_CURRENT_USER)
self._test_all(HKEY_CURRENT_USER, "日本-subkey")
def test_registry_works_extended_functions(self):
# Substitute the regular CreateKey and OpenKey calls with their
# extended counterparts.
# Note: DeleteKeyEx is not used here because it is platform dependent
cke = lambda key, sub_key: CreateKeyEx(key, sub_key, 0, KEY_ALL_ACCESS)
self._write_test_data(HKEY_CURRENT_USER, CreateKey=cke)
oke = lambda key, sub_key: OpenKeyEx(key, sub_key, 0, KEY_READ)
self._read_test_data(HKEY_CURRENT_USER, OpenKey=oke)
self._delete_test_data(HKEY_CURRENT_USER)
def test_named_arguments(self):
self._test_named_args(HKEY_CURRENT_USER, test_key_name)
# Use the regular DeleteKey to clean up
# DeleteKeyEx takes named args and is tested separately
DeleteKey(HKEY_CURRENT_USER, test_key_name)
def test_connect_registry_to_local_machine_works(self):
# perform minimal ConnectRegistry test which just invokes it
h = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
self.assertNotEqual(h.handle, 0)
h.Close()
self.assertEqual(h.handle, 0)
def test_inexistant_remote_registry(self):
connect = lambda: ConnectRegistry("abcdefghijkl", HKEY_CURRENT_USER)
self.assertRaises(OSError, connect)
def testExpandEnvironmentStrings(self):
r = ExpandEnvironmentStrings("%windir%\\test")
self.assertEqual(type(r), str)
self.assertEqual(r, os.environ["windir"] + "\\test")
def test_context_manager(self):
# ensure that the handle is closed if an exception occurs
try:
with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as h:
self.assertNotEqual(h.handle, 0)
raise OSError
except OSError:
self.assertEqual(h.handle, 0)
def test_changing_value(self):
# Issue2810: A race condition in 2.6 and 3.1 may cause
# EnumValue or QueryValue to raise "WindowsError: More data is
# available"
done = False
class VeryActiveThread(threading.Thread):
def run(self):
with CreateKey(HKEY_CURRENT_USER, test_key_name) as key:
use_short = True
long_string = 'x'*2000
while not done:
s = 'x' if use_short else long_string
use_short = not use_short
SetValue(key, 'changing_value', REG_SZ, s)
thread = VeryActiveThread()
thread.start()
try:
with CreateKey(HKEY_CURRENT_USER,
test_key_name+'\\changing_value') as key:
for _ in range(1000):
num_subkeys, num_values, t = QueryInfoKey(key)
for i in range(num_values):
name = EnumValue(key, i)
QueryValue(key, name[0])
finally:
done = True
thread.join()
DeleteKey(HKEY_CURRENT_USER, test_key_name+'\\changing_value')
DeleteKey(HKEY_CURRENT_USER, test_key_name)
def test_long_key(self):
# Issue2810, in 2.6 and 3.1 when the key name was exactly 256
# characters, EnumKey raised "WindowsError: More data is
# available"
name = 'x'*256
try:
with CreateKey(HKEY_CURRENT_USER, test_key_name) as key:
SetValue(key, name, REG_SZ, 'x')
num_subkeys, num_values, t = QueryInfoKey(key)
EnumKey(key, 0)
finally:
DeleteKey(HKEY_CURRENT_USER, '\\'.join((test_key_name, name)))
DeleteKey(HKEY_CURRENT_USER, test_key_name)
def test_dynamic_key(self):
# Issue2810, when the value is dynamically generated, these
# raise "WindowsError: More data is available" in 2.6 and 3.1
try:
EnumValue(HKEY_PERFORMANCE_DATA, 0)
except OSError as e:
if e.errno in (errno.EPERM, errno.EACCES):
self.skipTest("access denied to registry key "
"(are you running in a non-interactive session?)")
raise
QueryValueEx(HKEY_PERFORMANCE_DATA, "")
# Reflection requires XP x64/Vista at a minimum. XP doesn't have this stuff
# or DeleteKeyEx so make sure their use raises NotImplementedError
@unittest.skipUnless(WIN_VER < (5, 2), "Requires Windows XP")
def test_reflection_unsupported(self):
try:
with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
self.assertNotEqual(ck.handle, 0)
key = OpenKey(HKEY_CURRENT_USER, test_key_name)
self.assertNotEqual(key.handle, 0)
with self.assertRaises(NotImplementedError):
DisableReflectionKey(key)
with self.assertRaises(NotImplementedError):
EnableReflectionKey(key)
with self.assertRaises(NotImplementedError):
QueryReflectionKey(key)
with self.assertRaises(NotImplementedError):
DeleteKeyEx(HKEY_CURRENT_USER, test_key_name)
finally:
DeleteKey(HKEY_CURRENT_USER, test_key_name)
def test_setvalueex_value_range(self):
# Test for Issue #14420, accept proper ranges for SetValueEx.
# Py2Reg, which gets called by SetValueEx, was using PyLong_AsLong,
# thus raising OverflowError. The implementation now uses
# PyLong_AsUnsignedLong to match DWORD's size.
try:
with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
self.assertNotEqual(ck.handle, 0)
SetValueEx(ck, "test_name", None, REG_DWORD, 0x80000000)
finally:
DeleteKey(HKEY_CURRENT_USER, test_key_name)
def test_queryvalueex_return_value(self):
# Test for Issue #16759, return unsigned int from QueryValueEx.
# Reg2Py, which gets called by QueryValueEx, was returning a value
# generated by PyLong_FromLong. The implementation now uses
# PyLong_FromUnsignedLong to match DWORD's size.
try:
with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
self.assertNotEqual(ck.handle, 0)
test_val = 0x80000000
SetValueEx(ck, "test_name", None, REG_DWORD, test_val)
ret_val, ret_type = QueryValueEx(ck, "test_name")
self.assertEqual(ret_type, REG_DWORD)
self.assertEqual(ret_val, test_val)
finally:
DeleteKey(HKEY_CURRENT_USER, test_key_name)
def test_setvalueex_crash_with_none_arg(self):
# Test for Issue #21151, segfault when None is passed to SetValueEx
try:
with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
self.assertNotEqual(ck.handle, 0)
test_val = None
SetValueEx(ck, "test_name", 0, REG_BINARY, test_val)
ret_val, ret_type = QueryValueEx(ck, "test_name")
self.assertEqual(ret_type, REG_BINARY)
self.assertEqual(ret_val, test_val)
finally:
DeleteKey(HKEY_CURRENT_USER, test_key_name)
def test_read_string_containing_null(self):
# Test for issue 25778: REG_SZ should not contain null characters
try:
with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
self.assertNotEqual(ck.handle, 0)
test_val = "A string\x00 with a null"
SetValueEx(ck, "test_name", 0, REG_SZ, test_val)
ret_val, ret_type = QueryValueEx(ck, "test_name")
self.assertEqual(ret_type, REG_SZ)
self.assertEqual(ret_val, "A string")
finally:
DeleteKey(HKEY_CURRENT_USER, test_key_name)
@unittest.skipUnless(REMOTE_NAME, "Skipping remote registry tests")
class RemoteWinregTests(BaseWinregTests):
def test_remote_registry_works(self):
remote_key = ConnectRegistry(REMOTE_NAME, HKEY_CURRENT_USER)
self._test_all(remote_key)
@unittest.skipUnless(WIN64_MACHINE, "x64 specific registry tests")
class Win64WinregTests(BaseWinregTests):
def test_named_arguments(self):
self._test_named_args(HKEY_CURRENT_USER, test_key_name)
# Clean up and also exercise the named arguments
DeleteKeyEx(key=HKEY_CURRENT_USER, sub_key=test_key_name,
access=KEY_ALL_ACCESS, reserved=0)
def test_reflection_functions(self):
# Test that we can call the query, enable, and disable functions
# on a key which isn't on the reflection list with no consequences.
with OpenKey(HKEY_LOCAL_MACHINE, "Software") as key:
# HKLM\Software is redirected but not reflected in all OSes
self.assertTrue(QueryReflectionKey(key))
self.assertIsNone(EnableReflectionKey(key))
self.assertIsNone(DisableReflectionKey(key))
self.assertTrue(QueryReflectionKey(key))
@unittest.skipUnless(HAS_REFLECTION, "OS doesn't support reflection")
def test_reflection(self):
# Test that we can create, open, and delete keys in the 32-bit
# area. Because we are doing this in a key which gets reflected,
# test the differences of 32 and 64-bit keys before and after the
# reflection occurs (ie. when the created key is closed).
try:
with CreateKeyEx(HKEY_CURRENT_USER, test_reflect_key_name, 0,
KEY_ALL_ACCESS | KEY_WOW64_32KEY) as created_key:
self.assertNotEqual(created_key.handle, 0)
# The key should now be available in the 32-bit area
with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,
KEY_ALL_ACCESS | KEY_WOW64_32KEY) as key:
self.assertNotEqual(key.handle, 0)
# Write a value to what currently is only in the 32-bit area
SetValueEx(created_key, "", 0, REG_SZ, "32KEY")
# The key is not reflected until created_key is closed.
# The 64-bit version of the key should not be available yet.
open_fail = lambda: OpenKey(HKEY_CURRENT_USER,
test_reflect_key_name, 0,
KEY_READ | KEY_WOW64_64KEY)
self.assertRaises(OSError, open_fail)
# Now explicitly open the 64-bit version of the key
with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,
KEY_ALL_ACCESS | KEY_WOW64_64KEY) as key:
self.assertNotEqual(key.handle, 0)
# Make sure the original value we set is there
self.assertEqual("32KEY", QueryValue(key, ""))
# Set a new value, which will get reflected to 32-bit
SetValueEx(key, "", 0, REG_SZ, "64KEY")
# Reflection uses a "last-writer wins policy, so the value we set
# on the 64-bit key should be the same on 32-bit
with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,
KEY_READ | KEY_WOW64_32KEY) as key:
self.assertEqual("64KEY", QueryValue(key, ""))
finally:
DeleteKeyEx(HKEY_CURRENT_USER, test_reflect_key_name,
KEY_WOW64_32KEY, 0)
@unittest.skipUnless(HAS_REFLECTION, "OS doesn't support reflection")
def test_disable_reflection(self):
# Make use of a key which gets redirected and reflected
try:
with CreateKeyEx(HKEY_CURRENT_USER, test_reflect_key_name, 0,
KEY_ALL_ACCESS | KEY_WOW64_32KEY) as created_key:
# QueryReflectionKey returns whether or not the key is disabled
disabled = QueryReflectionKey(created_key)
self.assertEqual(type(disabled), bool)
# HKCU\Software\Classes is reflected by default
self.assertFalse(disabled)
DisableReflectionKey(created_key)
self.assertTrue(QueryReflectionKey(created_key))
# The key is now closed and would normally be reflected to the
# 64-bit area, but let's make sure that didn't happen.
open_fail = lambda: OpenKeyEx(HKEY_CURRENT_USER,
test_reflect_key_name, 0,
KEY_READ | KEY_WOW64_64KEY)
self.assertRaises(OSError, open_fail)
# Make sure the 32-bit key is actually there
with OpenKeyEx(HKEY_CURRENT_USER, test_reflect_key_name, 0,
KEY_READ | KEY_WOW64_32KEY) as key:
self.assertNotEqual(key.handle, 0)
finally:
DeleteKeyEx(HKEY_CURRENT_USER, test_reflect_key_name,
KEY_WOW64_32KEY, 0)
def test_exception_numbers(self):
with self.assertRaises(FileNotFoundError) as ctx:
QueryValue(HKEY_CLASSES_ROOT, 'some_value_that_does_not_exist')
def test_main():
support.run_unittest(LocalWinregTests, RemoteWinregTests,
Win64WinregTests)
if __name__ == "__main__":
if not REMOTE_NAME:
print("Remote registry calls can be tested using",
"'test_winreg.py --remote \\\\machine_name'")
test_main()
| FFMG/myoddweb.piger | monitor/api/python/Python-3.7.2/Lib/test/test_winreg.py | Python | gpl-2.0 | 21,678 | 0.000554 |
from common.connector import redmine
class ViewIssues:
def __init__(self, view_type, assigned_to='me', minimal_priority=0, exclude_projects=(), milestone=None):
self.redmine = redmine()
self.assigned_to = assigned_to
self.minimal_priority = minimal_priority
self.exclude_projects = exclude_projects
self.milestone = milestone
if view_type == 'list':
self.filtered_issues()
elif view_type == 'users':
self.users = self.user_list()
else:
self.num_issues()
def colorify_priority(self, state):
if state.id == 2:
return '\033[92m'
elif state.id == 4:
return '\033[1m\033[91m**'
elif state.id == 3:
return '\033[91m'
elif state.id == 1:
return '\033[94m'
else:
return '\033[94m'
def filtered_issues(self):
i_count = 0
for p in self.redmine.project.all():
if p.name in self.exclude_projects:
continue
issues = self.redmine.issue.filter(project_id=p.identifier, assigned_to_id=self.assigned_to)
if len(issues) == 0:
continue
print('Проект: %s (%s)' % (p.name, p.identifier))
for i in issues:
try:
if self.milestone != 'all' and str(i.fixed_version) not in self.milestone:
continue
except:
continue
i_count += 1
if i.priority.id < self.minimal_priority:
continue
color_priority = self.colorify_priority(i.priority)
color_state = self.colorify_priority(i.status)
end_color = '\033[0m'
print('[%s%s%s][%s%s%s]\t%i:\t%s' %(color_priority,
i.priority,
end_color,
color_state,
i.status,end_color,
i.id, i))
print('='*10)
print('Всего: %i' % i_count)
def num_issues(self):
issues = self.redmine.issue.filter(assigned_to_id=self.assigned_to)
count = len([i for i in issues if i.priority.id >= self.minimal_priority if i.project.name not in self.exclude_projects])
print('Активных задач: %i' % count)
def user_list(self):
print(self.redmine)
return [u for u in self.redmine.users]
class Colorify:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
| ex0hunt/redrat | func/viewer.py | Python | bsd-2-clause | 2,852 | 0.00495 |
import unittest
import pdb
from day13 import *
class TestDay13(unittest.TestCase):
def test_is_wall(self):
tests = (
(0, 0, False),
(1, 0, True),
(2, 0, False),
(-1, 0, True),
(0, -1, True),
)
for x, y, expected in tests:
self.assertEqual(
is_wall(x, y, 10),
expected,
"(%d,%d) should be %s" % (x,y, expected))
def test_solve_example(self):
solution = solve((1,1), (7,4), 10)
self.assertEqual(len(solution) - 1, 11)
@unittest.skip("slow")
def test_solve_part_1(self):
solution = solve((1,1), (31,39), 1350)
self.assertEqual(len(solution) - 1, 92)
@unittest.skip("slow")
def test_solve_part_2(self):
solution = solve((1,1), (31,39), 1350, 50)
self.assertEqual(solution, 124)
if __name__ == "__main__":
unittest.main()
| chrisb87/advent_of_code_2016 | day13/test_day13.py | Python | unlicense | 783 | 0.045977 |
from django.conf.urls import patterns, include, url
from .views import MapView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url('^$', 'mobiletrans.views.index', { 'template_name':'index.html'},
name="index"),
url('^about/$', 'mobiletrans.views.about', { 'template_name':'about.html'},
name="about"),
url('^routemap/$', MapView.as_view( template_name='routemap.html'),
name="routemap"),
url('^transitheat/$', MapView.as_view( template_name='transitheat.html'),
name="transitheat"),
url('^kml/$', 'mobiletrans.mtlocation.views.renderkml', { },
name="mtlocation_renderkml"),
url('^kml/longlat/(?P<long>[-\d.]+),(?P<lat>[-\d.]+)/$',
'mobiletrans.mtlocation.views.renderkml', { },
name="mtlocation_renderkml_longlat"),
url('^kml/latlong/(?P<lat>[-\d.]+),(?P<long>[-\d.]+)/$',
'mobiletrans.mtlocation.views.renderkml', { },
name="mtlocation_renderkml_latlong"),
url('^api/', include('mobiletrans.mtapi.urls')),
)
| JoeJasinski/WindyTransit | mobiletrans/urls.py | Python | mit | 1,139 | 0.022827 |
#
# Race Capture App
#
# Copyright (C) 2014-2017 Autosport Labs
#
# This file is part of the Race Capture App
#
# This 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.
#
# This software 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 code. If not, see <http://www.gnu.org/licenses/>.
from kivy.utils import get_color_from_hex as rgb
DEFAULT_COLOR_SEQUENCE = ['A0A0A0', '8A00B8', '3366FF', 'F5B800', '8AB800', 'f45b5b', 'ff0066']
class ColorSequence(object):
color_index = 0
colors = []
color_map = {}
def __init__(self, colors=DEFAULT_COLOR_SEQUENCE):
self.colors = colors
def get_color(self, key):
color = self.color_map.get(key)
if not color:
index = self.color_index
color = rgb(self.colors[index])
index = index + 1 if index < len(self.colors) - 1 else 0
self.color_index = index
self.color_map[key] = color
return color
| autosportlabs/RaceCapture_App | autosportlabs/uix/color/colorsequence.py | Python | gpl-3.0 | 1,401 | 0.002141 |
# (c) Copyright 2013, 2014, University of Manchester
#
# HydraPlatform 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 3 of the License, or
# (at your option) any later version.
#
# HydraPlatform 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 Lesser General Public License
# along with HydraPlatform. If not, see <http://www.gnu.org/licenses/>
#
import os
import glob
import ConfigParser
import sys
import logging
global CONFIG
CONFIG = None
global localfiles
global localfile
global repofile
global repofiles
global userfile
global userfiles
global sysfile
global sysfiles
def load_config():
"""Load a config file. This function looks for a config (*.ini) file in the
following order::
(1) ./*.ini
(2) ~/.config/hydra/
(3) /etc/hydra
(4) [...]/HYDRA/HydraLib/trunk/../../config/
(1) will override (2) will override (3) will override (4). Parameters not
defined in (1) will be taken from (2). Parameters not defined in (2) will
be taken from (3). (3) is the config folder that will be checked out from
the svn repository. (2) Will be be provided as soon as an installable
distribution is available. (1) will usually be written individually by
every user."""
global localfiles
global localfile
global repofile
global repofiles
global userfile
global userfiles
global sysfile
global sysfiles
global CONFIG
logging.basicConfig(level='INFO')
config = ConfigParser.ConfigParser(allow_no_value=True)
modulepath = os.path.dirname(os.path.abspath(__file__))
localfile = os.getcwd() + '/hydra.ini'
localfiles = glob.glob(localfile)
repofile = modulepath + '/../../../config/hydra.ini'
repofiles = glob.glob(repofile)
if os.name == 'nt':
import winpaths
userfile = os.path.expanduser('~') + '/AppData/Local/hydra.ini'
userfiles = glob.glob(userfile)
sysfile = winpaths.get_common_documents() + '/Hydra/hydra.ini'
sysfiles = glob.glob(sysfile)
else:
userfile = os.path.expanduser('~') + '/.config/hydra/hydra.ini'
userfiles = glob.glob(userfile)
sysfile = '/etc/hydra/hydra.ini'
sysfiles = glob.glob(sysfile)
for ini_file in repofiles:
logging.debug("Repofile: %s"%ini_file)
config.read(ini_file)
for ini_file in sysfiles:
logging.info("Sysfile: %s"%ini_file)
config.read(ini_file)
for ini_file in userfiles:
logging.info("Userfile: %s"%ini_file)
config.read(ini_file)
for ini_file in localfiles:
logging.info("Localfile: %s"%ini_file)
config.read(ini_file)
if os.name == 'nt':
set_windows_env_variables(config)
try:
home_dir = config.get('DEFAULT', 'home_dir')
except:
home_dir = os.environ.get('HYDRA_HOME_DIR', '~')
config.set('DEFAULT', 'home_dir', os.path.expanduser(home_dir))
try:
hydra_base = config.get('DEFAULT', 'hydra_base_dir')
except:
hydra_base = os.environ.get('HYDRA_BASE_DIR', modulepath + '/../../../')
config.set('DEFAULT', 'hydra_base_dir', os.path.expanduser(hydra_base))
CONFIG = config
return config
def set_windows_env_variables(config):
import winpaths
config.set('DEFAULT', 'common_app_data_folder', winpaths.get_common_appdata())
config.set('DEFAULT', 'win_local_appdata', winpaths.get_local_appdata())
config.set('DEFAULT', 'win_appdata', winpaths.get_appdata())
config.set('DEFAULT', 'win_desktop', winpaths.get_desktop())
config.set('DEFAULT', 'win_programs', winpaths.get_programs())
config.set('DEFAULT', 'win_common_admin_tools', winpaths.get_common_admin_tools())
config.set('DEFAULT', 'win_common_documents', winpaths.get_common_documents())
config.set('DEFAULT', 'win_cookies', winpaths.get_cookies())
config.set('DEFAULT', 'win_history', winpaths.get_history())
config.set('DEFAULT', 'win_internet_cache', winpaths.get_internet_cache())
config.set('DEFAULT', 'win_my_pictures', winpaths.get_my_pictures())
config.set('DEFAULT', 'win_personal', winpaths.get_personal())
config.set('DEFAULT', 'win_my_documents', winpaths.get_my_documents())
config.set('DEFAULT', 'win_program_files', winpaths.get_program_files())
config.set('DEFAULT', 'win_program_files_common', winpaths.get_program_files_common())
config.set('DEFAULT', 'win_system', winpaths.get_system())
config.set('DEFAULT', 'win_windows', winpaths.get_windows())
config.set('DEFAULT', 'win_startup', winpaths.get_startup())
config.set('DEFAULT', 'win_recent', winpaths.get_recent())
def get(section, option, default=None):
if CONFIG is None:
load_config()
try:
return CONFIG.get(section, option)
except:
return default
def getint(section, option, default=None):
if CONFIG is None:
load_config()
try:
return CONFIG.getint(section, option)
except:
return default
| UMWRG/HydraPlatform | HydraLib/python/HydraLib/config.py | Python | gpl-3.0 | 5,352 | 0.003737 |
# -*- coding: utf-8 -*-
#
# project-template documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 18 14:44:12 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import sphinx_rtd_theme
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# project root
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'numpydoc',
'nbsphinx',
'sphinxcontrib.programoutput',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
'sphinx.ext.mathjax',
'sphinx_issues',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'neleval'
copyright = u'2014-2018 Joel Nothman, Ben Hachey, Will Radford'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '3.0.3-dev'
release = '3.0.3-dev'
# version = neleval.__version__
# The full version, including alpha/beta/rc tags.
# release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# The reST default role (used for this markup: `text`) to use for all
# documents.
default_role = 'any'
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'project-templatedoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'neleval.tex', u'neleval Documentation',
u'neleval contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
}
# Config for sphinx_issues
issues_uri = 'https://github.com/wikilinks/neleval/issues/{issue}'
issues_github_path = 'wikilinks/neleval'
issues_user_uri = 'https://github.com/{user}'
| wikilinks/neleval | doc/conf.py | Python | apache-2.0 | 8,305 | 0 |
# Copyright(c) 2007-2010 by Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Chavier.
#
# Chavier 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 3 of the License, or
# (at your option) any later version.
#
# Chavier 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 Chavier. If not, see <http://www.gnu.org/licenses/>.
import random
import webbrowser
import pygtk
pygtk.require('2.0')
import gtk
class TextInputDialog(gtk.Dialog):
def __init__(self, toplevel_window, suggested_name):
flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
super(TextInputDialog, self).__init__(u'Enter a name for the dataset',
toplevel_window, flags, buttons)
self.set_default_size(300, -1)
hbox = gtk.HBox(spacing=6)
hbox.set_border_width(12)
label = gtk.Label(u'Name')
hbox.pack_start(label, False, False)
self.entry = gtk.Entry()
self.entry.set_text(suggested_name)
self.entry.set_activates_default(True)
hbox.pack_start(self.entry, True, True)
self.vbox.pack_start(hbox, False, False)
self.vbox.show_all()
self.set_default_response(gtk.RESPONSE_ACCEPT)
def get_name(self):
return self.entry.get_text()
class PointDialog(gtk.Dialog):
def __init__(self, toplevel_window, initial_x, initial_y):
flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
super(PointDialog, self).__init__(u'Enter the point values',
toplevel_window, flags, buttons)
initials = {u'x': str(initial_x), u'y': str(initial_y)}
self.entries = {}
for coordinate in (u'x', u'y'):
hbox = gtk.HBox(spacing=6)
hbox.set_border_width(12)
label = gtk.Label(coordinate)
hbox.pack_start(label, False, False)
entry = gtk.Entry()
entry.set_activates_default(True)
entry.set_text(initials[coordinate])
hbox.pack_start(entry, True, True)
self.entries[coordinate] = entry
self.vbox.pack_start(hbox, False, False)
self.vbox.show_all()
self.set_default_response(gtk.RESPONSE_ACCEPT)
def get_point(self):
return (float(self.entries[u'x'].get_text()),
float(self.entries[u'y'].get_text()))
class OptionDialog(gtk.Dialog):
def __init__(self, toplevel_window, label, value, value_type):
flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
super(OptionDialog, self).__init__(u'Enter the option value',
toplevel_window, flags, buttons)
hbox = gtk.HBox(spacing=6)
hbox.set_border_width(12)
label = gtk.Label(label)
hbox.pack_start(label, False, False)
self.entry = gtk.Entry()
self.entry.set_text(value or '')
self.entry.set_activates_default(True)
hbox.pack_start(self.entry, True, True)
self.vbox.pack_start(hbox, False, False)
self.vbox.show_all()
self.set_default_response(gtk.RESPONSE_ACCEPT)
def get_value(self):
return self.entry.get_text()
class RandomGeneratorDialog(gtk.Dialog):
def __init__(self, toplevel_window):
flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
super(RandomGeneratorDialog, self).__init__(u'Points generation',
toplevel_window,
flags, buttons)
self.size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
self.number = self._create_spin_button('Number of points to generate',
0, 1, 5, 1, 1000, 10)
self.min = self._create_spin_button('Minimum y value',
2, 0.5, 1, -1000, 1000, 0)
self.max = self._create_spin_button('Maximum y value',
2, 0.5, 1, 0, 1000, 10)
self.vbox.show_all()
self.set_default_response(gtk.RESPONSE_ACCEPT)
def _create_spin_button(self, label_text, digits, step, page,
min_value, max_value, value):
hbox = gtk.HBox(spacing=6)
hbox.set_border_width(12)
label = gtk.Label(label_text)
label.set_alignment(1.0, 0.5)
self.size_group.add_widget(label)
hbox.pack_start(label, False, False)
spin_button = gtk.SpinButton(digits=digits)
spin_button.set_increments(step, page)
spin_button.set_range(min_value, max_value)
spin_button.set_value(value)
spin_button.set_activates_default(True)
hbox.pack_start(spin_button, True, True)
self.vbox.pack_start(hbox, False, False)
return spin_button
def generate_points(self):
n = self.number.get_value_as_int()
min_value = self.min.get_value()
max_value = self.max.get_value()
return [(x, random.uniform(min_value, max_value))
for x in range(n)]
class AboutDialog(gtk.AboutDialog):
def __init__(self, toplevel_window):
super(AboutDialog, self).__init__()
self.set_transient_for(toplevel_window)
self.set_name('Chavier')
self.set_version('0.1')
self.set_comments('A Chart Viewer for the Pycha library')
self.set_copyright('Copyleft 2008 Lorenzo Gil Sanchez')
#self.set_license('LGPL')
author = 'Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>'
self.set_authors([author])
self.set_program_name('Chavier')
self.set_website('http://www.lorenzogil.com/projects/pycha')
self.set_website_label('Project website')
def url_handler(dialog, link, data=None):
webbrowser.open(link)
gtk.about_dialog_set_url_hook(url_handler)
def warning(window, msg):
dialog = gtk.MessageDialog(window,
gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, msg)
dialog.run()
dialog.destroy()
| timesong/pycha | chavier/dialogs.py | Python | lgpl-3.0 | 7,040 | 0.00071 |
from __future__ import unicode_literals
from moto.core.exceptions import RESTError
class EC2ClientError(RESTError):
code = 400
class DependencyViolationError(EC2ClientError):
def __init__(self, message):
super(DependencyViolationError, self).__init__(
"DependencyViolation", message)
class MissingParameterError(EC2ClientError):
def __init__(self, parameter):
super(MissingParameterError, self).__init__(
"MissingParameter",
"The request must contain the parameter {0}"
.format(parameter))
class InvalidDHCPOptionsIdError(EC2ClientError):
def __init__(self, dhcp_options_id):
super(InvalidDHCPOptionsIdError, self).__init__(
"InvalidDhcpOptionID.NotFound",
"DhcpOptionID {0} does not exist."
.format(dhcp_options_id))
class MalformedDHCPOptionsIdError(EC2ClientError):
def __init__(self, dhcp_options_id):
super(MalformedDHCPOptionsIdError, self).__init__(
"InvalidDhcpOptionsId.Malformed",
"Invalid id: \"{0}\" (expecting \"dopt-...\")"
.format(dhcp_options_id))
class InvalidKeyPairNameError(EC2ClientError):
def __init__(self, key):
super(InvalidKeyPairNameError, self).__init__(
"InvalidKeyPair.NotFound",
"The keypair '{0}' does not exist."
.format(key))
class InvalidKeyPairDuplicateError(EC2ClientError):
def __init__(self, key):
super(InvalidKeyPairDuplicateError, self).__init__(
"InvalidKeyPair.Duplicate",
"The keypair '{0}' already exists."
.format(key))
class InvalidVPCIdError(EC2ClientError):
def __init__(self, vpc_id):
super(InvalidVPCIdError, self).__init__(
"InvalidVpcID.NotFound",
"VpcID {0} does not exist."
.format(vpc_id))
class InvalidSubnetIdError(EC2ClientError):
def __init__(self, subnet_id):
super(InvalidSubnetIdError, self).__init__(
"InvalidSubnetID.NotFound",
"The subnet ID '{0}' does not exist"
.format(subnet_id))
class InvalidNetworkAclIdError(EC2ClientError):
def __init__(self, network_acl_id):
super(InvalidNetworkAclIdError, self).__init__(
"InvalidNetworkAclID.NotFound",
"The network acl ID '{0}' does not exist"
.format(network_acl_id))
class InvalidVpnGatewayIdError(EC2ClientError):
def __init__(self, network_acl_id):
super(InvalidVpnGatewayIdError, self).__init__(
"InvalidVpnGatewayID.NotFound",
"The virtual private gateway ID '{0}' does not exist"
.format(network_acl_id))
class InvalidNetworkInterfaceIdError(EC2ClientError):
def __init__(self, eni_id):
super(InvalidNetworkInterfaceIdError, self).__init__(
"InvalidNetworkInterfaceID.NotFound",
"The network interface ID '{0}' does not exist"
.format(eni_id))
class InvalidNetworkAttachmentIdError(EC2ClientError):
def __init__(self, attachment_id):
super(InvalidNetworkAttachmentIdError, self).__init__(
"InvalidAttachmentID.NotFound",
"The network interface attachment ID '{0}' does not exist"
.format(attachment_id))
class InvalidSecurityGroupDuplicateError(EC2ClientError):
def __init__(self, name):
super(InvalidSecurityGroupDuplicateError, self).__init__(
"InvalidGroup.Duplicate",
"The security group '{0}' already exists"
.format(name))
class InvalidSecurityGroupNotFoundError(EC2ClientError):
def __init__(self, name):
super(InvalidSecurityGroupNotFoundError, self).__init__(
"InvalidGroup.NotFound",
"The security group '{0}' does not exist"
.format(name))
class InvalidPermissionNotFoundError(EC2ClientError):
def __init__(self):
super(InvalidPermissionNotFoundError, self).__init__(
"InvalidPermission.NotFound",
"Could not find a matching ingress rule")
class InvalidRouteTableIdError(EC2ClientError):
def __init__(self, route_table_id):
super(InvalidRouteTableIdError, self).__init__(
"InvalidRouteTableID.NotFound",
"The routeTable ID '{0}' does not exist"
.format(route_table_id))
class InvalidRouteError(EC2ClientError):
def __init__(self, route_table_id, cidr):
super(InvalidRouteError, self).__init__(
"InvalidRoute.NotFound",
"no route with destination-cidr-block {0} in route table {1}"
.format(cidr, route_table_id))
class InvalidInstanceIdError(EC2ClientError):
def __init__(self, instance_id):
super(InvalidInstanceIdError, self).__init__(
"InvalidInstanceID.NotFound",
"The instance ID '{0}' does not exist"
.format(instance_id))
class InvalidAMIIdError(EC2ClientError):
def __init__(self, ami_id):
super(InvalidAMIIdError, self).__init__(
"InvalidAMIID.NotFound",
"The image id '[{0}]' does not exist"
.format(ami_id))
class InvalidAMIAttributeItemValueError(EC2ClientError):
def __init__(self, attribute, value):
super(InvalidAMIAttributeItemValueError, self).__init__(
"InvalidAMIAttributeItemValue",
"Invalid attribute item value \"{0}\" for {1} item type."
.format(value, attribute))
class MalformedAMIIdError(EC2ClientError):
def __init__(self, ami_id):
super(MalformedAMIIdError, self).__init__(
"InvalidAMIID.Malformed",
"Invalid id: \"{0}\" (expecting \"ami-...\")"
.format(ami_id))
class InvalidSnapshotIdError(EC2ClientError):
def __init__(self, snapshot_id):
super(InvalidSnapshotIdError, self).__init__(
"InvalidSnapshot.NotFound",
"") # Note: AWS returns empty message for this, as of 2014.08.22.
class InvalidVolumeIdError(EC2ClientError):
def __init__(self, volume_id):
super(InvalidVolumeIdError, self).__init__(
"InvalidVolume.NotFound",
"The volume '{0}' does not exist."
.format(volume_id))
class InvalidVolumeAttachmentError(EC2ClientError):
def __init__(self, volume_id, instance_id):
super(InvalidVolumeAttachmentError, self).__init__(
"InvalidAttachment.NotFound",
"Volume {0} can not be detached from {1} because it is not attached"
.format(volume_id, instance_id))
class InvalidDomainError(EC2ClientError):
def __init__(self, domain):
super(InvalidDomainError, self).__init__(
"InvalidParameterValue",
"Invalid value '{0}' for domain."
.format(domain))
class InvalidAddressError(EC2ClientError):
def __init__(self, ip):
super(InvalidAddressError, self).__init__(
"InvalidAddress.NotFound",
"Address '{0}' not found."
.format(ip))
class InvalidAllocationIdError(EC2ClientError):
def __init__(self, allocation_id):
super(InvalidAllocationIdError, self).__init__(
"InvalidAllocationID.NotFound",
"Allocation ID '{0}' not found."
.format(allocation_id))
class InvalidAssociationIdError(EC2ClientError):
def __init__(self, association_id):
super(InvalidAssociationIdError, self).__init__(
"InvalidAssociationID.NotFound",
"Association ID '{0}' not found."
.format(association_id))
class InvalidVPCPeeringConnectionIdError(EC2ClientError):
def __init__(self, vpc_peering_connection_id):
super(InvalidVPCPeeringConnectionIdError, self).__init__(
"InvalidVpcPeeringConnectionId.NotFound",
"VpcPeeringConnectionID {0} does not exist."
.format(vpc_peering_connection_id))
class InvalidVPCPeeringConnectionStateTransitionError(EC2ClientError):
def __init__(self, vpc_peering_connection_id):
super(InvalidVPCPeeringConnectionStateTransitionError, self).__init__(
"InvalidStateTransition",
"VpcPeeringConnectionID {0} is not in the correct state for the request."
.format(vpc_peering_connection_id))
class InvalidParameterValueError(EC2ClientError):
def __init__(self, parameter_value):
super(InvalidParameterValueError, self).__init__(
"InvalidParameterValue",
"Value {0} is invalid for parameter."
.format(parameter_value))
class InvalidParameterValueErrorTagNull(EC2ClientError):
def __init__(self):
super(InvalidParameterValueErrorTagNull, self).__init__(
"InvalidParameterValue",
"Tag value cannot be null. Use empty string instead.")
class InvalidInternetGatewayIdError(EC2ClientError):
def __init__(self, internet_gateway_id):
super(InvalidInternetGatewayIdError, self).__init__(
"InvalidInternetGatewayID.NotFound",
"InternetGatewayID {0} does not exist."
.format(internet_gateway_id))
class GatewayNotAttachedError(EC2ClientError):
def __init__(self, internet_gateway_id, vpc_id):
super(GatewayNotAttachedError, self).__init__(
"Gateway.NotAttached",
"InternetGatewayID {0} is not attached to a VPC {1}."
.format(internet_gateway_id, vpc_id))
class ResourceAlreadyAssociatedError(EC2ClientError):
def __init__(self, resource_id):
super(ResourceAlreadyAssociatedError, self).__init__(
"Resource.AlreadyAssociated",
"Resource {0} is already associated."
.format(resource_id))
class TagLimitExceeded(EC2ClientError):
def __init__(self):
super(TagLimitExceeded, self).__init__(
"TagLimitExceeded",
"The maximum number of Tags for a resource has been reached.")
class InvalidID(EC2ClientError):
def __init__(self, resource_id):
super(InvalidID, self).__init__(
"InvalidID",
"The ID '{0}' is not valid"
.format(resource_id))
class InvalidCIDRSubnetError(EC2ClientError):
def __init__(self, cidr):
super(InvalidCIDRSubnetError, self).__init__(
"InvalidParameterValue",
"invalid CIDR subnet specification: {0}"
.format(cidr))
| kennethd/moto | moto/ec2/exceptions.py | Python | apache-2.0 | 10,404 | 0.000192 |
# Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack Foundation
#
# 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.
"""
Stubouts for the test suite
"""
import contextlib
import mock
from nova.virt.vmwareapi import driver
from nova.virt.vmwareapi import error_util
from nova.virt.vmwareapi import fake
from nova.virt.vmwareapi import network_util
from nova.virt.vmwareapi import vmware_images
def fake_get_vim_object(arg):
"""Stubs out the VMwareAPISession's get_vim_object method."""
return fake.FakeVim()
def fake_is_vim_object(arg, module):
"""Stubs out the VMwareAPISession's is_vim_object method."""
return isinstance(module, fake.FakeVim)
def fake_temp_method_exception():
raise error_util.VimFaultException(
[error_util.NOT_AUTHENTICATED],
"Session Empty/Not Authenticated")
def fake_temp_session_exception():
raise error_util.SessionConnectionException("it's a fake!",
"Session Exception")
def fake_session_file_exception():
fault_list = [error_util.FILE_ALREADY_EXISTS]
raise error_util.VimFaultException(fault_list,
Exception('fake'))
def set_stubs(stubs):
"""Set the stubs."""
stubs.Set(network_util, 'get_network_with_the_name',
fake.fake_get_network)
stubs.Set(vmware_images, 'fetch_image', fake.fake_fetch_image)
stubs.Set(vmware_images, 'get_vmdk_size_and_properties',
fake.fake_get_vmdk_size_and_properties)
stubs.Set(vmware_images, 'upload_image', fake.fake_upload_image)
stubs.Set(driver.VMwareAPISession, "_get_vim_object",
fake_get_vim_object)
stubs.Set(driver.VMwareAPISession, "_is_vim_object",
fake_is_vim_object)
def fake_suds_context(calls={}):
"""Generate a suds client which automatically mocks all SOAP method calls.
Calls are stored in <calls>, indexed by the name of the call. If you need
to mock the behaviour of specific API calls you can pre-populate <calls>
with appropriate Mock objects.
"""
class fake_factory:
def create(self, name):
return mock.NonCallableMagicMock(name=name)
class fake_service:
def __getattr__(self, attr_name):
if attr_name in calls:
return calls[attr_name]
mock_call = mock.MagicMock(name=attr_name)
calls[attr_name] = mock_call
return mock_call
class fake_client:
def __init__(self, wdsl_url, **kwargs):
self.service = fake_service()
self.factory = fake_factory()
return contextlib.nested(
mock.patch('suds.client.Client', fake_client),
# As we're not connecting to a real host there's no need to wait
# between retries
mock.patch.object(driver, 'TIME_BETWEEN_API_CALL_RETRIES', 0)
)
| eharney/nova | nova/tests/virt/vmwareapi/stubs.py | Python | apache-2.0 | 3,393 | 0.000295 |
#! /usr/bin/env python
# SCardConnect_DIRECT.py : Unitary test for SCardConnect in DIRECT mode
# Copyright (C) 2009 Ludovic Rousseau
#
# 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 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 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/>.
# MSDN indicates that pdwActiveProtocol must be set to
# SCARD_PROTOCOL_UNDEFINED if SCARD_SHARE_DIRECT is used. This behavior
# has been implemented in revision 4332 but reverted in revision 4940 so
# that the protocol is not negociated again
from smartcard.scard import *
from smartcard.pcsc.PCSCExceptions import *
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if hresult != SCARD_S_SUCCESS:
raise EstablishContextException(hresult)
hresult, readers = SCardListReaders(hcontext, [])
if hresult != SCARD_S_SUCCESS:
raise ListReadersException(hresult)
print 'PC/SC Readers:', readers
reader = readers[0]
print "Using reader:", reader
# the card should be reseted or inserted just before execution
# Connect in SCARD_SHARE_DIRECT mode
hresult, hcard, dwActiveProtocol = SCardConnect(hcontext, reader,
SCARD_SHARE_DIRECT, SCARD_PROTOCOL_ANY)
if hresult != SCARD_S_SUCCESS:
raise BaseSCardException(hresult)
print "dwActiveProtocol:", dwActiveProtocol
# Reconnect in SCARD_SHARE_DIRECT mode
hresult, dwActiveProtocol = SCardReconnect(hcard,
SCARD_SHARE_DIRECT, SCARD_PROTOCOL_ANY, SCARD_LEAVE_CARD)
if hresult != SCARD_S_SUCCESS:
raise BaseSCardException(hresult)
# ActiveProtocol should be SCARD_PROTOCOL_UNDEFINED (0)
print "dwActiveProtocol:", dwActiveProtocol
if SCARD_PROTOCOL_UNDEFINED != dwActiveProtocol:
raise Exception('dwActiveProtocol should be SCARD_PROTOCOL_UNDEFINED')
hresult = SCardDisconnect(hcard, SCARD_LEAVE_CARD)
if hresult != SCARD_S_SUCCESS:
raise BaseSCardException(hresult)
# Connect in SCARD_SHARE_SHARED mode
hresult, hcard, dwActiveProtocol = SCardConnect(hcontext, reader,
SCARD_SHARE_SHARED, SCARD_PROTOCOL_ANY)
if hresult != SCARD_S_SUCCESS:
raise BaseSCardException(hresult)
print "dwActiveProtocol:", dwActiveProtocol
oldActiveProtocol = dwActiveProtocol
# Reconnect in SCARD_SHARE_DIRECT mode
hresult, dwActiveProtocol = SCardReconnect(hcard,
SCARD_SHARE_DIRECT, SCARD_PROTOCOL_ANY, SCARD_LEAVE_CARD)
if hresult != SCARD_S_SUCCESS:
raise BaseSCardException(hresult)
# ActiveProtocol should be SCARD_PROTOCOL_UNDEFINED (0)
print "dwActiveProtocol:", dwActiveProtocol
if oldActiveProtocol != dwActiveProtocol:
raise Exception('dwActiveProtocol should be like before')
hresult = SCardDisconnect(hcard, SCARD_RESET_CARD)
if hresult != SCARD_S_SUCCESS:
raise BaseSCardException(hresult)
hresult = SCardReleaseContext(hcontext)
if hresult != SCARD_S_SUCCESS:
raise ReleaseContextException(hresult)
| vicamo/pcsc-lite-android | UnitaryTests/SCardConnect_DIRECT.py | Python | bsd-3-clause | 3,325 | 0.001203 |
"""
Django settings for charityfund project.
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(os.environ.get('DEBUG', False))
TEMPLATE_DEBUG = bool(os.environ.get('DEBUG', False))
ALLOWED_HOSTS = os.environ['ALLOWED_HOSTS'].split(', ')
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'charityfund.urls'
WSGI_APPLICATION = 'charityfund.wsgi.application'
# Database
DATABASES = {
'default': dj_database_url.config(default='sqlite://../db.sqlite3'),
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
| DArtagan/charityfund | charityfund/settings.py | Python | mit | 1,699 | 0 |
from energenie import switch_on, switch_off
from time import sleep
print ("Turning off")
switch_off()
sleep(5)
print ("Turning on")
switch_on()
| fergalmoran/energenie | socket.py | Python | apache-2.0 | 147 | 0.020408 |
#!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# tcpconnect Trace TCP connect()s.
# For Linux, uses BCC, eBPF. Embedded C.
#
# USAGE: tcpconnect [-h] [-c] [-t] [-p PID] [-P PORT [PORT ...]] [-4 | -6]
#
# All connection attempts are traced, even if they ultimately fail.
#
# This uses dynamic tracing of kernel functions, and will need to be updated
# to match kernel changes.
#
# Copyright (c) 2015 Brendan Gregg.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 25-Sep-2015 Brendan Gregg Created this.
# 14-Feb-2016 " " Switch to bpf_perf_output.
# 09-Jan-2019 Takuma Kume Support filtering by UID
# 30-Jul-2019 Xiaozhou Liu Count connects.
# 07-Oct-2020 Nabil Schear Correlate connects with DNS responses
# 08-Mar-2021 Suresh Kumar Added LPORT option
from __future__ import print_function
from bcc import BPF
from bcc.containers import filter_by_containers
from bcc.utils import printb
import argparse
from socket import inet_ntop, ntohs, AF_INET, AF_INET6
from struct import pack
from time import sleep
from datetime import datetime
# arguments
examples = """examples:
./tcpconnect # trace all TCP connect()s
./tcpconnect -t # include timestamps
./tcpconnect -d # include DNS queries associated with connects
./tcpconnect -p 181 # only trace PID 181
./tcpconnect -P 80 # only trace port 80
./tcpconnect -P 80,81 # only trace port 80 and 81
./tcpconnect -4 # only trace IPv4 family
./tcpconnect -6 # only trace IPv6 family
./tcpconnect -U # include UID
./tcpconnect -u 1000 # only trace UID 1000
./tcpconnect -c # count connects per src ip and dest ip/port
./tcpconnect -L # include LPORT while printing outputs
./tcpconnect --cgroupmap mappath # only trace cgroups in this BPF map
./tcpconnect --mntnsmap mappath # only trace mount namespaces in the map
"""
parser = argparse.ArgumentParser(
description="Trace TCP connects",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=examples)
parser.add_argument("-t", "--timestamp", action="store_true",
help="include timestamp on output")
parser.add_argument("-p", "--pid",
help="trace this PID only")
parser.add_argument("-P", "--port",
help="comma-separated list of destination ports to trace.")
group = parser.add_mutually_exclusive_group()
group.add_argument("-4", "--ipv4", action="store_true",
help="trace IPv4 family only")
group.add_argument("-6", "--ipv6", action="store_true",
help="trace IPv6 family only")
parser.add_argument("-L", "--lport", action="store_true",
help="include LPORT on output")
parser.add_argument("-U", "--print-uid", action="store_true",
help="include UID on output")
parser.add_argument("-u", "--uid",
help="trace this UID only")
parser.add_argument("-c", "--count", action="store_true",
help="count connects per src ip and dest ip/port")
parser.add_argument("--cgroupmap",
help="trace cgroups in this BPF map only")
parser.add_argument("--mntnsmap",
help="trace mount namespaces in this BPF map only")
parser.add_argument("-d", "--dns", action="store_true",
help="include likely DNS query associated with each connect")
parser.add_argument("--ebpf", action="store_true",
help=argparse.SUPPRESS)
args = parser.parse_args()
debug = 0
# define BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <net/sock.h>
#include <bcc/proto.h>
BPF_HASH(currsock, u32, struct sock *);
// separate data structs for ipv4 and ipv6
struct ipv4_data_t {
u64 ts_us;
u32 pid;
u32 uid;
u32 saddr;
u32 daddr;
u64 ip;
u16 lport;
u16 dport;
char task[TASK_COMM_LEN];
};
BPF_PERF_OUTPUT(ipv4_events);
struct ipv6_data_t {
u64 ts_us;
u32 pid;
u32 uid;
unsigned __int128 saddr;
unsigned __int128 daddr;
u64 ip;
u16 lport;
u16 dport;
char task[TASK_COMM_LEN];
};
BPF_PERF_OUTPUT(ipv6_events);
// separate flow keys per address family
struct ipv4_flow_key_t {
u32 saddr;
u32 daddr;
u16 dport;
};
BPF_HASH(ipv4_count, struct ipv4_flow_key_t);
struct ipv6_flow_key_t {
unsigned __int128 saddr;
unsigned __int128 daddr;
u16 dport;
};
BPF_HASH(ipv6_count, struct ipv6_flow_key_t);
int trace_connect_entry(struct pt_regs *ctx, struct sock *sk)
{
if (container_should_be_filtered()) {
return 0;
}
u64 pid_tgid = bpf_get_current_pid_tgid();
u32 pid = pid_tgid >> 32;
u32 tid = pid_tgid;
FILTER_PID
u32 uid = bpf_get_current_uid_gid();
FILTER_UID
// stash the sock ptr for lookup on return
currsock.update(&tid, &sk);
return 0;
};
static int trace_connect_return(struct pt_regs *ctx, short ipver)
{
int ret = PT_REGS_RC(ctx);
u64 pid_tgid = bpf_get_current_pid_tgid();
u32 pid = pid_tgid >> 32;
u32 tid = pid_tgid;
struct sock **skpp;
skpp = currsock.lookup(&tid);
if (skpp == 0) {
return 0; // missed entry
}
if (ret != 0) {
// failed to send SYNC packet, may not have populated
// socket __sk_common.{skc_rcv_saddr, ...}
currsock.delete(&tid);
return 0;
}
// pull in details
struct sock *skp = *skpp;
u16 lport = skp->__sk_common.skc_num;
u16 dport = skp->__sk_common.skc_dport;
FILTER_PORT
FILTER_FAMILY
if (ipver == 4) {
IPV4_CODE
} else /* 6 */ {
IPV6_CODE
}
currsock.delete(&tid);
return 0;
}
int trace_connect_v4_return(struct pt_regs *ctx)
{
return trace_connect_return(ctx, 4);
}
int trace_connect_v6_return(struct pt_regs *ctx)
{
return trace_connect_return(ctx, 6);
}
"""
struct_init = {'ipv4':
{'count':
"""
struct ipv4_flow_key_t flow_key = {};
flow_key.saddr = skp->__sk_common.skc_rcv_saddr;
flow_key.daddr = skp->__sk_common.skc_daddr;
flow_key.dport = ntohs(dport);
ipv4_count.increment(flow_key);""",
'trace':
"""
struct ipv4_data_t data4 = {.pid = pid, .ip = ipver};
data4.uid = bpf_get_current_uid_gid();
data4.ts_us = bpf_ktime_get_ns() / 1000;
data4.saddr = skp->__sk_common.skc_rcv_saddr;
data4.daddr = skp->__sk_common.skc_daddr;
data4.lport = lport;
data4.dport = ntohs(dport);
bpf_get_current_comm(&data4.task, sizeof(data4.task));
ipv4_events.perf_submit(ctx, &data4, sizeof(data4));"""
},
'ipv6':
{'count':
"""
struct ipv6_flow_key_t flow_key = {};
bpf_probe_read_kernel(&flow_key.saddr, sizeof(flow_key.saddr),
skp->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
bpf_probe_read_kernel(&flow_key.daddr, sizeof(flow_key.daddr),
skp->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
flow_key.dport = ntohs(dport);
ipv6_count.increment(flow_key);""",
'trace':
"""
struct ipv6_data_t data6 = {.pid = pid, .ip = ipver};
data6.uid = bpf_get_current_uid_gid();
data6.ts_us = bpf_ktime_get_ns() / 1000;
bpf_probe_read_kernel(&data6.saddr, sizeof(data6.saddr),
skp->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
bpf_probe_read_kernel(&data6.daddr, sizeof(data6.daddr),
skp->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
data6.lport = lport;
data6.dport = ntohs(dport);
bpf_get_current_comm(&data6.task, sizeof(data6.task));
ipv6_events.perf_submit(ctx, &data6, sizeof(data6));"""
}
}
# This defines an additional BPF program that instruments udp_recvmsg system
# call to locate DNS response packets on UDP port 53. When these packets are
# located, the data is copied to user-space where python will parse them with
# dnslib.
#
# uses a percpu array of length 1 to store the dns_data_t off the stack to
# allow for a maximum DNS packet length of 512 bytes.
dns_bpf_text = """
#include <net/inet_sock.h>
#define MAX_PKT 512
struct dns_data_t {
u8 pkt[MAX_PKT];
};
BPF_PERF_OUTPUT(dns_events);
// store msghdr pointer captured on syscall entry to parse on syscall return
BPF_HASH(tbl_udp_msg_hdr, u64, struct msghdr *);
// single element per-cpu array to hold the current event off the stack
BPF_PERCPU_ARRAY(dns_data,struct dns_data_t,1);
int trace_udp_recvmsg(struct pt_regs *ctx)
{
__u64 pid_tgid = bpf_get_current_pid_tgid();
struct sock *sk = (struct sock *)PT_REGS_PARM1(ctx);
struct inet_sock *is = inet_sk(sk);
// only grab port 53 packets, 13568 is ntohs(53)
if (is->inet_dport == 13568) {
struct msghdr *msghdr = (struct msghdr *)PT_REGS_PARM2(ctx);
tbl_udp_msg_hdr.update(&pid_tgid, &msghdr);
}
return 0;
}
int trace_udp_ret_recvmsg(struct pt_regs *ctx)
{
__u64 pid_tgid = bpf_get_current_pid_tgid();
u32 zero = 0;
struct msghdr **msgpp = tbl_udp_msg_hdr.lookup(&pid_tgid);
if (msgpp == 0)
return 0;
struct msghdr *msghdr = (struct msghdr *)*msgpp;
if (msghdr->msg_iter.type != ITER_IOVEC)
goto delete_and_return;
int copied = (int)PT_REGS_RC(ctx);
if (copied < 0)
goto delete_and_return;
size_t buflen = (size_t)copied;
if (buflen > msghdr->msg_iter.iov->iov_len)
goto delete_and_return;
if (buflen > MAX_PKT)
buflen = MAX_PKT;
struct dns_data_t *data = dns_data.lookup(&zero);
if (!data) // this should never happen, just making the verifier happy
return 0;
void *iovbase = msghdr->msg_iter.iov->iov_base;
bpf_probe_read(data->pkt, buflen, iovbase);
dns_events.perf_submit(ctx, data, buflen);
delete_and_return:
tbl_udp_msg_hdr.delete(&pid_tgid);
return 0;
}
"""
if args.count and args.dns:
print("Error: you may not specify -d/--dns with -c/--count.")
exit()
# code substitutions
if args.count:
bpf_text = bpf_text.replace("IPV4_CODE", struct_init['ipv4']['count'])
bpf_text = bpf_text.replace("IPV6_CODE", struct_init['ipv6']['count'])
else:
bpf_text = bpf_text.replace("IPV4_CODE", struct_init['ipv4']['trace'])
bpf_text = bpf_text.replace("IPV6_CODE", struct_init['ipv6']['trace'])
if args.pid:
bpf_text = bpf_text.replace('FILTER_PID',
'if (pid != %s) { return 0; }' % args.pid)
if args.port:
dports = [int(dport) for dport in args.port.split(',')]
dports_if = ' && '.join(['dport != %d' % ntohs(dport) for dport in dports])
bpf_text = bpf_text.replace('FILTER_PORT',
'if (%s) { currsock.delete(&tid); return 0; }' % dports_if)
if args.ipv4:
bpf_text = bpf_text.replace('FILTER_FAMILY',
'if (ipver != 4) { return 0; }')
elif args.ipv6:
bpf_text = bpf_text.replace('FILTER_FAMILY',
'if (ipver != 6) { return 0; }')
if args.uid:
bpf_text = bpf_text.replace('FILTER_UID',
'if (uid != %s) { return 0; }' % args.uid)
bpf_text = filter_by_containers(args) + bpf_text
bpf_text = bpf_text.replace('FILTER_PID', '')
bpf_text = bpf_text.replace('FILTER_PORT', '')
bpf_text = bpf_text.replace('FILTER_FAMILY', '')
bpf_text = bpf_text.replace('FILTER_UID', '')
if args.dns:
bpf_text += dns_bpf_text
if debug or args.ebpf:
print(bpf_text)
if args.ebpf:
exit()
# process event
def print_ipv4_event(cpu, data, size):
event = b["ipv4_events"].event(data)
global start_ts
if args.timestamp:
if start_ts == 0:
start_ts = event.ts_us
printb(b"%-9.3f" % ((float(event.ts_us) - start_ts) / 1000000), nl="")
if args.print_uid:
printb(b"%-6d" % event.uid, nl="")
dest_ip = inet_ntop(AF_INET, pack("I", event.daddr)).encode()
if args.lport:
printb(b"%-6d %-12.12s %-2d %-16s %-6d %-16s %-6d %s" % (event.pid,
event.task, event.ip,
inet_ntop(AF_INET, pack("I", event.saddr)).encode(), event.lport,
dest_ip, event.dport, print_dns(dest_ip)))
else:
printb(b"%-6d %-12.12s %-2d %-16s %-16s %-6d %s" % (event.pid,
event.task, event.ip,
inet_ntop(AF_INET, pack("I", event.saddr)).encode(),
dest_ip, event.dport, print_dns(dest_ip)))
def print_ipv6_event(cpu, data, size):
event = b["ipv6_events"].event(data)
global start_ts
if args.timestamp:
if start_ts == 0:
start_ts = event.ts_us
printb(b"%-9.3f" % ((float(event.ts_us) - start_ts) / 1000000), nl="")
if args.print_uid:
printb(b"%-6d" % event.uid, nl="")
dest_ip = inet_ntop(AF_INET6, event.daddr).encode()
if args.lport:
printb(b"%-6d %-12.12s %-2d %-16s %-6d %-16s %-6d %s" % (event.pid,
event.task, event.ip,
inet_ntop(AF_INET6, event.saddr).encode(), event.lport,
dest_ip, event.dport, print_dns(dest_ip)))
else:
printb(b"%-6d %-12.12s %-2d %-16s %-16s %-6d %s" % (event.pid,
event.task, event.ip,
inet_ntop(AF_INET6, event.saddr).encode(),
dest_ip, event.dport, print_dns(dest_ip)))
def depict_cnt(counts_tab, l3prot='ipv4'):
for k, v in sorted(counts_tab.items(),
key=lambda counts: counts[1].value, reverse=True):
depict_key = ""
if l3prot == 'ipv4':
depict_key = "%-25s %-25s %-20s" % \
((inet_ntop(AF_INET, pack('I', k.saddr))),
inet_ntop(AF_INET, pack('I', k.daddr)), k.dport)
else:
depict_key = "%-25s %-25s %-20s" % \
((inet_ntop(AF_INET6, k.saddr)),
inet_ntop(AF_INET6, k.daddr), k.dport)
print("%s %-10d" % (depict_key, v.value))
def print_dns(dest_ip):
if not args.dns:
return b""
dnsname, timestamp = dns_cache.get(dest_ip, (None, None))
if timestamp is not None:
diff = datetime.now() - timestamp
diff = float(diff.seconds) * 1000 + float(diff.microseconds) / 1000
else:
diff = 0
if dnsname is None:
dnsname = b"No DNS Query"
if dest_ip == b"127.0.0.1" or dest_ip == b"::1":
dnsname = b"localhost"
retval = b"%s" % dnsname
if diff > DELAY_DNS:
retval += b" (%.3fms)" % diff
return retval
if args.dns:
try:
import dnslib
from cachetools import TTLCache
except ImportError:
print("Error: The python packages dnslib and cachetools are required "
"to use the -d/--dns option.")
print("Install this package with:")
print("\t$ pip3 install dnslib cachetools")
print(" or")
print("\t$ sudo apt-get install python3-dnslib python3-cachetools "
"(on Ubuntu 18.04+)")
exit(1)
# 24 hours
DEFAULT_TTL = 86400
# Cache Size in entries
DNS_CACHE_SIZE = 10240
# delay in ms in which to warn users of long delay between the query
# and the connect that used the IP
DELAY_DNS = 100
dns_cache = TTLCache(maxsize=DNS_CACHE_SIZE, ttl=DEFAULT_TTL)
# process event
def save_dns(cpu, data, size):
event = b["dns_events"].event(data)
payload = event.pkt[:size]
# pass the payload to dnslib for parsing
dnspkt = dnslib.DNSRecord.parse(payload)
# lets only look at responses
if dnspkt.header.qr != 1:
return
# must be some questions in there
if dnspkt.header.q != 1:
return
# make sure there are answers
if dnspkt.header.a == 0 and dnspkt.header.aa == 0:
return
# lop off the trailing .
question = ("%s" % dnspkt.q.qname)[:-1].encode('utf-8')
for answer in dnspkt.rr:
# skip all but A and AAAA records
if answer.rtype == 1 or answer.rtype == 28:
dns_cache[str(answer.rdata).encode('utf-8')] = (question,
datetime.now())
# initialize BPF
b = BPF(text=bpf_text)
b.attach_kprobe(event="tcp_v4_connect", fn_name="trace_connect_entry")
b.attach_kprobe(event="tcp_v6_connect", fn_name="trace_connect_entry")
b.attach_kretprobe(event="tcp_v4_connect", fn_name="trace_connect_v4_return")
b.attach_kretprobe(event="tcp_v6_connect", fn_name="trace_connect_v6_return")
if args.dns:
b.attach_kprobe(event="udp_recvmsg", fn_name="trace_udp_recvmsg")
b.attach_kretprobe(event="udp_recvmsg", fn_name="trace_udp_ret_recvmsg")
print("Tracing connect ... Hit Ctrl-C to end")
if args.count:
try:
while True:
sleep(99999999)
except KeyboardInterrupt:
pass
# header
print("\n%-25s %-25s %-20s %-10s" % (
"LADDR", "RADDR", "RPORT", "CONNECTS"))
depict_cnt(b["ipv4_count"])
depict_cnt(b["ipv6_count"], l3prot='ipv6')
# read events
else:
# header
if args.timestamp:
print("%-9s" % ("TIME(s)"), end="")
if args.print_uid:
print("%-6s" % ("UID"), end="")
if args.lport:
print("%-6s %-12s %-2s %-16s %-6s %-16s %-6s" % ("PID", "COMM", "IP", "SADDR",
"LPORT", "DADDR", "DPORT"), end="")
else:
print("%-6s %-12s %-2s %-16s %-16s %-6s" % ("PID", "COMM", "IP", "SADDR",
"DADDR", "DPORT"), end="")
if args.dns:
print(" QUERY")
else:
print()
start_ts = 0
# read events
b["ipv4_events"].open_perf_buffer(print_ipv4_event)
b["ipv6_events"].open_perf_buffer(print_ipv6_event)
if args.dns:
b["dns_events"].open_perf_buffer(save_dns)
while True:
try:
b.perf_buffer_poll()
except KeyboardInterrupt:
exit()
| brendangregg/bcc | tools/tcpconnect.py | Python | apache-2.0 | 17,972 | 0.002393 |
# -*- coding: UTF-8 -*-
# File: summary.py
# Author: Yuxin Wu <ppwwyyxx@gmail.com>
import six
import tensorflow as tf
import re
from ..utils import *
from . import get_global_step_var
from .symbolic_functions import rms
__all__ = ['create_summary', 'add_param_summary', 'add_activation_summary',
'add_moving_summary', 'summary_moving_average']
def create_summary(name, v):
"""
Return a tf.Summary object with name and simple scalar value v
"""
assert isinstance(name, six.string_types), type(name)
v = float(v)
s = tf.Summary()
s.value.add(tag=name, simple_value=v)
return s
def add_activation_summary(x, name=None):
"""
Add summary to graph for an activation tensor x.
If name is None, use x.name.
"""
ndim = x.get_shape().ndims
assert ndim >= 2, \
"Summary a scalar with histogram? Maybe use scalar instead. FIXME!"
if name is None:
name = x.name
with tf.name_scope('act_summary'):
tf.histogram_summary(name + '/activation', x)
tf.scalar_summary(name + '/activation_sparsity', tf.nn.zero_fraction(x))
tf.scalar_summary(
name + '/activation_rms', rms(x))
def add_param_summary(summary_lists):
"""
Add summary for all trainable variables matching the regex
:param summary_lists: list of (regex, [list of summary type to perform]).
Type can be 'mean', 'scalar', 'histogram', 'sparsity', 'rms'
"""
def perform(var, action):
ndim = var.get_shape().ndims
name = var.name.replace(':0', '')
if action == 'scalar':
assert ndim == 0, "Scalar summary on high-dimension data. Maybe you want 'mean'?"
tf.scalar_summary(name, var)
return
assert ndim > 0, "Cannot perform {} summary on scalar data".format(action)
if action == 'histogram':
tf.histogram_summary(name, var)
return
if action == 'sparsity':
tf.scalar_summary(name + '/sparsity', tf.nn.zero_fraction(var))
return
if action == 'mean':
tf.scalar_summary(name + '/mean', tf.reduce_mean(var))
return
if action == 'rms':
tf.scalar_summary(name + '/rms', rms(var))
return
raise RuntimeError("Unknown summary type: {}".format(action))
params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
with tf.name_scope('param_summary'):
for p in params:
name = p.name
for rgx, actions in summary_lists:
if not rgx.endswith('$'):
rgx = rgx + '(:0)?$'
if re.match(rgx, name):
for act in actions:
perform(p, act)
def add_moving_summary(v, *args):
"""
:param v: tensor or list of tensor to summary
:param args: tensors to summary
"""
if not isinstance(v, list):
v = [v]
v.extend(args)
for x in v:
tf.add_to_collection(MOVING_SUMMARY_VARS_KEY, x)
def summary_moving_average():
""" Create a MovingAverage op and summary for all variables in
MOVING_SUMMARY_VARS_KEY.
:returns: a op to maintain these average.
"""
with tf.name_scope('EMA_summary'):
global_step_var = get_global_step_var()
with tf.name_scope(None):
averager = tf.train.ExponentialMovingAverage(
0.99, num_updates=global_step_var, name='EMA')
vars_to_summary = tf.get_collection(MOVING_SUMMARY_VARS_KEY)
avg_maintain_op = averager.apply(vars_to_summary)
for idx, c in enumerate(vars_to_summary):
# TODO assert scalar
name = re.sub('tower[p0-9]+/', '', c.op.name)
tf.scalar_summary(name, averager.average(c))
return avg_maintain_op
| yinglanma/AI-project | tensorpack/tfutils/summary.py | Python | apache-2.0 | 3,816 | 0.002621 |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
from grid_cell_model.submitting import flagparse
import noisefigs
from noisefigs.env import NoiseEnvironment
import config_standard_gEE_3060 as config
parser = flagparse.FlagParser()
parser.add_flag('--bumpDriftSweep')
args = parser.parse_args()
env = NoiseEnvironment(user_config=config.get_config())
if args.bumpDriftSweep or args.all:
env.register_plotter(noisefigs.plotters.BumpDriftAtTimePlotter)
env.plot()
| MattNolanLab/ei-attractor | grid_cell_model/simulations/007_noise/figures/paper/ee_connections_ei_flat/figure_drifts.py | Python | gpl-3.0 | 501 | 0.001996 |
# Copyright 2016 GoDaddy.
#
# 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 neutron_lib import constants
import neutron.api.extensions as api_ext
import neutron.common.config as config
import neutron.extensions
import neutron.services.network_ip_availability.plugin as plugin_module
import neutron.tests.unit.db.test_db_base_plugin_v2 as test_db_base_plugin_v2
API_RESOURCE = 'network-ip-availabilities'
IP_AVAIL_KEY = 'network_ip_availability'
IP_AVAILS_KEY = 'network_ip_availabilities'
EXTENSIONS_PATH = ':'.join(neutron.extensions.__path__)
PLUGIN_NAME = '%s.%s' % (plugin_module.NetworkIPAvailabilityPlugin.__module__,
plugin_module.NetworkIPAvailabilityPlugin.__name__)
class TestNetworkIPAvailabilityAPI(
test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
def setUp(self):
svc_plugins = {'plugin_name': PLUGIN_NAME}
super(TestNetworkIPAvailabilityAPI, self).setUp(
service_plugins=svc_plugins)
self.plugin = plugin_module.NetworkIPAvailabilityPlugin()
ext_mgr = api_ext.PluginAwareExtensionManager(
EXTENSIONS_PATH, {"network-ip-availability": self.plugin}
)
app = config.load_paste_app('extensions_test_app')
self.ext_api = api_ext.ExtensionMiddleware(app, ext_mgr=ext_mgr)
def _validate_availability(self, network, availability, expected_used_ips,
expected_total_ips=253):
self.assertEqual(network['name'], availability['network_name'])
self.assertEqual(network['id'], availability['network_id'])
self.assertEqual(expected_used_ips, availability['used_ips'])
self.assertEqual(expected_total_ips, availability['total_ips'])
def _validate_from_availabilities(self, availabilities, wrapped_network,
expected_used_ips,
expected_total_ips=253):
network = wrapped_network['network']
availability = self._find_availability(availabilities, network['id'])
self.assertIsNotNone(availability)
self._validate_availability(network, availability,
expected_used_ips=expected_used_ips,
expected_total_ips=expected_total_ips)
def test_usages_query_list_with_fields_total_ips(self):
with self.network() as net:
with self.subnet(network=net):
# list by query fields: total_ips
params = 'fields=total_ips'
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertIn(IP_AVAILS_KEY, response)
self.assertEqual(1, len(response[IP_AVAILS_KEY]))
availability = response[IP_AVAILS_KEY][0]
self.assertIn('total_ips', availability)
self.assertEqual(253, availability['total_ips'])
self.assertNotIn('network_id', availability)
def test_usages_query_show_with_fields_total_ips(self):
with self.network() as net:
with self.subnet(network=net):
network = net['network']
# Show by query fields: total_ips
params = ['total_ips']
request = self.new_show_request(API_RESOURCE,
network['id'],
fields=params)
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
self.assertIn(IP_AVAIL_KEY, response)
availability = response[IP_AVAIL_KEY]
self.assertIn('total_ips', availability)
self.assertEqual(253, availability['total_ips'])
self.assertNotIn('network_id', availability)
@staticmethod
def _find_availability(availabilities, net_id):
for ip_availability in availabilities:
if net_id == ip_availability['network_id']:
return ip_availability
def test_basic(self):
with self.network() as net:
with self.subnet(network=net):
network = net['network']
# Get ALL
request = self.new_list_request(API_RESOURCE, self.fmt)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertIn(IP_AVAILS_KEY, response)
self.assertEqual(1, len(response[IP_AVAILS_KEY]))
self._validate_from_availabilities(response[IP_AVAILS_KEY],
net, 0)
# Get single via id
request = self.new_show_request(API_RESOURCE, network['id'])
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
self.assertIn(IP_AVAIL_KEY, response)
usage = response[IP_AVAIL_KEY]
self._validate_availability(network, usage, 0)
def test_usages_multi_nets_subnets(self):
with self.network(name='net1') as n1,\
self.network(name='net2') as n2,\
self.network(name='net3') as n3:
# n1 should have 2 subnets, n2 should have none, n3 has 1
with self.subnet(network=n1) as subnet1_1, \
self.subnet(cidr='40.0.0.0/24', network=n3) as subnet3_1:
# Consume 3 ports n1, none n2, 2 ports on n3
with self.port(subnet=subnet1_1),\
self.port(subnet=subnet1_1),\
self.port(subnet=subnet1_1),\
self.port(subnet=subnet3_1),\
self.port(subnet=subnet3_1):
# Test get ALL
request = self.new_list_request(API_RESOURCE)
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
self.assertIn(IP_AVAILS_KEY, response)
self.assertEqual(3, len(response[IP_AVAILS_KEY]))
data = response[IP_AVAILS_KEY]
self._validate_from_availabilities(data, n1, 3, 253)
self._validate_from_availabilities(data, n2, 0, 0)
self._validate_from_availabilities(data, n3, 2, 253)
# Test get single via network id
network = n1['network']
request = self.new_show_request(API_RESOURCE,
network['id'])
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
self.assertIn(IP_AVAIL_KEY, response)
self._validate_availability(network,
response[IP_AVAIL_KEY], 3, 253)
def test_usages_multi_nets_subnets_sums(self):
with self.network(name='net1') as n1:
# n1 has 2 subnets
with self.subnet(network=n1) as subnet1_1, \
self.subnet(cidr='40.0.0.0/24', network=n1) as subnet1_2:
# Consume 3 ports n1: 1 on subnet 1 and 2 on subnet 2
with self.port(subnet=subnet1_1),\
self.port(subnet=subnet1_2),\
self.port(subnet=subnet1_2):
# Get ALL
request = self.new_list_request(API_RESOURCE)
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
self.assertIn(IP_AVAILS_KEY, response)
self.assertEqual(1, len(response[IP_AVAILS_KEY]))
self._validate_from_availabilities(response[IP_AVAILS_KEY],
n1, 3, 506)
# Get single via network id
network = n1['network']
request = self.new_show_request(API_RESOURCE,
network['id'])
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
self.assertIn(IP_AVAIL_KEY, response)
self._validate_availability(network,
response[IP_AVAIL_KEY], 3, 506)
def test_usages_port_consumed_v4(self):
with self.network() as net:
with self.subnet(network=net) as subnet:
request = self.new_list_request(API_RESOURCE)
# Consume 2 ports
with self.port(subnet=subnet), self.port(subnet=subnet):
response = self.deserialize(self.fmt,
request.get_response(
self.ext_api))
self._validate_from_availabilities(response[IP_AVAILS_KEY],
net, 2)
def test_usages_query_ip_version_v4(self):
with self.network() as net:
with self.subnet(network=net):
# Get IPv4
params = 'ip_version=%s' % constants.IP_VERSION_4
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertIn(IP_AVAILS_KEY, response)
self.assertEqual(1, len(response[IP_AVAILS_KEY]))
self._validate_from_availabilities(response[IP_AVAILS_KEY],
net, 0)
# Get IPv6 should return empty array
params = 'ip_version=%s' % constants.IP_VERSION_6
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertEqual(0, len(response[IP_AVAILS_KEY]))
def test_usages_query_ip_version_v6(self):
with self.network() as net:
with self.subnet(
network=net, cidr='2607:f0d0:1002:51::/64',
ip_version=constants.IP_VERSION_6,
ipv6_address_mode=constants.DHCPV6_STATELESS):
# Get IPv6
params = 'ip_version=%s' % constants.IP_VERSION_6
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertEqual(1, len(response[IP_AVAILS_KEY]))
self._validate_from_availabilities(
response[IP_AVAILS_KEY], net, 0, 18446744073709551614)
# Get IPv4 should return empty array
params = 'ip_version=%s' % constants.IP_VERSION_4
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertEqual(0, len(response[IP_AVAILS_KEY]))
def test_usages_ports_consumed_v6(self):
with self.network() as net:
with self.subnet(
network=net, cidr='2607:f0d0:1002:51::/64',
ip_version=constants.IP_VERSION_6,
ipv6_address_mode=constants.DHCPV6_STATELESS) as subnet:
request = self.new_list_request(API_RESOURCE)
# Consume 3 ports
with self.port(subnet=subnet),\
self.port(subnet=subnet), \
self.port(subnet=subnet):
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
self._validate_from_availabilities(response[IP_AVAILS_KEY],
net, 3,
18446744073709551614)
def test_usages_query_network_id(self):
with self.network() as net:
with self.subnet(network=net):
network = net['network']
test_id = network['id']
# Get by query param: network_id
params = 'network_id=%s' % test_id
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertIn(IP_AVAILS_KEY, response)
self.assertEqual(1, len(response[IP_AVAILS_KEY]))
self._validate_from_availabilities(response[IP_AVAILS_KEY],
net, 0)
# Get by NON-matching query param: network_id
params = 'network_id=clearlywontmatch'
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertEqual(0, len(response[IP_AVAILS_KEY]))
def test_usages_query_network_name(self):
test_name = 'net_name_1'
with self.network(name=test_name) as net:
with self.subnet(network=net):
# Get by query param: network_name
params = 'network_name=%s' % test_name
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertIn(IP_AVAILS_KEY, response)
self.assertEqual(1, len(response[IP_AVAILS_KEY]))
self._validate_from_availabilities(response[IP_AVAILS_KEY],
net, 0)
# Get by NON-matching query param: network_name
params = 'network_name=clearly-wont-match'
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertEqual(0, len(response[IP_AVAILS_KEY]))
def test_usages_query_tenant_id(self):
test_tenant_id = 'a-unique-test-id'
with self.network(tenant_id=test_tenant_id) as net:
with self.subnet(network=net):
# Get by query param: tenant_id
params = 'tenant_id=%s' % test_tenant_id
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertIn(IP_AVAILS_KEY, response)
self.assertEqual(1, len(response[IP_AVAILS_KEY]))
self._validate_from_availabilities(response[IP_AVAILS_KEY],
net, 0)
for net_avail in response[IP_AVAILS_KEY]:
self.assertEqual(test_tenant_id, net_avail['tenant_id'])
# Get by NON-matching query param: tenant_id
params = 'tenant_id=clearly-wont-match'
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertEqual(0, len(response[IP_AVAILS_KEY]))
def test_usages_query_project_id(self):
test_project_id = 'a-unique-project-id'
with self.network(tenant_id=test_project_id) as net:
with self.subnet(network=net):
# Get by query param: project_id
params = 'project_id=%s' % test_project_id
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertIn(IP_AVAILS_KEY, response)
self.assertEqual(1, len(response[IP_AVAILS_KEY]))
self._validate_from_availabilities(response[IP_AVAILS_KEY],
net, 0)
for net_avail in response[IP_AVAILS_KEY]:
self.assertEqual(test_project_id, net_avail['project_id'])
# Get by NON-matching query param: project_id
params = 'project_id=clearly-wont-match'
request = self.new_list_request(API_RESOURCE, params=params)
response = self.deserialize(self.fmt,
request.get_response(self.ext_api))
self.assertEqual(0, len(response[IP_AVAILS_KEY]))
def test_usages_multi_net_multi_subnet_46(self):
# Setup mixed v4/v6 networks with IPs consumed on each
with self.network(name='net-v6-1') as net_v6_1, \
self.network(name='net-v6-2') as net_v6_2, \
self.network(name='net-v4-1') as net_v4_1, \
self.network(name='net-v4-2') as net_v4_2:
with self.subnet(network=net_v6_1, cidr='2607:f0d0:1002:51::/64',
ip_version=constants.IP_VERSION_6) as s61, \
self.subnet(network=net_v6_2,
cidr='2607:f0d0:1003:52::/64',
ip_version=constants.IP_VERSION_6) as s62, \
self.subnet(network=net_v4_1, cidr='10.0.0.0/24') as s41, \
self.subnet(network=net_v4_2, cidr='10.0.1.0/24') as s42:
with self.port(subnet=s61),\
self.port(subnet=s62), self.port(subnet=s62), \
self.port(subnet=s41), \
self.port(subnet=s42), self.port(subnet=s42):
# Verify consumption across all
request = self.new_list_request(API_RESOURCE)
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
avails_list = response[IP_AVAILS_KEY]
self._validate_from_availabilities(
avails_list, net_v6_1, 1, 18446744073709551614)
self._validate_from_availabilities(
avails_list, net_v6_2, 2, 18446744073709551614)
self._validate_from_availabilities(
avails_list, net_v4_1, 1, 253)
self._validate_from_availabilities(
avails_list, net_v4_2, 2, 253)
# Query by IP versions. Ensure subnet versions match
for ip_ver in [constants.IP_VERSION_4,
constants.IP_VERSION_6]:
params = 'ip_version=%i' % ip_ver
request = self.new_list_request(API_RESOURCE,
params=params)
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
for net_avail in response[IP_AVAILS_KEY]:
for sub in net_avail['subnet_ip_availability']:
self.assertEqual(ip_ver, sub['ip_version'])
# Verify consumption querying 2 network ids (IN clause)
request = self.new_list_request(
API_RESOURCE,
params='network_id=%s&network_id=%s'
% (net_v4_2['network']['id'],
net_v6_2['network']['id']))
response = self.deserialize(
self.fmt, request.get_response(self.ext_api))
avails_list = response[IP_AVAILS_KEY]
self._validate_from_availabilities(
avails_list, net_v6_2, 2, 18446744073709551614)
self._validate_from_availabilities(
avails_list, net_v4_2, 2, 253)
| noironetworks/neutron | neutron/tests/unit/extensions/test_network_ip_availability.py | Python | apache-2.0 | 21,269 | 0 |
""" Basic functions for manipulating 2d arrays
"""
from __future__ import division, absolute_import, print_function
__all__ = ['diag', 'diagflat', 'eye', 'fliplr', 'flipud', 'rot90', 'tri',
'triu', 'tril', 'vander', 'histogram2d', 'mask_indices',
'tril_indices', 'tril_indices_from', 'triu_indices',
'triu_indices_from',
]
from numpy.core.numeric import (
asanyarray, subtract, arange, zeros, greater_equal, multiply, ones,
asarray, where, dtype as np_dtype, less, int8, int16, int32, int64
)
from numpy.core import iinfo
i1 = iinfo(int8)
i2 = iinfo(int16)
i4 = iinfo(int32)
def _min_int(low, high):
""" get small int that fits the range """
if high <= i1.max and low >= i1.min:
return int8
if high <= i2.max and low >= i2.min:
return int16
if high <= i4.max and low >= i4.min:
return int32
return int64
def fliplr(m):
"""
Flip array in the left/right direction.
Flip the entries in each row in the left/right direction.
Columns are preserved, but appear in a different order than before.
Parameters
----------
m : array_like
Input array, must be at least 2-D.
Returns
-------
f : ndarray
A view of `m` with the columns reversed. Since a view
is returned, this operation is :math:`\\mathcal O(1)`.
See Also
--------
flipud : Flip array in the up/down direction.
rot90 : Rotate array counterclockwise.
Notes
-----
Equivalent to A[:,::-1]. Requires the array to be at least 2-D.
Examples
--------
>>> A = np.diag([1.,2.,3.])
>>> A
array([[ 1., 0., 0.],
[ 0., 2., 0.],
[ 0., 0., 3.]])
>>> np.fliplr(A)
array([[ 0., 0., 1.],
[ 0., 2., 0.],
[ 3., 0., 0.]])
>>> A = np.random.randn(2,3,5)
>>> np.all(np.fliplr(A)==A[:,::-1,...])
True
"""
m = asanyarray(m)
if m.ndim < 2:
raise ValueError("Input must be >= 2-d.")
return m[:, ::-1]
def flipud(m):
"""
Flip array in the up/down direction.
Flip the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.
Parameters
----------
m : array_like
Input array.
Returns
-------
out : array_like
A view of `m` with the rows reversed. Since a view is
returned, this operation is :math:`\\mathcal O(1)`.
See Also
--------
fliplr : Flip array in the left/right direction.
rot90 : Rotate array counterclockwise.
Notes
-----
Equivalent to ``A[::-1,...]``.
Does not require the array to be two-dimensional.
Examples
--------
>>> A = np.diag([1.0, 2, 3])
>>> A
array([[ 1., 0., 0.],
[ 0., 2., 0.],
[ 0., 0., 3.]])
>>> np.flipud(A)
array([[ 0., 0., 3.],
[ 0., 2., 0.],
[ 1., 0., 0.]])
>>> A = np.random.randn(2,3,5)
>>> np.all(np.flipud(A)==A[::-1,...])
True
>>> np.flipud([1,2])
array([2, 1])
"""
m = asanyarray(m)
if m.ndim < 1:
raise ValueError("Input must be >= 1-d.")
return m[::-1, ...]
def rot90(m, k=1):
"""
Rotate an array by 90 degrees in the counter-clockwise direction.
The first two dimensions are rotated; therefore, the array must be at
least 2-D.
Parameters
----------
m : array_like
Array of two or more dimensions.
k : integer
Number of times the array is rotated by 90 degrees.
Returns
-------
y : ndarray
Rotated array.
See Also
--------
fliplr : Flip an array horizontally.
flipud : Flip an array vertically.
Examples
--------
>>> m = np.array([[1,2],[3,4]], int)
>>> m
array([[1, 2],
[3, 4]])
>>> np.rot90(m)
array([[2, 4],
[1, 3]])
>>> np.rot90(m, 2)
array([[4, 3],
[2, 1]])
"""
m = asanyarray(m)
if m.ndim < 2:
raise ValueError("Input must >= 2-d.")
k = k % 4
if k == 0:
return m
elif k == 1:
return fliplr(m).swapaxes(0, 1)
elif k == 2:
return fliplr(flipud(m))
else:
# k == 3
return fliplr(m.swapaxes(0, 1))
def eye(N, M=None, k=0, dtype=float):
"""
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
M : int, optional
Number of columns in the output. If None, defaults to `N`.
k : int, optional
Index of the diagonal: 0 (the default) refers to the main diagonal,
a positive value refers to an upper diagonal, and a negative value
to a lower diagonal.
dtype : data-type, optional
Data-type of the returned array.
Returns
-------
I : ndarray of shape (N,M)
An array where all elements are equal to zero, except for the `k`-th
diagonal, whose values are equal to one.
See Also
--------
identity : (almost) equivalent function
diag : diagonal 2-D array from a 1-D array specified by the user.
Examples
--------
>>> np.eye(2, dtype=int)
array([[1, 0],
[0, 1]])
>>> np.eye(3, k=1)
array([[ 0., 1., 0.],
[ 0., 0., 1.],
[ 0., 0., 0.]])
"""
if M is None:
M = N
m = zeros((N, M), dtype=dtype)
if k >= M:
return m
if k >= 0:
i = k
else:
i = (-k) * M
m[:M-k].flat[i::M+1] = 1
return m
def diag(v, k=0):
"""
Extract a diagonal or construct a diagonal array.
See the more detailed documentation for ``numpy.diagonal`` if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.
Parameters
----------
v : array_like
If `v` is a 2-D array, return a copy of its `k`-th diagonal.
If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
diagonal.
k : int, optional
Diagonal in question. The default is 0. Use `k>0` for diagonals
above the main diagonal, and `k<0` for diagonals below the main
diagonal.
Returns
-------
out : ndarray
The extracted diagonal or constructed diagonal array.
See Also
--------
diagonal : Return specified diagonals.
diagflat : Create a 2-D array with the flattened input as a diagonal.
trace : Sum along diagonals.
triu : Upper triangle of an array.
tril : Lower triangle of an array.
Examples
--------
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])
"""
v = asarray(v)
s = v.shape
if len(s) == 1:
n = s[0]+abs(k)
res = zeros((n, n), v.dtype)
if k >= 0:
i = k
else:
i = (-k) * n
res[:n-k].flat[i::n+1] = v
return res
elif len(s) == 2:
return v.diagonal(k)
else:
raise ValueError("Input must be 1- or 2-d.")
def diagflat(v, k=0):
"""
Create a two-dimensional array with the flattened input as a diagonal.
Parameters
----------
v : array_like
Input data, which is flattened and set as the `k`-th
diagonal of the output.
k : int, optional
Diagonal to set; 0, the default, corresponds to the "main" diagonal,
a positive (negative) `k` giving the number of the diagonal above
(below) the main.
Returns
-------
out : ndarray
The 2-D output array.
See Also
--------
diag : MATLAB work-alike for 1-D and 2-D arrays.
diagonal : Return specified diagonals.
trace : Sum along diagonals.
Examples
--------
>>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
[0, 0, 2],
[0, 0, 0]])
"""
try:
wrap = v.__array_wrap__
except AttributeError:
wrap = None
v = asarray(v).ravel()
s = len(v)
n = s + abs(k)
res = zeros((n, n), v.dtype)
if (k >= 0):
i = arange(0, n-k)
fi = i+k+i*n
else:
i = arange(0, n+k)
fi = i+(i-k)*n
res.flat[fi] = v
if not wrap:
return res
return wrap(res)
def tri(N, M=None, k=0, dtype=float):
"""
An array with ones at and below the given diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the array.
M : int, optional
Number of columns in the array.
By default, `M` is taken equal to `N`.
k : int, optional
The sub-diagonal at and below which the array is filled.
`k` = 0 is the main diagonal, while `k` < 0 is below it,
and `k` > 0 is above. The default is 0.
dtype : dtype, optional
Data type of the returned array. The default is float.
Returns
-------
tri : ndarray of shape (N, M)
Array with its lower triangle filled with ones and zero elsewhere;
in other words ``T[i,j] == 1`` for ``i <= j + k``, 0 otherwise.
Examples
--------
>>> np.tri(3, 5, 2, dtype=int)
array([[1, 1, 1, 0, 0],
[1, 1, 1, 1, 0],
[1, 1, 1, 1, 1]])
>>> np.tri(3, 5, -1)
array([[ 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0.],
[ 1., 1., 0., 0., 0.]])
"""
if M is None:
M = N
m = greater_equal.outer(arange(N, dtype=_min_int(0, N)),
arange(-k, M-k, dtype=_min_int(-k, M - k)))
# Avoid making a copy if the requested type is already bool
if np_dtype(dtype) != np_dtype(bool):
m = m.astype(dtype)
return m
def tril(m, k=0):
"""
Lower triangle of an array.
Return a copy of an array with elements above the `k`-th diagonal zeroed.
Parameters
----------
m : array_like, shape (M, N)
Input array.
k : int, optional
Diagonal above which to zero elements. `k = 0` (the default) is the
main diagonal, `k < 0` is below it and `k > 0` is above.
Returns
-------
tril : ndarray, shape (M, N)
Lower triangle of `m`, of same shape and data-type as `m`.
See Also
--------
triu : same thing, only for the upper triangle
Examples
--------
>>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 0, 0, 0],
[ 4, 0, 0],
[ 7, 8, 0],
[10, 11, 12]])
"""
m = asanyarray(m)
return multiply(tri(*m.shape[-2:], k=k, dtype=bool), m, dtype=m.dtype)
def triu(m, k=0):
"""
Upper triangle of an array.
Return a copy of a matrix with the elements below the `k`-th diagonal
zeroed.
Please refer to the documentation for `tril` for further details.
See Also
--------
tril : lower triangle of an array
Examples
--------
>>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 0, 8, 9],
[ 0, 0, 12]])
"""
m = asanyarray(m)
return multiply(~tri(*m.shape[-2:], k=k-1, dtype=bool), m, dtype=m.dtype)
# Originally borrowed from John Hunter and matplotlib
def vander(x, N=None, order='decreasing'):
"""
Generate a Vandermonde matrix.
The columns of the output matrix are powers of the input vector. The
order of the powers is determined by the `order` argument, either
"decreasing" (the default) or "increasing". Specifically, when
`order` is "decreasing", the `i`-th output column is the input vector
raised element-wise to the power of ``N - i - 1``. Such a matrix with
a geometric progression in each row is named for Alexandre-Theophile
Vandermonde.
Parameters
----------
x : array_like
1-D input array.
N : int, optional
Number of columns in the output. If `N` is not specified, a square
array is returned (``N = len(x)``).
order : str, optional
Order of the powers of the columns. Must be either 'decreasing'
(the default) or 'increasing'.
Returns
-------
out : ndarray
Vandermonde matrix. If `order` is "decreasing", the first column is
``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `order` is
"increasing", the columns are ``x^0, x^1, ..., x^(N-1)``.
See Also
--------
polynomial.polynomial.polyvander
Examples
--------
>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> x = np.array([1, 2, 3, 5])
>>> np.vander(x)
array([[ 1, 1, 1, 1],
[ 8, 4, 2, 1],
[ 27, 9, 3, 1],
[125, 25, 5, 1]])
>>> np.vander(x, order='increasing')
array([[ 1, 1, 1, 1],
[ 1, 2, 4, 8],
[ 1, 3, 9, 27],
[ 1, 5, 25, 125]])
The determinant of a square Vandermonde matrix is the product
of the differences between the values of the input vector:
>>> np.linalg.det(np.vander(x))
48.000000000000043
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48
"""
if order not in ['decreasing', 'increasing']:
raise ValueError("Invalid order %r; order must be either "
"'decreasing' or 'increasing'." % (order,))
x = asarray(x)
if x.ndim != 1:
raise ValueError("x must be a one-dimensional array or sequence.")
if N is None:
N = len(x)
if order == "decreasing":
powers = arange(N - 1, -1, -1)
else:
powers = arange(N)
V = x.reshape(-1, 1) ** powers
return V
def histogram2d(x, y, bins=10, range=None, normed=False, weights=None):
"""
Compute the bi-dimensional histogram of two data samples.
Parameters
----------
x : array_like, shape (N,)
An array containing the x coordinates of the points to be
histogrammed.
y : array_like, shape (N,)
An array containing the y coordinates of the points to be
histogrammed.
bins : int or [int, int] or array_like or [array, array], optional
The bin specification:
* If int, the number of bins for the two dimensions (nx=ny=bins).
* If [int, int], the number of bins in each dimension
(nx, ny = bins).
* If array_like, the bin edges for the two dimensions
(x_edges=y_edges=bins).
* If [array, array], the bin edges in each dimension
(x_edges, y_edges = bins).
range : array_like, shape(2,2), optional
The leftmost and rightmost edges of the bins along each dimension
(if not specified explicitly in the `bins` parameters):
``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range
will be considered outliers and not tallied in the histogram.
normed : bool, optional
If False, returns the number of samples in each bin. If True,
returns the bin density ``bin_count / sample_count / bin_area``.
weights : array_like, shape(N,), optional
An array of values ``w_i`` weighing each sample ``(x_i, y_i)``.
Weights are normalized to 1 if `normed` is True. If `normed` is
False, the values of the returned histogram are equal to the sum of
the weights belonging to the samples falling into each bin.
Returns
-------
H : ndarray, shape(nx, ny)
The bi-dimensional histogram of samples `x` and `y`. Values in `x`
are histogrammed along the first dimension and values in `y` are
histogrammed along the second dimension.
xedges : ndarray, shape(nx,)
The bin edges along the first dimension.
yedges : ndarray, shape(ny,)
The bin edges along the second dimension.
See Also
--------
histogram : 1D histogram
histogramdd : Multidimensional histogram
Notes
-----
When `normed` is True, then the returned histogram is the sample
density, defined such that the sum over bins of the product
``bin_value * bin_area`` is 1.
Please note that the histogram does not follow the Cartesian convention
where `x` values are on the abscissa and `y` values on the ordinate
axis. Rather, `x` is histogrammed along the first dimension of the
array (vertical), and `y` along the second dimension of the array
(horizontal). This ensures compatibility with `histogramdd`.
Examples
--------
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt
Construct a 2D-histogram with variable bin width. First define the bin
edges:
>>> xedges = [0, 1, 1.5, 3, 5]
>>> yedges = [0, 2, 3, 4, 6]
Next we create a histogram H with random bin content:
>>> x = np.random.normal(3, 1, 100)
>>> y = np.random.normal(1, 1, 100)
>>> H, xedges, yedges = np.histogram2d(y, x, bins=(xedges, yedges))
Or we fill the histogram H with a determined bin content:
>>> H = np.ones((4, 4)).cumsum().reshape(4, 4)
>>> print H[::-1] # This shows the bin content in the order as plotted
[[ 13. 14. 15. 16.]
[ 9. 10. 11. 12.]
[ 5. 6. 7. 8.]
[ 1. 2. 3. 4.]]
Imshow can only do an equidistant representation of bins:
>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131)
>>> ax.set_title('imshow: equidistant')
>>> im = plt.imshow(H, interpolation='nearest', origin='low',
extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
pcolormesh can display exact bin edges:
>>> ax = fig.add_subplot(132)
>>> ax.set_title('pcolormesh: exact bin edges')
>>> X, Y = np.meshgrid(xedges, yedges)
>>> ax.pcolormesh(X, Y, H)
>>> ax.set_aspect('equal')
NonUniformImage displays exact bin edges with interpolation:
>>> ax = fig.add_subplot(133)
>>> ax.set_title('NonUniformImage: interpolated')
>>> im = mpl.image.NonUniformImage(ax, interpolation='bilinear')
>>> xcenters = xedges[:-1] + 0.5 * (xedges[1:] - xedges[:-1])
>>> ycenters = yedges[:-1] + 0.5 * (yedges[1:] - yedges[:-1])
>>> im.set_data(xcenters, ycenters, H)
>>> ax.images.append(im)
>>> ax.set_xlim(xedges[0], xedges[-1])
>>> ax.set_ylim(yedges[0], yedges[-1])
>>> ax.set_aspect('equal')
>>> plt.show()
"""
from numpy import histogramdd
try:
N = len(bins)
except TypeError:
N = 1
if N != 1 and N != 2:
xedges = yedges = asarray(bins, float)
bins = [xedges, yedges]
hist, edges = histogramdd([x, y], bins, range, normed, weights)
return hist, edges[0], edges[1]
def mask_indices(n, mask_func, k=0):
"""
Return the indices to access (n, n) arrays, given a masking function.
Assume `mask_func` is a function that, for a square array a of size
``(n, n)`` with a possible offset argument `k`, when called as
``mask_func(a, k)`` returns a new array with zeros in certain locations
(functions like `triu` or `tril` do precisely this). Then this function
returns the indices where the non-zero values would be located.
Parameters
----------
n : int
The returned indices will be valid to access arrays of shape (n, n).
mask_func : callable
A function whose call signature is similar to that of `triu`, `tril`.
That is, ``mask_func(x, k)`` returns a boolean array, shaped like `x`.
`k` is an optional argument to the function.
k : scalar
An optional argument which is passed through to `mask_func`. Functions
like `triu`, `tril` take a second argument that is interpreted as an
offset.
Returns
-------
indices : tuple of arrays.
The `n` arrays of indices corresponding to the locations where
``mask_func(np.ones((n, n)), k)`` is True.
See Also
--------
triu, tril, triu_indices, tril_indices
Notes
-----
.. versionadded:: 1.4.0
Examples
--------
These are the indices that would allow you to access the upper triangular
part of any 3x3 array:
>>> iu = np.mask_indices(3, np.triu)
For example, if `a` is a 3x3 array:
>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> a[iu]
array([0, 1, 2, 4, 5, 8])
An offset can be passed also to the masking function. This gets us the
indices starting on the first diagonal right of the main one:
>>> iu1 = np.mask_indices(3, np.triu, 1)
with which we now extract only three elements:
>>> a[iu1]
array([1, 2, 5])
"""
m = ones((n, n), int)
a = mask_func(m, k)
return where(a != 0)
def tril_indices(n, k=0, m=None):
"""
Return the indices for the lower-triangle of an (n, m) array.
Parameters
----------
n : int
The row dimension of the arrays for which the returned
indices will be valid.
k : int, optional
Diagonal offset (see `tril` for details).
m : int, optional
.. versionadded:: 1.9.0
The column dimension of the arrays for which the returned
arrays will be valid.
By default `m` is taken equal to `n`.
Returns
-------
inds : tuple of arrays
The indices for the triangle. The returned tuple contains two arrays,
each with the indices along one dimension of the array.
See also
--------
triu_indices : similar function, for upper-triangular.
mask_indices : generic function accepting an arbitrary mask function.
tril, triu
Notes
-----
.. versionadded:: 1.4.0
Examples
--------
Compute two different sets of indices to access 4x4 arrays, one for the
lower triangular part starting at the main diagonal, and one starting two
diagonals further right:
>>> il1 = np.tril_indices(4)
>>> il2 = np.tril_indices(4, 2)
Here is how they can be used with a sample array:
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Both for indexing:
>>> a[il1]
array([ 0, 4, 5, 8, 9, 10, 12, 13, 14, 15])
And for assigning values:
>>> a[il1] = -1
>>> a
array([[-1, 1, 2, 3],
[-1, -1, 6, 7],
[-1, -1, -1, 11],
[-1, -1, -1, -1]])
These cover almost the whole array (two diagonals right of the main one):
>>> a[il2] = -10
>>> a
array([[-10, -10, -10, 3],
[-10, -10, -10, -10],
[-10, -10, -10, -10],
[-10, -10, -10, -10]])
"""
return where(tri(n, m, k=k, dtype=bool))
def tril_indices_from(arr, k=0):
"""
Return the indices for the lower-triangle of arr.
See `tril_indices` for full details.
Parameters
----------
arr : array_like
The indices will be valid for square arrays whose dimensions are
the same as arr.
k : int, optional
Diagonal offset (see `tril` for details).
See Also
--------
tril_indices, tril
Notes
-----
.. versionadded:: 1.4.0
"""
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1])
def triu_indices(n, k=0, m=None):
"""
Return the indices for the upper-triangle of an (n, m) array.
Parameters
----------
n : int
The size of the arrays for which the returned indices will
be valid.
k : int, optional
Diagonal offset (see `triu` for details).
m : int, optional
.. versionadded:: 1.9.0
The column dimension of the arrays for which the returned
arrays will be valid.
By default `m` is taken equal to `n`.
Returns
-------
inds : tuple, shape(2) of ndarrays, shape(`n`)
The indices for the triangle. The returned tuple contains two arrays,
each with the indices along one dimension of the array. Can be used
to slice a ndarray of shape(`n`, `n`).
See also
--------
tril_indices : similar function, for lower-triangular.
mask_indices : generic function accepting an arbitrary mask function.
triu, tril
Notes
-----
.. versionadded:: 1.4.0
Examples
--------
Compute two different sets of indices to access 4x4 arrays, one for the
upper triangular part starting at the main diagonal, and one starting two
diagonals further right:
>>> iu1 = np.triu_indices(4)
>>> iu2 = np.triu_indices(4, 2)
Here is how they can be used with a sample array:
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Both for indexing:
>>> a[iu1]
array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15])
And for assigning values:
>>> a[iu1] = -1
>>> a
array([[-1, -1, -1, -1],
[ 4, -1, -1, -1],
[ 8, 9, -1, -1],
[12, 13, 14, -1]])
These cover only a small part of the whole array (two diagonals right
of the main one):
>>> a[iu2] = -10
>>> a
array([[ -1, -1, -10, -10],
[ 4, -1, -1, -10],
[ 8, 9, -1, -1],
[ 12, 13, 14, -1]])
"""
return where(~tri(n, m, k=k-1, dtype=bool))
def triu_indices_from(arr, k=0):
"""
Return the indices for the upper-triangle of arr.
See `triu_indices` for full details.
Parameters
----------
arr : ndarray, shape(N, N)
The indices will be valid for square arrays.
k : int, optional
Diagonal offset (see `triu` for details).
Returns
-------
triu_indices_from : tuple, shape(2) of ndarray, shape(N)
Indices for the upper-triangle of `arr`.
See Also
--------
triu_indices, triu
Notes
-----
.. versionadded:: 1.4.0
"""
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1])
| immerrr/numpy | numpy/lib/twodim_base.py | Python | bsd-3-clause | 26,858 | 0.000037 |
import sys
import click
import os
import subprocess
from packageinfo import BUILD, VERSION, NAME
# The version of the buildcommon to checkout.
BUILDCOMMONS_VERSION = "v0.2"
def bootstrap_devenv():
try:
os.makedirs(".devenv")
except OSError:
pass
if not os.path.exists(".devenv/buildrecipes-common"):
subprocess.check_call([
"git", "clone", "-b", BUILDCOMMONS_VERSION,
"http://github.com/simphony/buildrecipes-common.git",
".devenv/buildrecipes-common"
])
sys.path.insert(0, ".devenv/buildrecipes-common")
bootstrap_devenv()
import buildcommons as common # noqa
workspace = common.workspace()
common.edmenv_setup()
@click.group()
def cli():
pass
@cli.command()
def egg():
common.local_repo_to_edm_egg(".", name=NAME, version=VERSION, build=BUILD)
@cli.command()
def upload_egg():
egg_path = "endist/{NAME}-{VERSION}-{BUILD}.egg".format(
NAME=NAME,
VERSION=VERSION,
BUILD=BUILD)
click.echo("Uploading {} to EDM repo".format(egg_path))
common.upload_egg(egg_path)
click.echo("Done")
@cli.command()
def clean():
click.echo("Cleaning")
common.clean(["endist", ".devenv"])
cli()
| simphony/simphony-lammps-md | edmsetup.py | Python | bsd-2-clause | 1,237 | 0 |
import logging
import os
import warnings
from ..util import SysOutCapture
from .base import Tool, Issue, ToolIssue
# Hacks to prevent pyroma from screwing up the logging system for everyone else
old_config = logging.basicConfig
try:
logging.basicConfig = lambda **k: None
from pyroma import projectdata, ratings
finally:
logging.basicConfig = old_config
# Hacks so we can get the messages of these tests without running them.
HACKS = (
('PythonVersion', '_major_version_specified', False),
('ValidREST', '_message', ''),
('ClassifierVerification', '_incorrect', []),
('Licensing', '_message', ''),
)
for clazz, attr, value in HACKS:
if hasattr(ratings, clazz):
setattr(getattr(ratings, clazz), attr, value)
TIDYPY_ISSUES = {
'NOT_CALLED': (
'SetupNotCalled',
'setup() was not invoked.',
),
'SCRIPT_FAIL': (
'SetupFailed',
'Execution of the setup module failed:\n%s',
),
'RST_ERROR': (
'RstProblem',
'The reStructuredText in your description generated errors:\n%s',
),
}
class PyromaIssue(Issue):
tool = 'pyroma'
class PyromaTool(Tool):
"""
Pyroma tests your project's packaging friendliness.
"""
@classmethod
def get_default_config(cls):
config = Tool.get_default_config()
config['filters'] = [
r'setup\.py$',
]
return config
@classmethod
def get_all_codes(cls):
return [
(test.__class__.__name__, test.message().strip())
for test in ratings.ALL_TESTS
] + list(TIDYPY_ISSUES.values())
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.disabled = self.config['disabled'][:]
if 'LicenseClassifier' in self.disabled:
self.disabled.append('LicenceClassifier')
if 'Licence' in self.disabled:
self.disabled.append('License')
def execute(self, finder):
issues = []
for filepath in finder.files(self.config['filters']):
dirname, _ = os.path.split(filepath)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
with SysOutCapture() as capture:
try:
data = projectdata.get_data(dirname)
except RuntimeError:
err = capture.get_stderr()
if err:
issues.append(PyromaIssue(
TIDYPY_ISSUES['SCRIPT_FAIL'][0],
TIDYPY_ISSUES['SCRIPT_FAIL'][1] % (err,),
filepath,
))
else:
issues.append(PyromaIssue(
TIDYPY_ISSUES['NOT_CALLED'][0],
TIDYPY_ISSUES['NOT_CALLED'][1],
filepath,
))
continue
for test in ratings.ALL_TESTS:
name = test.__class__.__name__
if name in self.disabled:
continue
if test.test(data) is False:
issues.append(PyromaIssue(
name,
test.message(),
filepath,
))
err = capture.get_stderr()
if err:
if err.startswith('<string>:'):
issues.append(PyromaIssue(
TIDYPY_ISSUES['RST_ERROR'][0],
TIDYPY_ISSUES['RST_ERROR'][1] % (err,),
filepath,
))
else:
issues.append(ToolIssue(
err,
filepath,
))
return [
issue
for issue in issues
if issue.code not in self.disabled
]
| jayclassless/tidypy | src/tidypy/tools/pyroma.py | Python | mit | 4,228 | 0.000237 |
###############################################################################
# Copyright (C) 2008 Johann Haarhoff <johann.haarhoff@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of Version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
###############################################################################
#
# Originally written:
# 2008 Johann Haarhoff, <johann.haarhoff@gmail.com>
# Modifications:
#
###############################################################################
#global modules
import shapelibc
import dbflibc
import sys
#my modules
from xmlwriter import * #AUTO_REMOVED by make
from vec import * #AUTO_REMOVED by make
def castSpecific(shpobj):
"""
if given a SHPObject, this will return a more
specific version like SHPPointObject depending
on the SHPType of the given object
"""
if shpobj._SHPType == shapelibc.SHPT_POINT:
obj = SHPPointObject()
obj.createFromObject(shpobj)
return obj
elif shpobj._SHPType == shapelibc.SHPT_ARCZ:
obj = SHPArcZObject()
obj.createFromObject(shpobj)
return obj
elif shpobj._SHPType == shapelibc.SHPT_ARC:
obj = SHPArcObject()
obj.createFromObject(shpobj)
return obj
elif shpobj._SHPType == shapelibc.SHPT_POLYGONZ:
obj = SHPPolygonZObject()
obj.createFromObject(shpobj)
return obj
elif shpobj._SHPType == shapelibc.SHPT_POLYGON:
obj = SHPPolygonObject()
obj.createFromObject(shpobj)
return obj
class WrongShapeObjectError(Exception):
"""
Thrown when trying to instantiate say a
SHPPointOPbject from file, and the file
returns a different type
"""
pass
class SHPObject():
def __init__(self,SHPType = shapelibc.SHPT_NULL,SHPId = -1,Verts = [[]],Label="",Desc = ""):
self._SHPType = SHPType
self._SHPId = SHPId
self._Verts = Verts
self._Label = Label
self._Desc = Desc
def createFromFile(self,filestream,shapenum):
"""
The filestream should already be opened
with shapelibc.open() before calling this
"""
shp = shapelibc.ShapeFile_read_object(filestream,shapenum)
SHPObject.__init__(self,shapelibc.SHPObject_type_get(shp),
shapelibc.SHPObject_id_get(shp),
shapelibc.SHPObject_vertices(shp))
def makeDescriptionFromFile(self,filestream,shapenum):
"""
The filestream should already be opened
with dbflibc.open() before calling this
"""
numfields = dbflibc.DBFFile_field_count(filestream)
for i in range(0,numfields):
field_name = str(dbflibc.DBFFile_field_info(filestream,i)[1]).upper()
field_data = str(dbflibc.DBFFile_read_attribute(filestream,shapenum,i)).lower()
self._Desc = self._Desc + "<b>" + field_name + ": </b>" + field_data + "<br>"
class SHPPointObject(SHPObject):
def __init__(self,SHPId = -1,Verts = [[]],Label="",Desc=""):
SHPObject.__init__(self,shapelibc.SHPT_POINT,SHPId,Verts,Label,Desc)
def createFromFile(self,filestream,shapenum):
SHPObject.createFromFile(self,filestream,shapenum)
if self._SHPType != shapelibc.SHPT_POINT:
raise WrongShapeObjectError()
def createFromObject(self,shpobject):
if shpobject._SHPType != shapelibc.SHPT_POINT:
raise WrongShapeObjectError()
SHPPointObject.__init__(self,shpobject._SHPId,shpobject._Verts,shpobject._Label,shpobject._Desc)
def toKML(self,out,styleUrl="",indentstr = '\t'):
kmlwriter = BetterXMLWriter(out,indentstr)
kmlwriter.openElement("Placemark")
kmlwriter.openElement("name")
if self._Label == "":
kmlwriter.addData(str(self._SHPId))
else:
kmlwriter.addData(str(self._Label))
kmlwriter.closeLast()
kmlwriter.openElement("styleUrl")
kmlwriter.addData(str(styleUrl))
kmlwriter.closeLast()
kmlwriter.openElement("description")
kmlwriter.addCData(self._Desc)
kmlwriter.closeLast()
kmlwriter.openElement("Point")
kmlwriter.openElement("coordinates")
for i,j in self._Verts:
kmlwriter.addData(str(i)+","+str(j)+",0 ")
kmlwriter.endDocument()
class SHPArcZObject(SHPObject):
def __init__(self,SHPId = -1,Verts = [[]],Label="",Desc=""):
SHPObject.__init__(self,shapelibc.SHPT_ARCZ,SHPId,Verts,Label,Desc)
def createFromFile(self,filestream,shapenum):
SHPObject.createFromFile(self,filestream,shapenum)
if self._SHPType != shapelibc.SHPT_ARCZ:
raise WrongShapeObjectError()
def createFromObject(self,shpobject):
if shpobject._SHPType != shapelibc.SHPT_ARCZ:
raise WrongShapeObjectError()
SHPArcZObject.__init__(self,shpobject._SHPId,shpobject._Verts,shpobject._Label,shpobject._Desc)
def toKML(self,out,styleUrl="",indentstr = '\t'):
kmlwriter = BetterXMLWriter(out,indentstr)
kmlwriter.openElement("Placemark")
kmlwriter.openElement("name")
if self._Label == "":
kmlwriter.addData(str(self._SHPId))
else:
kmlwriter.addData(str(self._Label))
kmlwriter.closeLast()
kmlwriter.openElement("styleUrl")
kmlwriter.addData(str(styleUrl))
kmlwriter.closeLast()
kmlwriter.openElement("description")
kmlwriter.addCData(self._Desc)
kmlwriter.closeLast()
kmlwriter.openElement("LineString")
kmlwriter.openElement("tessellate")
kmlwriter.addData("1")
kmlwriter.closeLast()
kmlwriter.openElement("coordinates")
#shapelibc does not populate _Verts properly,
#so we need to check for the Z coordinate
#even if this is an ArcZ
if len(self._Verts[0][0]) == 2:
#we only have x and y
for i,j in self._Verts[0]:
kmlwriter.addData(str(i)+","+str(j)+",0 ")
elif len(self._Verts[0][0]) == 3:
#we have x, y and z
for i,j,k in self._Verts[0]:
kmlwriter.addData(str(i)+","+str(j)+","+str(k)+" ")
elif len(self._Verts[0][0]) == 4:
#we have x,y,z and m
#I don't know what to do with m at this stage
for i,j,k,l in self._Verts[0]:
kmlwriter.addData(str(i)+","+str(j)+","+str(k)+" ")
kmlwriter.endDocument()
class SHPArcObject(SHPArcZObject):
def __init__(self,SHPId = -1,Verts = [[]],Label="",Desc=""):
SHPObject.__init__(self,shapelibc.SHPT_ARC,SHPId,Verts,Label,Desc)
def createFromFile(self,filestream,shapenum):
SHPObject.createFromFile(self,filestream,shapenum)
if self._SHPType != shapelibc.SHPT_ARC:
raise WrongShapeObjectError()
def createFromObject(self,shpobject):
if shpobject._SHPType != shapelibc.SHPT_ARC:
raise WrongShapeObjectError()
SHPArcObject.__init__(self,shpobject._SHPId,shpobject._Verts,shpobject._Label,shpobject._Desc)
class SHPPolygonZObject(SHPObject):
def __init__(self,SHPId = -1,Verts = [[]],Label="",Desc=""):
SHPObject.__init__(self,shapelibc.SHPT_POLYGONZ,SHPId,Verts,Label,Desc)
def createFromFile(self,filestream,shapenum):
SHPObject.createFromFile(self,filestream,shapenum)
if self._SHPType != shapelibc.SHPT_POLYGONZ:
raise WrongShapeObjectError()
def createFromObject(self,shpobject):
if shpobject._SHPType != shapelibc.SHPT_POLYGONZ:
raise WrongShapeObjectError()
SHPPolygonZObject.__init__(self,shpobject._SHPId,shpobject._Verts,shpobject._Label,shpobject._Desc)
def toKML(self,out,styleUrl="",indentstr = '\t'):
kmlwriter = BetterXMLWriter(out,indentstr)
kmlwriter.openElement("Placemark")
kmlwriter.openElement("name")
if self._Label == "":
kmlwriter.addData(str(self._SHPId))
else:
kmlwriter.addData(str(self._Label))
kmlwriter.closeLast()
kmlwriter.openElement("styleUrl")
kmlwriter.addData(str(styleUrl))
kmlwriter.closeLast()
kmlwriter.openElement("description")
kmlwriter.addCData(self._Desc)
kmlwriter.closeLast()
kmlwriter.openElement("Polygon")
kmlwriter.openElement("extrude")
kmlwriter.addData("0")
kmlwriter.closeLast()
kmlwriter.openElement("tessellate")
kmlwriter.addData("1")
kmlwriter.closeLast()
#polygons may have multiple parts
#in the shapefile, a part is an outer boundary if the
#poly is wound clockwise, and an inner boundary if it
#is wound anticlockwise.
#we use winding_number in vec.py to figure this out
for part,coords in enumerate(self._Verts):
dir = winding_number(coords) #winding_number is from vec.py
if dir > 0:
kmlwriter.openElement("outerBoundaryIs")
elif dir < 0:
kmlwriter.openElement("innerBoundaryIs")
kmlwriter.openElement("LinearRing")
kmlwriter.openElement("coordinates")
#shapelibc does not populate _Verts properly,
#so we need to check for the Z coordinate
#even if this is a PolygonZ
if len(self._Verts[part][0]) == 2:
#we only have x and y
for i,j in self._Verts[part]:
kmlwriter.addData(str(i)+","+str(j)+",0 ")
elif len(self._Verts[part][0]) == 3:
#we have x, y and z
for i,j,k in self._Verts[part]:
kmlwriter.addData(str(i)+","+str(j)+","+str(k)+" ")
elif len(self._Verts[part][0]) == 4:
#we have x,y,z and m
#I don't know what to do with m at this stage
for i,j,k,l in self._Verts[part]:
kmlwriter.addData(str(i)+","+str(j)+","+str(k)+" ")
kmlwriter.closeLast() #coordinates
kmlwriter.closeLast() #LinearRing
kmlwriter.closeLast() #outer/innerBoudary
kmlwriter.endDocument()
class SHPPolygonObject(SHPPolygonZObject):
def __init__(self,SHPId = -1,Verts = [[]],Label="",Desc=""):
SHPObject.__init__(self,shapelibc.SHPT_POLYGON,SHPId,Verts,Label,Desc)
def createFromFile(self,filestream,shapenum):
SHPObject.createFromFile(self,filestream,shapenum)
if self._SHPType != shapelibc.SHPT_POLYGON:
raise WrongShapeObjectError()
def createFromObject(self,shpobject):
if shpobject._SHPType != shapelibc.SHPT_POLYGON:
raise WrongShapeObjectError()
SHPPolygonObject.__init__(self,shpobject._SHPId,shpobject._Verts,shpobject._Label,shpobject._Desc)
| Jaden-J/shape2ge | src/shapeobjects.py | Python | gpl-2.0 | 10,069 | 0.049558 |
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.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/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from six.moves import queue
import multiprocessing
import os
import signal
import sys
import time
import traceback
HAS_ATFORK=True
try:
from Crypto.Random import atfork
except ImportError:
HAS_ATFORK=False
from ansible.errors import AnsibleError, AnsibleConnectionFailure
from ansible.executor.task_executor import TaskExecutor
from ansible.executor.task_result import TaskResult
from ansible.playbook.handler import Handler
from ansible.playbook.task import Task
from ansible.utils.debug import debug
__all__ = ['WorkerProcess']
class WorkerProcess(multiprocessing.Process):
'''
The worker thread class, which uses TaskExecutor to run tasks
read from a job queue and pushes results into a results queue
for reading later.
'''
def __init__(self, tqm, main_q, rslt_q, loader):
# takes a task queue manager as the sole param:
self._main_q = main_q
self._rslt_q = rslt_q
self._loader = loader
# dupe stdin, if we have one
self._new_stdin = sys.stdin
try:
fileno = sys.stdin.fileno()
if fileno is not None:
try:
self._new_stdin = os.fdopen(os.dup(fileno))
except OSError, e:
# couldn't dupe stdin, most likely because it's
# not a valid file descriptor, so we just rely on
# using the one that was passed in
pass
except ValueError:
# couldn't get stdin's fileno, so we just carry on
pass
super(WorkerProcess, self).__init__()
def run(self):
'''
Called when the process is started, and loops indefinitely
until an error is encountered (typically an IOerror from the
queue pipe being disconnected). During the loop, we attempt
to pull tasks off the job queue and run them, pushing the result
onto the results queue. We also remove the host from the blocked
hosts list, to signify that they are ready for their next task.
'''
if HAS_ATFORK:
atfork()
while True:
task = None
try:
if not self._main_q.empty():
debug("there's work to be done!")
(host, task, basedir, job_vars, play_context, shared_loader_obj) = self._main_q.get(block=False)
debug("got a task/handler to work on: %s" % task)
# because the task queue manager starts workers (forks) before the
# playbook is loaded, set the basedir of the loader inherted by
# this fork now so that we can find files correctly
self._loader.set_basedir(basedir)
# Serializing/deserializing tasks does not preserve the loader attribute,
# since it is passed to the worker during the forking of the process and
# would be wasteful to serialize. So we set it here on the task now, and
# the task handles updating parent/child objects as needed.
task.set_loader(self._loader)
# apply the given task's information to the connection info,
# which may override some fields already set by the play or
# the options specified on the command line
new_play_context = play_context.set_task_and_host_override(task=task, host=host)
# execute the task and build a TaskResult from the result
debug("running TaskExecutor() for %s/%s" % (host, task))
executor_result = TaskExecutor(host, task, job_vars, new_play_context, self._new_stdin, self._loader, shared_loader_obj).run()
debug("done running TaskExecutor() for %s/%s" % (host, task))
task_result = TaskResult(host, task, executor_result)
# put the result on the result queue
debug("sending task result")
self._rslt_q.put(task_result, block=False)
debug("done sending task result")
else:
time.sleep(0.1)
except queue.Empty:
pass
except (IOError, EOFError, KeyboardInterrupt):
break
except AnsibleConnectionFailure:
try:
if task:
task_result = TaskResult(host, task, dict(unreachable=True))
self._rslt_q.put(task_result, block=False)
except:
# FIXME: most likely an abort, catch those kinds of errors specifically
break
except Exception, e:
debug("WORKER EXCEPTION: %s" % e)
debug("WORKER EXCEPTION: %s" % traceback.format_exc())
try:
if task:
task_result = TaskResult(host, task, dict(failed=True, exception=traceback.format_exc(), stdout=''))
self._rslt_q.put(task_result, block=False)
except:
# FIXME: most likely an abort, catch those kinds of errors specifically
break
debug("WORKER PROCESS EXITING")
| scottcunningham/ansible | lib/ansible/executor/process/worker.py | Python | gpl-3.0 | 6,192 | 0.004037 |
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
# Create a new instance of the IE driver
driver = webdriver.PhantomJS()
# go to the google home page
driver.get("http://www.google.com")
# find the element that's name attribute is q (the google search box)
inputElement = driver.find_element_by_name("q")
# type in the search
inputElement.send_keys("cheese!")
# submit the form (although google automatically searches now without submitting)
inputElement.submit()
# the page is ajaxy so the title is originally this:
print driver.title
driver.get_screenshot_as_file('screenshot.png')
try:
# we have to wait for the page to refresh, the last thing that seems to be updated is the title
WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))
# You should see "cheese! - Google Search"
print driver.title
finally:
driver.quit() | ktan2020/legacy-automation | samples/misc/sel_google_search_phantomjs.py | Python | mit | 1,101 | 0.00545 |
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
"""OpenMM structure I/O --- :mod:`MDAnalysis.converters.OpenMM`
================================================================
Read coordinates data from a
`OpenMM <http://docs.openmm.org/latest/api-python/generated/openmm.app.simulation.Simulation.html#openmm.app.simulation.Simulation>`_
:class:`openmm.app.simulation.Simulation` with :class:`OpenMMReader`
into a MDAnalysis Universe.
Also converts other objects within the
`OpenMM Application Layer <http://docs.openmm.org/latest/api-python/app.html>`_:
- `openmm.app.pdbfile.PDBFile <http://docs.openmm.org/latest/api-python/generated/openmm.app.pdbfile.PDBFile.html#openmm.app.pdbfile.PDBFile>`_
- `openmm.app.modeller.Modeller <http://docs.openmm.org/latest/api-python/generated/openmm.app.modeller.Modeller.html#openmm.app.modeller.Modeller>`_
- `openmm.app.pdbxfile.PDBxFile <http://docs.openmm.org/latest/api-python/generated/openmm.app.pdbxfile.PDBxFile.html#openmm.app.pdbxfile.PDBxFile>`_
Example
-------
OpenMM can read various file formats into OpenMM objects.
MDAnalysis can then convert some of these OpenMM objects into MDAnalysis Universe objects.
>>> import openmm.app as app
>>> import MDAnalysis as mda
>>> from MDAnalysis.tests.datafiles import PDBX
>>> pdbxfile = app.PDBxFile(PDBX)
>>> mda.Universe(pdbxfile)
<Universe with 60 atoms>
Classes
-------
.. autoclass:: OpenMMSimulationReader
:members:
.. autoclass:: OpenMMAppReader
:members:
"""
import numpy as np
from ..coordinates import base
class OpenMMSimulationReader(base.SingleFrameReaderBase):
"""Reader for OpenMM Simulation objects
.. versionadded:: 2.0.0
"""
format = "OPENMMSIMULATION"
units = {"time": "ps", "length": "nm", "velocity": "nm/ps",
"force": "kJ/(mol*nm)", "energy": "kJ/mol"}
@staticmethod
def _format_hint(thing):
"""Can this reader read *thing*?
"""
try:
from openmm.app import Simulation
except ImportError:
try: # pragma: no cover
from simtk.openmm.app import Simulation
except ImportError:
return False
else:
return isinstance(thing, Simulation)
def _read_first_frame(self):
self.n_atoms = self.filename.topology.getNumAtoms()
self.ts = self._mda_timestep_from_omm_context()
if self.convert_units:
self.convert_pos_from_native(self.ts._pos)
self.ts.triclinic_dimensions = self.convert_pos_from_native(
self.ts.triclinic_dimensions, inplace=False
)
self.ts.dimensions[3:] = _sanitize_box_angles(self.ts.dimensions[3:])
self.convert_velocities_from_native(self.ts._velocities)
self.convert_forces_from_native(self.ts._forces)
self.convert_time_from_native(self.ts.dt)
def _mda_timestep_from_omm_context(self):
""" Construct Timestep object from OpenMM context """
try:
import openmm.unit as u
except ImportError: # pragma: no cover
import simtk.unit as u
state = self.filename.context.getState(-1, getVelocities=True,
getForces=True, getEnergy=True)
n_atoms = self.filename.context.getSystem().getNumParticles()
ts = self._Timestep(n_atoms, **self._ts_kwargs)
ts.frame = 0
ts.data["time"] = state.getTime()._value
ts.data["potential_energy"] = (
state.getPotentialEnergy().in_units_of(u.kilojoule/u.mole)
)
ts.data["kinetic_energy"] = (
state.getKineticEnergy().in_units_of(u.kilojoule/u.mole)
)
ts.triclinic_dimensions = state.getPeriodicBoxVectors(
asNumpy=True)._value
ts.dimensions[3:] = _sanitize_box_angles(ts.dimensions[3:])
ts.positions = state.getPositions(asNumpy=True)._value
ts.velocities = state.getVelocities(asNumpy=True)._value
ts.forces = state.getForces(asNumpy=True)._value
return ts
class OpenMMAppReader(base.SingleFrameReaderBase):
"""Reader for OpenMM Application layer objects
See also `the object definition in the OpenMM Application layer <http://docs.openmm.org/latest/api-python/generated/openmm.app.simulation.Simulation.html#openmm.app.simulation.Simulation>`_
.. versionadded:: 2.0.0
"""
format = "OPENMMAPP"
units = {"time": "ps", "length": "nm"}
@staticmethod
def _format_hint(thing):
"""Can this reader read *thing*?
"""
try:
from openmm import app
except ImportError:
try: # pragma: no cover
from simtk.openmm import app
except ImportError:
return False
else:
return isinstance(thing, (app.PDBFile, app.Modeller,
app.PDBxFile))
def _read_first_frame(self):
self.n_atoms = self.filename.topology.getNumAtoms()
self.ts = self._mda_timestep_from_omm_app()
if self.convert_units:
self.convert_pos_from_native(self.ts._pos)
if self.ts.dimensions is not None:
self.ts.triclinic_dimensions = self.convert_pos_from_native(
self.ts.triclinic_dimensions, inplace=False
)
self.ts.dimensions[3:] = _sanitize_box_angles(self.ts.dimensions[3:])
def _mda_timestep_from_omm_app(self):
""" Construct Timestep object from OpenMM Application object """
omm_object = self.filename
n_atoms = omm_object.topology.getNumAtoms()
ts = self._Timestep(n_atoms, **self._ts_kwargs)
ts.frame = 0
if omm_object.topology.getPeriodicBoxVectors() is not None:
ts.triclinic_dimensions = np.array(
omm_object.topology.getPeriodicBoxVectors()._value
)
ts.dimensions[3:] = _sanitize_box_angles(ts.dimensions[3:])
ts.positions = np.array(omm_object.getPositions()._value)
return ts
def _sanitize_box_angles(angles):
""" Ensure box angles correspond to first quadrant
See `discussion on unitcell angles <https://github.com/MDAnalysis/mdanalysis/pull/2917/files#r620558575>`_
"""
inverted = 180 - angles
return np.min(np.array([angles, inverted]), axis=0)
| MDAnalysis/mdanalysis | package/MDAnalysis/converters/OpenMM.py | Python | gpl-2.0 | 7,397 | 0.001622 |
n = int(input())
arr = []
for i in range(n):
arr.append(input())
q = int(input())
for i in range(q):
query = input()
count = 0
for j in range(len(arr)):
if arr[j] == query:
count +=1
print(count)
| vipmunot/HackerRank | Data Structures/Arrays/Sparse Arrays.py | Python | mit | 249 | 0.02008 |
import numpy as np
import json
import sys
from .. import _smcpp, util, logging, data_filter
import smcpp.defaults
from smcpp.optimize.optimizers import SMCPPOptimizer, TwoPopulationOptimizer
from smcpp.optimize.plugins import analysis_saver, parameter_optimizer
logger = logging.getLogger(__name__)
from ..model import SMCModel, SMCTwoPopulationModel
_model_cls_d = {cls.__name__: cls for cls in (SMCModel, SMCTwoPopulationModel)}
class BaseAnalysis:
"Base class for analysis of population genetic data."
def __init__(self, files, args):
# Misc. parameter initialiations
self._args = args
if args.cores is not None:
_smcpp.set_num_threads(args.cores)
self._N0 = .5e-4 / args.mu # .0001 = args.mu * 2 * N0
self._theta = 2. * self._N0 * args.mu
logger.info("theta: %f", self._theta)
if args.r is not None:
self._rho = 2 * self._N0 * args.r
else:
self._rho = self._theta
assert np.all(np.isfinite([self._rho, self._theta]))
logger.info("rho: %f", self._rho)
self._penalty = 0.
self._niter = args.em_iterations
if args.unfold:
args.polarization_error = 0.
logger.warning(
"Using unfolded SFS. The user should verify "
"that the ancestral allele has been correctly "
"coded."
)
if args.polarization_error > 0.:
logger.debug("Polarization error p=%f", args.polarization_error)
# Load data and apply transformations to normalize
pipe = self._pipeline = data_filter.DataPipeline(files)
pipe.add_filter(load_data=data_filter.LoadData())
pipe.add_filter(data_filter.RecodeNonseg(cutoff=args.nonseg_cutoff))
pipe.add_filter(data_filter.Compress())
pipe.add_filter(data_filter.BreakLongSpans(cutoff=100000))
pipe.add_filter(data_filter.DropSmallContigs(100000))
pipe.add_filter(watterson=data_filter.Watterson())
pipe.add_filter(
mutation_counts=data_filter.CountMutations(
w=int(2e-3 * self._N0 / self._rho)
)
)
@property
def hidden_states(self):
return self._hs
@hidden_states.setter
def hidden_states(self, hs):
hs = np.array(hs)
self._hs = {pop: hs for pop in self.populations}
@property
def populations(self):
return self._pipeline["load_data"].populations
def _init_optimizer(self, outdir, base, algorithm, xtol, ftol, single):
self._optimizer = self._OPTIMIZER_CLS(self, algorithm, xtol, ftol, single)
if outdir:
self._optimizer.register_plugin(analysis_saver.AnalysisSaver(outdir, base))
def rescale(self, x):
return x / (2. * self._N0)
def __len__(self):
return sum(len(c) for c in self.contigs)
def _init_inference_manager(self, polarization_error, hs):
## Create inference object which will be used for all further calculations.
logger.debug("Creating inference manager...")
d = {}
max_n = {}
a = {}
self._ims = {}
for c in self.contigs:
d.setdefault(c.pid, []).append(c)
max_n.setdefault(c.pid, -1)
max_n[c.pid] = np.maximum(max_n[c.pid], c.n)
a.setdefault(c.pid, []).append(tuple(c.a))
for pid in d:
logger.debug("Creating inference manager for %s", pid)
data = [c.data for c in d[pid]]
if len(pid) == 1:
im = _smcpp.PyOnePopInferenceManager(max_n[pid], data, hs[pid[0]], pid, polarization_error)
else:
assert len(pid) == 2
s = set(a[pid])
assert len(s) == 1
im = _smcpp.PyTwoPopInferenceManager(
*(max_n[pid]), *s.pop(), data, hs[pid[0]], pid, polarization_error
)
im.model = self._model
im.theta = self._theta
im.rho = self._rho
im.alpha = self._alpha = 1
self._ims[pid] = im
# @property
# def _data(self):
# return [c.data for c in self.contigs]
def run(self, niter=None):
"Perform the analysis."
self._optimizer.run(niter or self._niter)
def Q(self):
"Value of Q() function in M-step."
qq = [self._ims[pop].Q(separate=True) for pop in self._ims]
qr = self._penalty * self.model.regularizer()
qq = np.sum(qq)
ret = qq - qr
logger.debug("reg: %s", util.format_ad(qr))
logger.debug("Q: %s", util.format_ad(ret))
return ret
def E_step(self):
"Perform E-step."
logger.info("Running E-step")
for pop in self._ims:
self._ims[pop].E_step()
logger.info("E-step completed")
def loglik(self, reg=True):
"Log-likelihood of data after most recent E-step."
ll = sum([im.loglik() for im in self._ims.values()])
if reg:
ll -= self._penalty * float(self.model.regularizer())
return ll
@property
def model(self):
return self._model
@model.setter
def model(self, m):
self._model = m
for im in self._ims.values():
im.model = m
@property
def alpha(self):
return self._alpha
@alpha.setter
def alpha(self, a):
self._alpha = a
for im in self._ims.values():
im.alpha = a
@property
def rho(self):
return self._rho
@rho.setter
def rho(self, r):
self._rho = r
for im in self._ims.values():
im.rho = r
@property
def contigs(self):
return list(self._pipeline.results())
@property
def npop(self):
"The number of populations contained in this analysis."
return len(self.populations)
def dump(self, filename):
"Dump result of this analysis to :filename:."
d = {"theta": self._theta, "rho": self._rho, "alpha": self._alpha}
d["model"] = self.model.to_dict()
d["hidden_states"] = {k: list(v) for k, v in self.hidden_states.items()}
json.dump(d, open(filename + ".json", "wt"), sort_keys=True, indent=4)
| terhorst/psmcpp | smcpp/analysis/base.py | Python | gpl-3.0 | 6,269 | 0.001276 |
from csv import DictReader
from django.core.management.base import BaseCommand
from registrations.models import ClinicCode
class Command(BaseCommand):
help = (
"This command takes in a CSV with the columns: uid, code, facility, province,"
"and location, and creates/updates the cliniccodes in the database."
"This will only add or update, it will not remove"
)
def add_arguments(self, parser):
parser.add_argument("data_csv", type=str, help=("The CSV with the data in it"))
def normalise_location(self, location):
"""
Normalises the location from `[longitude,latitude]` to ISO6709
"""
def fractional_part(f):
if not float(f) % 1:
return ""
parts = f.split(".")
return f".{parts[1]}"
try:
longitude, latitude = location.strip("[]").split(",")
return (
f"{int(float(latitude)):+03d}{fractional_part(latitude)}"
f"{int(float(longitude)):+04d}{fractional_part(longitude)}"
"/"
)
except (AttributeError, ValueError, TypeError):
return None
def handle(self, *args, **kwargs):
updated = 0
created = 0
with open(kwargs["data_csv"]) as f:
reader = DictReader(f)
for row in reader:
_, new = ClinicCode.objects.update_or_create(
uid=row["uid"].strip(),
defaults={
"code": row["code"].strip(),
"value": row["code"].strip(),
"name": row["facility"].strip(),
"province": {
"ec": "ZA-EC",
"fs": "ZA-FS",
"gp": "ZA-GT",
"kz": "ZA-NL",
"lp": "ZA-LP",
"mp": "ZA-MP",
"nc": "ZA-NC",
"nw": "ZA-NW",
"wc": "ZA-WC",
}[row["province"].strip()[:2].lower()],
"location": self.normalise_location(row["location"].strip()),
},
)
if new:
created += 1
else:
updated += 1
self.success(f"Updated {updated} and created {created} clinic codes")
def log(self, level, msg):
self.stdout.write(level(msg))
def success(self, msg):
self.log(self.style.SUCCESS, msg)
| praekeltfoundation/ndoh-hub | registrations/management/commands/upload_clinic_codes.py | Python | bsd-3-clause | 2,626 | 0.001142 |
#!/usr/bin/env python
# Copyright 2015 The Kubernetes Authors.
#
# 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 print_function
import argparse
import datetime
import glob
import json
import mmap
import os
import re
import sys
parser = argparse.ArgumentParser()
parser.add_argument("filenames", help="list of files to check, all files if unspecified", nargs='*')
args = parser.parse_args()
rootdir = os.path.dirname(__file__) + "/../../"
rootdir = os.path.abspath(rootdir)
def get_refs():
refs = {}
for path in glob.glob(os.path.join(rootdir, "verify/boilerplate/boilerplate.*.txt")):
extension = os.path.basename(path).split(".")[1]
ref_file = open(path, 'r')
ref = ref_file.read().splitlines()
ref_file.close()
refs[extension] = ref
return refs
def file_passes(filename, refs, regexs):
try:
f = open(filename, 'r')
except:
return False
data = f.read()
f.close()
extension = file_extension(filename)
ref = refs[extension]
# remove build tags from the top of Go files
if extension == "go":
p = regexs["go_build_constraints"]
(data, found) = p.subn("", data, 1)
# remove shebang from the top of shell files
if extension == "sh":
p = regexs["shebang"]
(data, found) = p.subn("", data, 1)
data = data.splitlines()
# if our test file is smaller than the reference it surely fails!
if len(ref) > len(data):
return False
# trim our file to the same number of lines as the reference file
data = data[:len(ref)]
p = regexs["year"]
for d in data:
if p.search(d):
return False
# Replace all occurrences of the regex "2016|2015|2014" with "YEAR"
p = regexs["date"]
for i, d in enumerate(data):
(data[i], found) = p.subn('YEAR', d)
if found != 0:
break
# if we don't match the reference at this point, fail
if ref != data:
return False
return True
def file_extension(filename):
return os.path.splitext(filename)[1].split(".")[-1].lower()
skipped_dirs = ['Godeps', 'third_party', '_output', '.git', 'vendor']
def normalize_files(files):
newfiles = []
for pathname in files:
if any(x in pathname for x in skipped_dirs):
continue
newfiles.append(pathname)
for i, pathname in enumerate(newfiles):
if not os.path.isabs(pathname):
newfiles[i] = os.path.join(rootdir, pathname)
return newfiles
def get_files(extensions):
files = []
if len(args.filenames) > 0:
files = args.filenames
else:
for root, dirs, walkfiles in os.walk(rootdir):
# don't visit certain dirs. This is just a performance improvement
# as we would prune these later in normalize_files(). But doing it
# cuts down the amount of filesystem walking we do and cuts down
# the size of the file list
for d in skipped_dirs:
if d in dirs:
dirs.remove(d)
for name in walkfiles:
pathname = os.path.join(root, name)
files.append(pathname)
files = normalize_files(files)
outfiles = []
for pathname in files:
extension = file_extension(pathname)
if extension in extensions:
outfiles.append(pathname)
return outfiles
def get_dates():
years = datetime.datetime.now().year
return '(%s)' % '|'.join((str(year) for year in range(2014, years+1)))
def get_regexs():
regexs = {}
# Search for "YEAR" which exists in the boilerplate, but shouldn't in the real thing
regexs["year"] = re.compile( 'YEAR' )
# dates can be 2014, 2015,... till current year, company holder names can be anything
regexs["date"] = re.compile(get_dates())
# strip // +build \n\n build constraints
regexs["go_build_constraints"] = re.compile(r"^(// \+build.*\n)+\n", re.MULTILINE)
# strip #!.* from shell scripts
regexs["shebang"] = re.compile(r"^(#!.*\n)\n*", re.MULTILINE)
return regexs
def main():
regexs = get_regexs()
refs = get_refs()
filenames = get_files(refs.keys())
for filename in filenames:
if not file_passes(filename, refs, regexs):
print(filename, file=sys.stdout)
if __name__ == "__main__":
sys.exit(main())
| sjug/perf-tests | verify/boilerplate/boilerplate.py | Python | apache-2.0 | 4,896 | 0.003881 |
__all__ = [
'json_schema',
]
import lollipop.types as lt
import lollipop.validators as lv
from lollipop.utils import identity
from collections import OrderedDict
from .compat import iteritems
def find_validators(schema, validator_type):
return [validator
for validator in schema.validators
if isinstance(validator, validator_type)]
def json_schema(schema):
"""Convert Lollipop schema to JSON schema"""
js = OrderedDict()
if schema.name:
js['title'] = schema.name
if schema.description:
js['description'] = schema.description
any_of_validators = find_validators(schema, lv.AnyOf)
if any_of_validators:
choices = set(any_of_validators[0].choices)
for validator in any_of_validators[1:]:
choices = choices.intersection(set(validator.choices))
if not choices:
raise ValueError('AnyOf constraints choices does not allow any values')
js['enum'] = list(schema.dump(choice) for choice in choices)
return js
none_of_validators = find_validators(schema, lv.NoneOf)
if none_of_validators:
choices = set(none_of_validators[0].values)
for validator in none_of_validators[1:]:
choices = choices.union(set(validator.values))
if choices:
js['not'] = {'enum': list(schema.dump(choice) for choice in choices)}
if isinstance(schema, lt.Any):
pass
elif isinstance(schema, lt.String):
js['type'] = 'string'
length_validators = find_validators(schema, lv.Length)
if length_validators:
if any(v.min for v in length_validators) or \
any(v.exact for v in length_validators):
js['minLength'] = max(v.exact or v.min for v in length_validators)
if any(v.max for v in length_validators) or \
any(v.exact for v in length_validators):
js['maxLength'] = min(v.exact or v.max for v in length_validators)
regexp_validators = find_validators(schema, lv.Regexp)
if regexp_validators:
js['pattern'] = regexp_validators[0].regexp.pattern
elif isinstance(schema, lt.Number):
if isinstance(schema, lt.Integer):
js['type'] = 'integer'
else:
js['type'] = 'number'
range_validators = find_validators(schema, lv.Range)
if range_validators:
if any(v.min for v in range_validators):
js['minimum'] = max(v.min for v in range_validators if v.min)
if any(v.max for v in range_validators):
js['maximum'] = min(v.max for v in range_validators if v.max)
elif isinstance(schema, lt.Boolean):
js['type'] = 'boolean'
elif isinstance(schema, lt.List):
js['type'] = 'array'
js['items'] = json_schema(schema.item_type)
length_validators = find_validators(schema, lv.Length)
if length_validators:
if any(v.min for v in length_validators) or \
any(v.exact for v in length_validators):
js['minItems'] = min(v.exact or v.min for v in length_validators)
if any(v.max for v in length_validators) or \
any(v.exact for v in length_validators):
js['maxItems'] = min(v.exact or v.max for v in length_validators)
unique_validators = find_validators(schema, lv.Unique)
if unique_validators and any(v.key is identity for v in unique_validators):
js['uniqueItems'] = True
elif isinstance(schema, lt.Tuple):
js['type'] = 'array'
js['items'] = [json_schema(item_type) for item_type in schema.item_types]
elif isinstance(schema, lt.Object):
js['type'] = 'object'
js['properties'] = OrderedDict(
(k, json_schema(v.field_type))
for k, v in iteritems(schema.fields)
)
required = [
k
for k, v in iteritems(schema.fields)
if not isinstance(v.field_type, lt.Optional)
]
if required:
js['required'] = required
if schema.allow_extra_fields in [True, False]:
js['additionalProperties'] = schema.allow_extra_fields
elif isinstance(schema.allow_extra_fields, lt.Field):
field_type = schema.allow_extra_fields.field_type
if isinstance(field_type, lt.Any):
js['additionalProperties'] = True
else:
js['additionalProperties'] = json_schema(field_type)
elif isinstance(schema, lt.Dict):
js['type'] = 'object'
fixed_properties = schema.value_types \
if hasattr(schema.value_types, 'keys') else {}
properties = OrderedDict(
(k, json_schema(v))
for k, v in iteritems(fixed_properties)
)
if properties:
js['properties'] = properties
required = [
k
for k, v in iteritems(fixed_properties)
if not isinstance(v, lt.Optional)
]
if required:
js['required'] = required
if hasattr(schema.value_types, 'default'):
js['additionalProperties'] = json_schema(schema.value_types.default)
elif isinstance(schema, lt.Constant):
js['const'] = schema.value
elif isinstance(schema, lt.Optional):
js.update(json_schema(schema.inner_type))
default = schema.load_default()
if default:
js['default'] = schema.inner_type.dump(default)
elif hasattr(schema, 'inner_type'):
js.update(json_schema(schema.inner_type))
return js
| akscram/lollipop-jsonschema | lollipop_jsonschema/jsonschema.py | Python | mit | 5,661 | 0.00159 |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements staffline distance estimation.
The staffline distance is the vertical distance between consecutive lines in a
staff, which is assumed to be uniform for a single staff on a scanned music
score. The staffline thickness is the vertical height of each staff line, which
is assumed to be uniform for the entire page.
Uses the algorithm described in [1], which creates a histogram of possible
staffline distance and thickness values for the entire image, based on the
vertical run-length encoding [2]. Each consecutive pair of black and white runs
contributes to the staffline distance histogram (because they may be the
staffline followed by an unobstructed space, or vice versa). We then take the
argmax of the histogram, and find candidate staff line runs. These runs must be
before or after another run, such that the sum of the run lengths is the
detected staffline distance. Then the black run is considered to be an actual
staff line, and its length contributes to the staffline thickness histogram.
Although we use a single staffline distance value for staffline thickness
detection, we may detect multiple distinct peaks in the histogram. We then run
staff detection using each distinct peak value, to detect smaller staves with an
unusual size, e.g. ossia parts [3].
[1] Cardoso, Jaime S., and Ana Rebelo. "Robust staffline thickness and distance
estimation in binary and gray-level music scores." 20th International
Conference on Pattern Recognition (ICPR). IEEE, 2010.
[2] https://en.wikipedia.org/wiki/Run-length_encoding
[3] https://en.wikipedia.org/wiki/Ossia
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from moonlight.util import run_length
from moonlight.util import segments
# The size of the histograms. Normal values for the peak are around 20 for
# staffline distance, and 2-3 for staffline thickness.
_MAX_STAFFLINE_DISTANCE_THICKNESS_VALUE = 256
# The minimum number of votes for a staffline distance bin. We expect images to
# be a reasonable size (> 100x100), and want to ensure we exclude images that
# don't contain any staves.
_MIN_STAFFLINE_DISTANCE_SCORE = 10000
# The maximum allowed number of unique staffline distances. If more staffline
# distances are detected, return an empty list instead.
_MAX_ALLOWED_UNIQUE_STAFFLINE_DISTANCES = 3
_STAFFLINE_DISTANCE_INVALIDATE_DISTANCE = 1
_STAFFLINE_THICKNESS_INVALIDATE_DISTANCE = 1
_PEAK_CUTOFF = 0.5
def _single_peak(values, relative_cutoff, minval, invalidate_distance):
"""Takes a single peak if it is high enough compared to all other peaks.
Args:
values: 1D tensor of values to take the peaks on.
relative_cutoff: The fraction of the highest peak which all other peaks
should be below.
minval: The peak should have at least this value.
invalidate_distance: Exclude values that are up to invalidate_distance away
from the peak.
Returns:
The index of the single peak in `values`, or -1 if there is not a single
peak that satisfies `relative_cutoff`.
"""
relative_cutoff = tf.convert_to_tensor(relative_cutoff, tf.float32)
# argmax is safe because the histogram is always non-empty.
peak = tf.to_int32(tf.argmax(values))
# Take values > minval away from the peak.
other_values = tf.boolean_mask(
values,
tf.greater(
tf.abs(tf.range(tf.shape(values)[0]) - peak), invalidate_distance))
should_take_peak = tf.logical_and(
tf.greater_equal(values[peak], minval),
# values[peak] * relative_cutoff must be >= other_values.
tf.reduce_all(
tf.greater_equal(
tf.to_float(values[peak]) * relative_cutoff,
tf.to_float(other_values))))
return tf.cond(should_take_peak, lambda: peak, lambda: -1)
def _estimate_staffline_distance(columns, lengths):
"""Estimates the staffline distances of a music score.
Args:
columns: 1D array. The column indices of each vertical run.
lengths: 1D array. The length of each consecutive vertical run.
Returns:
A 1D tensor of possible staffline distances in the image.
"""
with tf.name_scope('estimate_staffline_distance'):
run_pair_lengths = lengths[:-1] + lengths[1:]
keep_pair = tf.equal(columns[:-1], columns[1:])
staffline_distance_histogram = tf.bincount(
tf.boolean_mask(run_pair_lengths, keep_pair),
# minlength required to avoid errors on a fully white image.
minlength=_MAX_STAFFLINE_DISTANCE_THICKNESS_VALUE,
maxlength=_MAX_STAFFLINE_DISTANCE_THICKNESS_VALUE)
peaks = segments.peaks(
staffline_distance_histogram,
minval=_MIN_STAFFLINE_DISTANCE_SCORE,
invalidate_distance=_STAFFLINE_DISTANCE_INVALIDATE_DISTANCE)
def do_filter_peaks():
"""Process the peaks if they are non-empty.
Returns:
The filtered peaks. Peaks below the cutoff when compared to the highest
peak are removed. If the peaks are invalid, then an empty list is
returned.
"""
histogram_size = tf.shape(staffline_distance_histogram)[0]
peak_values = tf.to_float(tf.gather(staffline_distance_histogram, peaks))
max_value = tf.reduce_max(peak_values)
allowed_peaks = tf.greater_equal(peak_values,
max_value * tf.constant(_PEAK_CUTOFF))
# Check if there are too many detected staffline distances, and we should
# return an empty list.
allowed_peaks &= tf.less_equal(
tf.reduce_sum(tf.to_int32(allowed_peaks)),
_MAX_ALLOWED_UNIQUE_STAFFLINE_DISTANCES)
# Check if any values sufficiently far away from the peaks are too high.
# This means the peaks are not sharp enough and we should return an empty
# list.
far_from_peak = tf.greater(
tf.reduce_min(
tf.abs(tf.range(histogram_size)[None, :] - peaks[:, None]),
axis=0), _STAFFLINE_DISTANCE_INVALIDATE_DISTANCE)
allowed_peaks &= tf.less(
tf.to_float(
tf.reduce_max(
tf.boolean_mask(staffline_distance_histogram,
far_from_peak))),
max_value * tf.constant(_PEAK_CUTOFF))
return tf.boolean_mask(peaks, allowed_peaks)
return tf.cond(
tf.greater(tf.shape(peaks)[0], 0), do_filter_peaks,
lambda: tf.identity(peaks))
def _estimate_staffline_thickness(columns, values, lengths, staffline_distance):
"""Estimates the staffline thickness of a music score.
Args:
columns: 1D array. The column indices of each consecutive vertical run.
values: 1D array. The value (0 or 1) of each vertical run.
lengths: 1D array. The length of each vertical run.
staffline_distance: A 1D tensor of the possible staffline distances in the
image. One of the distances may be chosen arbitrarily.
Returns:
A scalar tensor with the staffline thickness for the entire page, or -1 if
it could not be estimated (staffline_distance is empty, or there are not
enough runs to estimate the staffline thickness).
"""
with tf.name_scope('estimate_staffline_thickness'):
def do_estimate():
"""Compute the thickness if distance detection was successful."""
run_pair_lengths = lengths[:-1] + lengths[1:]
# Use the smallest staffline distance to estimate the staffline thickness.
keep_pair = tf.logical_and(
tf.equal(columns[:-1], columns[1:]),
tf.equal(run_pair_lengths, staffline_distance[0]))
run_pair_lengths = tf.boolean_mask(run_pair_lengths, keep_pair)
start_values = tf.boolean_mask(values[:-1], keep_pair)
start_lengths = tf.boolean_mask(lengths[:-1], keep_pair)
end_lengths = tf.boolean_mask(lengths[1:], keep_pair)
staffline_thickness_values = tf.where(
tf.not_equal(start_values, 0), start_lengths, end_lengths)
staffline_thickness_histogram = tf.bincount(
staffline_thickness_values,
minlength=_MAX_STAFFLINE_DISTANCE_THICKNESS_VALUE,
maxlength=_MAX_STAFFLINE_DISTANCE_THICKNESS_VALUE)
return _single_peak(
staffline_thickness_histogram,
_PEAK_CUTOFF,
minval=1,
invalidate_distance=_STAFFLINE_THICKNESS_INVALIDATE_DISTANCE)
return tf.cond(
tf.greater(tf.shape(staffline_distance)[0], 0), do_estimate,
lambda: tf.constant(-1, tf.int32))
def estimate_staffline_distance_and_thickness(image, threshold=127):
"""Estimates the staffline distance and thickness of a music score.
Args:
image: A 2D tensor (HW) and type uint8.
threshold: The global threshold for the image.
Returns:
The estimated vertical distance(s) from the center of one staffline to the
next in the music score. 1D tensor containing all unique values of the
estimated staffline distance for each staff.
The estimated staffline thickness of the music score.
Raises:
TypeError: If `image` is an invalid type.
"""
image = tf.convert_to_tensor(image, name='image', dtype=tf.uint8)
threshold = tf.convert_to_tensor(threshold, name='threshold', dtype=tf.uint8)
if image.dtype.base_dtype != tf.uint8:
raise TypeError('Invalid dtype %s.' % image.dtype)
columns, values, lengths = run_length.vertical_run_length_encoding(
tf.less(image, threshold))
staffline_distance = _estimate_staffline_distance(columns, lengths)
staffline_thickness = _estimate_staffline_thickness(columns, values, lengths,
staffline_distance)
# staffline_thickness may be -1 even if staffline_distance > 0. Fix it so
# that we can check either one to determine whether there are staves.
staffline_distance = tf.cond(
tf.equal(staffline_thickness, -1), lambda: tf.zeros([0], tf.int32),
lambda: tf.identity(staffline_distance))
return staffline_distance, staffline_thickness
| tensorflow/moonlight | moonlight/staves/staffline_distance.py | Python | apache-2.0 | 10,559 | 0.00483 |
from django.conf import settings, UserSettingsHolder
from django.contrib.auth.models import User
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test.client import Client
from django.utils.functional import wraps
from django.utils.importlib import import_module
import constance.config
from constance.backends import database as constance_database
from nose import SkipTest
from nose.tools import eq_
import test_utils
from ..exceptions import FixtureMissingError
from ..urlresolvers import split_path, reverse
get = lambda c, v, **kw: c.get(reverse(v, **kw), follow=True)
post = lambda c, v, data={}, **kw: c.post(reverse(v, **kw), data, follow=True)
def attrs_eq(received, **expected):
"""Compares received's attributes with expected's kwargs."""
for k, v in expected.iteritems():
eq_(v, getattr(received, k))
def get_user(username='testuser'):
"""Return a django user or raise FixtureMissingError"""
try:
return User.objects.get(username=username)
except User.DoesNotExist:
raise FixtureMissingError(
'Username "%s" not found. You probably forgot to import a'
' users fixture.' % username)
class overrider(object):
"""
See http://djangosnippets.org/snippets/2437/
Acts as either a decorator, or a context manager. If it's a decorator it
takes a function and returns a wrapped function. If it's a contextmanager
it's used with the ``with`` statement. In either event entering/exiting
are called before and after, respectively, the function/block is executed.
"""
def __init__(self, **kwargs):
self.options = kwargs
def __enter__(self):
self.enable()
def __exit__(self, exc_type, exc_value, traceback):
self.disable()
def __call__(self, func):
@wraps(func)
def inner(*args, **kwargs):
with self:
return func(*args, **kwargs)
return inner
def enable(self):
pass
def disable(self):
pass
class override_constance_settings(overrider):
"""Decorator / context manager to override constance settings and defeat
its caching."""
def enable(self):
self.old_cache = constance_database.db_cache
constance_database.db_cache = None
self.old_settings = dict((k, getattr(constance.config, k))
for k in dir(constance.config))
for k, v in self.options.items():
constance.config._backend.set(k, v)
def disable(self):
for k, v in self.old_settings.items():
constance.config._backend.set(k, v)
constance_database.db_cache = self.old_cache
class override_settings(overrider):
"""Decorator / context manager to override Django settings"""
def enable(self):
self.old_settings = settings._wrapped
override = UserSettingsHolder(settings._wrapped)
for key, new_value in self.options.items():
setattr(override, key, new_value)
settings._wrapped = override
def disable(self):
settings._wrapped = self.old_settings
def mock_lookup_user():
return {u'confirmed': True,
u'country': u'us',
u'created-date': u'12/8/2013 8:05:55 AM',
u'email': u'testuser@test.com',
u'format': u'H',
u'lang': u'en-US',
u'master': True,
u'newsletters': [],
u'pending': False,
u'status': u'ok',
u'token': u'cdaa9e5d-2023-5f59-974d-83f6a29514ec'}
class SessionAwareClient(Client):
"""
Just a small override to patch the session property to be able to
use the sessions.
"""
def _session(self):
"""
Obtains the current session variables.
Backported the else clause from Django 1.7 to make sure there
is a session available during tests.
"""
if 'django.contrib.sessions' in settings.INSTALLED_APPS:
engine = import_module(settings.SESSION_ENGINE)
cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
if cookie:
return engine.SessionStore(cookie.value)
else:
session = engine.SessionStore()
session.save()
self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
return session
return {}
session = property(_session)
class LocalizingMixin(object):
def request(self, **request):
"""Make a request, but prepend a locale if there isn't one already."""
# Fall back to defaults as in the superclass's implementation:
path = request.get('PATH_INFO', self.defaults.get('PATH_INFO', '/'))
locale, shortened = split_path(path)
if not locale:
request['PATH_INFO'] = '/%s/%s' % (settings.LANGUAGE_CODE,
shortened)
return super(LocalizingMixin, self).request(**request)
class LocalizingClient(LocalizingMixin, SessionAwareClient):
"""Client which prepends a locale so test requests can get through
LocaleURLMiddleware without resulting in a locale-prefix-adding 301.
Otherwise, we'd have to hard-code locales into our tests everywhere or
{mock out reverse() and make LocaleURLMiddleware not fire}.
"""
# If you use this, you might also find the force_locale=True argument to
# kuma.core.urlresolvers.reverse() handy, in case you need to force locale
# prepending in a one-off case or do it outside a mock request.
class KumaTestCase(test_utils.TestCase):
client_class = SessionAwareClient
localizing_client = False
skipme = False
@classmethod
def setUpClass(cls):
if cls.skipme:
raise SkipTest
if cls.localizing_client:
cls.client_class = LocalizingClient
super(KumaTestCase, cls).setUpClass()
def get_messages(self, request):
# Django 1.4 RequestFactory requests can't be used to test views that
# call messages.add (https://code.djangoproject.com/ticket/17971)
# FIXME: HACK from http://stackoverflow.com/q/11938164/571420
messages = FallbackStorage(request)
request._messages = messages
return messages
class SkippedTestCase(KumaTestCase):
skipme = True
| mastizada/kuma | kuma/core/tests/__init__.py | Python | mpl-2.0 | 6,376 | 0.000471 |
import copy
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django_countries import countries
import accounts
import third_party_auth
from edxmako.shortcuts import marketing_link
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from openedx.core.djangoapps.user_api.helpers import FormDescription
from openedx.features.enterprise_support.api import enterprise_customer_for_request
from student.forms import get_registration_extension_form
from student.models import UserProfile
def get_password_reset_form():
"""Return a description of the password reset form.
This decouples clients from the API definition:
if the API decides to modify the form, clients won't need
to be updated.
See `user_api.helpers.FormDescription` for examples
of the JSON-encoded form description.
Returns:
HttpResponse
"""
form_desc = FormDescription("post", reverse("password_change_request"))
# Translators: This label appears above a field on the password reset
# form meant to hold the user's email address.
email_label = _(u"Email")
# Translators: This example email address is used as a placeholder in
# a field on the password reset form meant to hold the user's email address.
email_placeholder = _(u"username@domain.com")
# Translators: These instructions appear on the password reset form,
# immediately below a field meant to hold the user's email address.
email_instructions = _(u"The email address you used to register with {platform_name}").format(
platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)
)
form_desc.add_field(
"email",
field_type="email",
label=email_label,
placeholder=email_placeholder,
instructions=email_instructions,
restrictions={
"min_length": accounts.EMAIL_MIN_LENGTH,
"max_length": accounts.EMAIL_MAX_LENGTH,
}
)
return form_desc
def get_login_session_form():
"""Return a description of the login form.
This decouples clients from the API definition:
if the API decides to modify the form, clients won't need
to be updated.
See `user_api.helpers.FormDescription` for examples
of the JSON-encoded form description.
Returns:
HttpResponse
"""
form_desc = FormDescription("post", reverse("user_api_login_session"))
# Translators: This label appears above a field on the login form
# meant to hold the user's email address.
email_label = _(u"Email")
# Translators: This example email address is used as a placeholder in
# a field on the login form meant to hold the user's email address.
email_placeholder = _(u"username@domain.com")
# Translators: These instructions appear on the login form, immediately
# below a field meant to hold the user's email address.
email_instructions = _("The email address you used to register with {platform_name}").format(
platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)
)
form_desc.add_field(
"email",
field_type="email",
label=email_label,
placeholder=email_placeholder,
instructions=email_instructions,
restrictions={
"min_length": accounts.EMAIL_MIN_LENGTH,
"max_length": accounts.EMAIL_MAX_LENGTH,
}
)
# Translators: This label appears above a field on the login form
# meant to hold the user's password.
password_label = _(u"Password")
form_desc.add_field(
"password",
label=password_label,
field_type="password",
restrictions={
"max_length": accounts.PASSWORD_MAX_LENGTH,
}
)
form_desc.add_field(
"remember",
field_type="checkbox",
label=_("Remember me"),
default=False,
required=False,
)
return form_desc
class RegistrationFormFactory(object):
"""HTTP end-points for creating a new user. """
DEFAULT_FIELDS = ["email", "name", "username", "password"]
EXTRA_FIELDS = [
"confirm_email",
"first_name",
"last_name",
"city",
"state",
"country",
"gender",
"year_of_birth",
"level_of_education",
"company",
"title",
"mailing_address",
"goals",
"honor_code",
"terms_of_service",
"profession",
"specialty",
]
def _is_field_visible(self, field_name):
"""Check whether a field is visible based on Django settings. """
return self._extra_fields_setting.get(field_name) in ["required", "optional"]
def _is_field_required(self, field_name):
"""Check whether a field is required based on Django settings. """
return self._extra_fields_setting.get(field_name) == "required"
def __init__(self):
# Backwards compatibility: Honor code is required by default, unless
# explicitly set to "optional" in Django settings.
self._extra_fields_setting = copy.deepcopy(configuration_helpers.get_value('REGISTRATION_EXTRA_FIELDS'))
if not self._extra_fields_setting:
self._extra_fields_setting = copy.deepcopy(settings.REGISTRATION_EXTRA_FIELDS)
self._extra_fields_setting["honor_code"] = self._extra_fields_setting.get("honor_code", "required")
# Check that the setting is configured correctly
for field_name in self.EXTRA_FIELDS:
if self._extra_fields_setting.get(field_name, "hidden") not in ["required", "optional", "hidden"]:
msg = u"Setting REGISTRATION_EXTRA_FIELDS values must be either required, optional, or hidden."
raise ImproperlyConfigured(msg)
# Map field names to the instance method used to add the field to the form
self.field_handlers = {}
valid_fields = self.DEFAULT_FIELDS + self.EXTRA_FIELDS
for field_name in valid_fields:
handler = getattr(self, "_add_{field_name}_field".format(field_name=field_name))
self.field_handlers[field_name] = handler
field_order = configuration_helpers.get_value('REGISTRATION_FIELD_ORDER')
if not field_order:
field_order = settings.REGISTRATION_FIELD_ORDER or valid_fields
# Check that all of the valid_fields are in the field order and vice versa, if not set to the default order
if set(valid_fields) != set(field_order):
field_order = valid_fields
self.field_order = field_order
def get_registration_form(self, request):
"""Return a description of the registration form.
This decouples clients from the API definition:
if the API decides to modify the form, clients won't need
to be updated.
This is especially important for the registration form,
since different edx-platform installations might
collect different demographic information.
See `user_api.helpers.FormDescription` for examples
of the JSON-encoded form description.
Arguments:
request (HttpRequest)
Returns:
HttpResponse
"""
form_desc = FormDescription("post", reverse("user_api_registration"))
self._apply_third_party_auth_overrides(request, form_desc)
# Custom form fields can be added via the form set in settings.REGISTRATION_EXTENSION_FORM
custom_form = get_registration_extension_form()
if custom_form:
# Default fields are always required
for field_name in self.DEFAULT_FIELDS:
self.field_handlers[field_name](form_desc, required=True)
for field_name, field in custom_form.fields.items():
restrictions = {}
if getattr(field, 'max_length', None):
restrictions['max_length'] = field.max_length
if getattr(field, 'min_length', None):
restrictions['min_length'] = field.min_length
field_options = getattr(
getattr(custom_form, 'Meta', None), 'serialization_options', {}
).get(field_name, {})
field_type = field_options.get('field_type', FormDescription.FIELD_TYPE_MAP.get(field.__class__))
if not field_type:
raise ImproperlyConfigured(
"Field type '{}' not recognized for registration extension field '{}'.".format(
field_type,
field_name
)
)
form_desc.add_field(
field_name, label=field.label,
default=field_options.get('default'),
field_type=field_options.get('field_type', FormDescription.FIELD_TYPE_MAP.get(field.__class__)),
placeholder=field.initial, instructions=field.help_text, required=field.required,
restrictions=restrictions,
options=getattr(field, 'choices', None), error_messages=field.error_messages,
include_default_option=field_options.get('include_default_option'),
)
# Extra fields configured in Django settings
# may be required, optional, or hidden
for field_name in self.EXTRA_FIELDS:
if self._is_field_visible(field_name):
self.field_handlers[field_name](
form_desc,
required=self._is_field_required(field_name)
)
else:
# Go through the fields in the fields order and add them if they are required or visible
for field_name in self.field_order:
if field_name in self.DEFAULT_FIELDS:
self.field_handlers[field_name](form_desc, required=True)
elif self._is_field_visible(field_name):
self.field_handlers[field_name](
form_desc,
required=self._is_field_required(field_name)
)
return form_desc
def _add_email_field(self, form_desc, required=True):
"""Add an email field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a field on the registration form
# meant to hold the user's email address.
email_label = _(u"Email")
# Translators: This example email address is used as a placeholder in
# a field on the registration form meant to hold the user's email address.
email_placeholder = _(u"username@domain.com")
# Translators: These instructions appear on the registration form, immediately
# below a field meant to hold the user's email address.
email_instructions = _(u"This is what you will use to login.")
form_desc.add_field(
"email",
field_type="email",
label=email_label,
placeholder=email_placeholder,
instructions=email_instructions,
restrictions={
"min_length": accounts.EMAIL_MIN_LENGTH,
"max_length": accounts.EMAIL_MAX_LENGTH,
},
required=required
)
def _add_confirm_email_field(self, form_desc, required=True):
"""Add an email confirmation field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a field on the registration form
# meant to confirm the user's email address.
email_label = _(u"Confirm Email")
error_msg = accounts.REQUIRED_FIELD_CONFIRM_EMAIL_MSG
form_desc.add_field(
"confirm_email",
label=email_label,
required=required,
error_messages={
"required": error_msg
}
)
def _add_name_field(self, form_desc, required=True):
"""Add a name field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a field on the registration form
# meant to hold the user's full name.
name_label = _(u"Full Name")
# Translators: This example name is used as a placeholder in
# a field on the registration form meant to hold the user's name.
name_placeholder = _(u"Jane Q. Learner")
# Translators: These instructions appear on the registration form, immediately
# below a field meant to hold the user's full name.
name_instructions = _(u"This name will be used on any certificates that you earn.")
form_desc.add_field(
"name",
label=name_label,
placeholder=name_placeholder,
instructions=name_instructions,
restrictions={
"max_length": accounts.NAME_MAX_LENGTH,
},
required=required
)
def _add_username_field(self, form_desc, required=True):
"""Add a username field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a field on the registration form
# meant to hold the user's public username.
username_label = _(u"Public Username")
username_instructions = _(
# Translators: These instructions appear on the registration form, immediately
# below a field meant to hold the user's public username.
u"The name that will identify you in your courses. "
u"It cannot be changed later."
)
# Translators: This example username is used as a placeholder in
# a field on the registration form meant to hold the user's username.
username_placeholder = _(u"Jane_Q_Learner")
form_desc.add_field(
"username",
label=username_label,
instructions=username_instructions,
placeholder=username_placeholder,
restrictions={
"min_length": accounts.USERNAME_MIN_LENGTH,
"max_length": accounts.USERNAME_MAX_LENGTH,
},
required=required
)
def _add_password_field(self, form_desc, required=True):
"""Add a password field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a field on the registration form
# meant to hold the user's password.
password_label = _(u"Password")
form_desc.add_field(
"password",
label=password_label,
field_type="password",
restrictions={
"min_length": accounts.PASSWORD_MIN_LENGTH,
"max_length": accounts.PASSWORD_MAX_LENGTH,
},
required=required
)
def _add_level_of_education_field(self, form_desc, required=True):
"""Add a level of education field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a dropdown menu on the registration
# form used to select the user's highest completed level of education.
education_level_label = _(u"Highest level of education completed")
error_msg = accounts.REQUIRED_FIELD_LEVEL_OF_EDUCATION_MSG
# The labels are marked for translation in UserProfile model definition.
options = [(name, _(label)) for name, label in UserProfile.LEVEL_OF_EDUCATION_CHOICES] # pylint: disable=translation-of-non-string
form_desc.add_field(
"level_of_education",
label=education_level_label,
field_type="select",
options=options,
include_default_option=True,
required=required,
error_messages={
"required": error_msg
}
)
def _add_gender_field(self, form_desc, required=True):
"""Add a gender field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a dropdown menu on the registration
# form used to select the user's gender.
gender_label = _(u"Gender")
# The labels are marked for translation in UserProfile model definition.
options = [(name, _(label)) for name, label in UserProfile.GENDER_CHOICES] # pylint: disable=translation-of-non-string
form_desc.add_field(
"gender",
label=gender_label,
field_type="select",
options=options,
include_default_option=True,
required=required
)
def _add_year_of_birth_field(self, form_desc, required=True):
"""Add a year of birth field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a dropdown menu on the registration
# form used to select the user's year of birth.
yob_label = _(u"Year of birth")
options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS]
form_desc.add_field(
"year_of_birth",
label=yob_label,
field_type="select",
options=options,
include_default_option=True,
required=required
)
def _add_field_with_configurable_select_options(self, field_name, field_label, form_desc, required=False):
"""Add a field to a form description.
If select options are given for this field, it will be a select type
otherwise it will be a text type.
Arguments:
field_name: name of field
field_label: label for the field
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to False
"""
extra_field_options = configuration_helpers.get_value('EXTRA_FIELD_OPTIONS')
if extra_field_options is None or extra_field_options.get(field_name) is None:
field_type = "text"
include_default_option = False
options = None
error_msg = ''
exec("error_msg = accounts.REQUIRED_FIELD_%s_TEXT_MSG" % (field_name.upper()))
else:
field_type = "select"
include_default_option = True
field_options = extra_field_options.get(field_name)
options = [(unicode(option.lower()), option) for option in field_options]
error_msg = ''
exec("error_msg = accounts.REQUIRED_FIELD_%s_SELECT_MSG" % (field_name.upper()))
form_desc.add_field(
field_name,
label=field_label,
field_type=field_type,
options=options,
include_default_option=include_default_option,
required=required,
error_messages={
"required": error_msg
}
)
def _add_profession_field(self, form_desc, required=False):
"""Add a profession field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to False
"""
# Translators: This label appears above a dropdown menu on the registration
# form used to select the user's profession
profession_label = _("Profession")
self._add_field_with_configurable_select_options('profession', profession_label, form_desc, required=required)
def _add_specialty_field(self, form_desc, required=False):
"""Add a specialty field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to False
"""
# Translators: This label appears above a dropdown menu on the registration
# form used to select the user's specialty
specialty_label = _("Specialty")
self._add_field_with_configurable_select_options('specialty', specialty_label, form_desc, required=required)
def _add_mailing_address_field(self, form_desc, required=True):
"""Add a mailing address field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a field on the registration form
# meant to hold the user's mailing address.
mailing_address_label = _(u"Mailing address")
error_msg = accounts.REQUIRED_FIELD_MAILING_ADDRESS_MSG
form_desc.add_field(
"mailing_address",
label=mailing_address_label,
field_type="textarea",
required=required,
error_messages={
"required": error_msg
}
)
def _add_goals_field(self, form_desc, required=True):
"""Add a goals field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This phrase appears above a field on the registration form
# meant to hold the user's reasons for registering with edX.
goals_label = _(u"Tell us why you're interested in {platform_name}").format(
platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME)
)
error_msg = accounts.REQUIRED_FIELD_GOALS_MSG
form_desc.add_field(
"goals",
label=goals_label,
field_type="textarea",
required=required,
error_messages={
"required": error_msg
}
)
def _add_city_field(self, form_desc, required=True):
"""Add a city field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a field on the registration form
# which allows the user to input the city in which they live.
city_label = _(u"City")
error_msg = accounts.REQUIRED_FIELD_CITY_MSG
form_desc.add_field(
"city",
label=city_label,
required=required,
error_messages={
"required": error_msg
}
)
def _add_state_field(self, form_desc, required=False):
"""Add a State/Province/Region field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to False
"""
# Translators: This label appears above a field on the registration form
# which allows the user to input the State/Province/Region in which they live.
state_label = _(u"State/Province/Region")
form_desc.add_field(
"state",
label=state_label,
required=required
)
def _add_company_field(self, form_desc, required=False):
"""Add a Company field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to False
"""
# Translators: This label appears above a field on the registration form
# which allows the user to input the Company
company_label = _(u"Company")
form_desc.add_field(
"company",
label=company_label,
required=required
)
def _add_title_field(self, form_desc, required=False):
"""Add a Title field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to False
"""
# Translators: This label appears above a field on the registration form
# which allows the user to input the Title
title_label = _(u"Title")
form_desc.add_field(
"title",
label=title_label,
required=required
)
def _add_first_name_field(self, form_desc, required=False):
"""Add a First Name field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to False
"""
# Translators: This label appears above a field on the registration form
# which allows the user to input the First Name
first_name_label = _(u"First Name")
form_desc.add_field(
"first_name",
label=first_name_label,
required=required
)
def _add_last_name_field(self, form_desc, required=False):
"""Add a Last Name field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to False
"""
# Translators: This label appears above a field on the registration form
# which allows the user to input the First Name
last_name_label = _(u"Last Name")
form_desc.add_field(
"last_name",
label=last_name_label,
required=required
)
def _add_country_field(self, form_desc, required=True):
"""Add a country field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This label appears above a dropdown menu on the registration
# form used to select the country in which the user lives.
country_label = _(u"Country or Region of Residence")
country_instructions = _(
# Translators: These instructions appear on the registration form, immediately
# below a field meant to hold the user's country.
u"The country or region where you live."
)
error_msg = accounts.REQUIRED_FIELD_COUNTRY_MSG
# If we set a country code, make sure it's uppercase for the sake of the form.
default_country = form_desc._field_overrides.get('country', {}).get('defaultValue')
if default_country:
form_desc.override_field_properties(
'country',
default=default_country.upper()
)
form_desc.add_field(
"country",
label=country_label,
instructions=country_instructions,
field_type="select",
options=list(countries),
include_default_option=True,
required=required,
error_messages={
"required": error_msg
}
)
def _add_honor_code_field(self, form_desc, required=True):
"""Add an honor code field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Separate terms of service and honor code checkboxes
if self._is_field_visible("terms_of_service"):
terms_label = _(u"Honor Code")
terms_link = marketing_link("HONOR")
terms_text = _(u"Review the Honor Code")
# Combine terms of service and honor code checkboxes
else:
# Translators: This is a legal document users must agree to
# in order to register a new account.
terms_label = _(u"Terms of Service and Honor Code")
terms_link = marketing_link("HONOR")
terms_text = _(u"Review the Terms of Service and Honor Code")
# Translators: "Terms of Service" is a legal document users must agree to
# in order to register a new account.
label = _(u"I agree to the {platform_name} {terms_of_service}").format(
platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME),
terms_of_service=terms_label
)
# Translators: "Terms of Service" is a legal document users must agree to
# in order to register a new account.
error_msg = _(u"You must agree to the {platform_name} {terms_of_service}").format(
platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME),
terms_of_service=terms_label
)
form_desc.add_field(
"honor_code",
label=label,
field_type="checkbox",
default=False,
required=required,
error_messages={
"required": error_msg
},
supplementalLink=terms_link,
supplementalText=terms_text
)
def _add_terms_of_service_field(self, form_desc, required=True):
"""Add a terms of service field to a form description.
Arguments:
form_desc: A form description
Keyword Arguments:
required (bool): Whether this field is required; defaults to True
"""
# Translators: This is a legal document users must agree to
# in order to register a new account.
terms_label = _(u"Terms of Service")
terms_link = marketing_link("TOS")
terms_text = _(u"Review the Terms of Service")
# Translators: "Terms of service" is a legal document users must agree to
# in order to register a new account.
label = _(u"I agree to the {platform_name} {terms_of_service}").format(
platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME),
terms_of_service=terms_label
)
# Translators: "Terms of service" is a legal document users must agree to
# in order to register a new account.
error_msg = _(u"You must agree to the {platform_name} {terms_of_service}").format(
platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME),
terms_of_service=terms_label
)
form_desc.add_field(
"terms_of_service",
label=label,
field_type="checkbox",
default=False,
required=required,
error_messages={
"required": error_msg
},
supplementalLink=terms_link,
supplementalText=terms_text
)
def _apply_third_party_auth_overrides(self, request, form_desc):
"""Modify the registration form if the user has authenticated with a third-party provider.
If a user has successfully authenticated with a third-party provider,
but does not yet have an account with EdX, we want to fill in
the registration form with any info that we get from the
provider.
This will also hide the password field, since we assign users a default
(random) password on the assumption that they will be using
third-party auth to log in.
Arguments:
request (HttpRequest): The request for the registration form, used
to determine if the user has successfully authenticated
with a third-party provider.
form_desc (FormDescription): The registration form description
"""
if third_party_auth.is_enabled():
running_pipeline = third_party_auth.pipeline.get(request)
if running_pipeline:
current_provider = third_party_auth.provider.Registry.get_from_pipeline(running_pipeline)
if current_provider:
# Override username / email / full name
field_overrides = current_provider.get_register_form_data(
running_pipeline.get('kwargs')
)
# When the TPA Provider is configured to skip the registration form and we are in an
# enterprise context, we need to hide all fields except for terms of service and
# ensure that the user explicitly checks that field.
hide_registration_fields_except_tos = (current_provider.skip_registration_form and
enterprise_customer_for_request(request))
for field_name in self.DEFAULT_FIELDS + self.EXTRA_FIELDS:
if field_name in field_overrides:
form_desc.override_field_properties(
field_name, default=field_overrides[field_name]
)
if (field_name not in ['terms_of_service', 'honor_code']
and field_overrides[field_name]
and hide_registration_fields_except_tos):
form_desc.override_field_properties(
field_name,
field_type="hidden",
label="",
instructions="",
)
# Hide the password field
form_desc.override_field_properties(
"password",
default="",
field_type="hidden",
required=False,
label="",
instructions="",
restrictions={}
)
# used to identify that request is running third party social auth
form_desc.add_field(
"social_auth_provider",
field_type="hidden",
label="",
default=current_provider.name if current_provider.name else "Third Party",
required=False,
)
| angelapper/edx-platform | openedx/core/djangoapps/user_api/api.py | Python | agpl-3.0 | 35,762 | 0.002489 |
#!/usr/bin/env python
""" This is a hacked version of PyUnit that extends its reporting capabilities
with optional meta data on the test cases. It also makes it possible to
separate the standard and error output streams in TextTestRunner.
It's a hack rather than a set of subclasses because a) Steve had used double
underscore private attributes for some things I needed access to, and b) the
changes affected so many classes that it was easier just to hack it.
The changes are in the following places:
TestCase:
- minor refactoring of __init__ and __call__ internals
- added some attributes and methods for storing and retrieving meta data
_TextTestResult
- refactored the stream handling
- incorporated all the output code from TextTestRunner
- made the output of FAIL and ERROR information more flexible and
incorporated the new meta data from TestCase
- added a flag called 'explain' to __init__ that controls whether the new '
explanation' meta data from TestCase is printed along with tracebacks
TextTestRunner
- delegated all output to _TextTestResult
- added 'err' and 'explain' to the __init__ signature to match the changes
in _TextTestResult
TestProgram
- added -e and --explain as flags on the command line
-- Tavis Rudd <tavis@redonions.net> (Sept 28th, 2001)
- _TestTextResult.printErrorList(): print blank line after each traceback
-- Mike Orr <mso@oz.net> (Nov 11, 2002)
TestCase methods copied from unittest in Python 2.3:
- .assertAlmostEqual(first, second, places=7, msg=None): to N decimal places.
- .failIfAlmostEqual(first, second, places=7, msg=None)
-- Mike Orr (Jan 5, 2004)
Below is the original docstring for unittest.
---------------------------------------------------------------------------
Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
Smalltalk testing framework.
This module contains the core framework classes that form the basis of
specific test cases and suites (TestCase, TestSuite etc.), and also a
text-based utility class for running the tests and reporting the results
(TextTestRunner).
Simple usage:
import unittest
class IntegerArithmenticTestCase(unittest.TestCase):
def testAdd(self): ## test method names begin 'test*'
self.assertEquals((1 + 2), 3)
self.assertEquals(0 + 1, 1)
def testMultiply(self);
self.assertEquals((0 * 10), 0)
self.assertEquals((5 * 8), 40)
if __name__ == '__main__':
unittest.main()
Further information is available in the bundled documentation, and from
http://pyunit.sourceforge.net/
Copyright (c) 1999, 2000, 2001 Steve Purcell
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.
IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""
__author__ = "Steve Purcell"
__email__ = "stephen_purcell at yahoo dot com"
__revision__ = "$Revision: 1.1 $"[11:-2]
##################################################
## DEPENDENCIES ##
import os
import re
import string
import sys
import time
import traceback
import types
import pprint
##################################################
## CONSTANTS & GLOBALS
try:
True,False
except NameError:
True, False = (1==1),(1==0)
##############################################################################
# Test framework core
##############################################################################
class TestResult:
"""Holder for test result information.
Test results are automatically managed by the TestCase and TestSuite
classes, and do not need to be explicitly manipulated by writers of tests.
Each instance holds the total number of tests run, and collections of
failures and errors that occurred among those test runs. The collections
contain tuples of (testcase, exceptioninfo), where exceptioninfo is a
tuple of values as returned by sys.exc_info().
"""
def __init__(self):
self.failures = []
self.errors = []
self.testsRun = 0
self.shouldStop = 0
def startTest(self, test):
"Called when the given test is about to be run"
self.testsRun = self.testsRun + 1
def stopTest(self, test):
"Called when the given test has been run"
pass
def addError(self, test, err):
"Called when an error has occurred"
self.errors.append((test, err))
def addFailure(self, test, err):
"Called when a failure has occurred"
self.failures.append((test, err))
def addSuccess(self, test):
"Called when a test has completed successfully"
pass
def wasSuccessful(self):
"Tells whether or not this result was a success"
return len(self.failures) == len(self.errors) == 0
def stop(self):
"Indicates that the tests should be aborted"
self.shouldStop = 1
def __repr__(self):
return "<%s run=%i errors=%i failures=%i>" % \
(self.__class__, self.testsRun, len(self.errors),
len(self.failures))
class TestCase:
"""A class whose instances are single test cases.
By default, the test code itself should be placed in a method named
'runTest'.
If the fixture may be used for many test cases, create as
many test methods as are needed. When instantiating such a TestCase
subclass, specify in the constructor arguments the name of the test method
that the instance is to execute.
Test authors should subclass TestCase for their own tests. Construction
and deconstruction of the test's environment ('fixture') can be
implemented by overriding the 'setUp' and 'tearDown' methods respectively.
If it is necessary to override the __init__ method, the base class
__init__ method must always be called. It is important that subclasses
should not change the signature of their __init__ method, since instances
of the classes are instantiated automatically by parts of the framework
in order to be run.
"""
# This attribute determines which exception will be raised when
# the instance's assertion methods fail; test methods raising this
# exception will be deemed to have 'failed' rather than 'errored'
failureException = AssertionError
# the name of the fixture. Used for displaying meta data about the test
name = None
def __init__(self, methodName='runTest'):
"""Create an instance of the class that will use the named test
method when executed. Raises a ValueError if the instance does
not have a method with the specified name.
"""
self._testMethodName = methodName
self._setupTestMethod()
self._setupMetaData()
def _setupTestMethod(self):
try:
self._testMethod = getattr(self, self._testMethodName)
except AttributeError:
raise ValueError, "no such test method in %s: %s" % \
(self.__class__, self._testMethodName)
## meta data methods
def _setupMetaData(self):
"""Setup the default meta data for the test case:
- id: self.__class__.__name__ + testMethodName OR self.name + testMethodName
- description: 1st line of Class docstring + 1st line of method docstring
- explanation: rest of Class docstring + rest of method docstring
"""
testDoc = self._testMethod.__doc__ or '\n'
testDocLines = testDoc.splitlines()
testDescription = testDocLines[0].strip()
if len(testDocLines) > 1:
testExplanation = '\n'.join(
[ln.strip() for ln in testDocLines[1:]]
).strip()
else:
testExplanation = ''
fixtureDoc = self.__doc__ or '\n'
fixtureDocLines = fixtureDoc.splitlines()
fixtureDescription = fixtureDocLines[0].strip()
if len(fixtureDocLines) > 1:
fixtureExplanation = '\n'.join(
[ln.strip() for ln in fixtureDocLines[1:]]
).strip()
else:
fixtureExplanation = ''
if not self.name:
self.name = self.__class__
self._id = "%s.%s" % (self.name, self._testMethodName)
if not fixtureDescription:
self._description = testDescription
else:
self._description = fixtureDescription + ', ' + testDescription
if not fixtureExplanation:
self._explanation = testExplanation
else:
self._explanation = ['Fixture Explanation:',
'--------------------',
fixtureExplanation,
'',
'Test Explanation:',
'-----------------',
testExplanation
]
self._explanation = '\n'.join(self._explanation)
def id(self):
return self._id
def setId(self, id):
self._id = id
def describe(self):
"""Returns a one-line description of the test, or None if no
description has been provided.
The default implementation of this method returns the first line of
the specified test method's docstring.
"""
return self._description
shortDescription = describe
def setDescription(self, descr):
self._description = descr
def explain(self):
return self._explanation
def setExplanation(self, expln):
self._explanation = expln
## core methods
def setUp(self):
"Hook method for setting up the test fixture before exercising it."
pass
def run(self, result=None):
return self(result)
def tearDown(self):
"Hook method for deconstructing the test fixture after testing it."
pass
def debug(self):
"""Run the test without collecting errors in a TestResult"""
self.setUp()
self._testMethod()
self.tearDown()
## internal methods
def defaultTestResult(self):
return TestResult()
def __call__(self, result=None):
if result is None:
result = self.defaultTestResult()
result.startTest(self)
try:
try:
self.setUp()
except:
result.addError(self, self.__exc_info())
return
ok = 0
try:
self._testMethod()
ok = 1
except self.failureException, e:
result.addFailure(self, self.__exc_info())
except:
result.addError(self, self.__exc_info())
try:
self.tearDown()
except:
result.addError(self, self.__exc_info())
ok = 0
if ok:
result.addSuccess(self)
finally:
result.stopTest(self)
return result
def countTestCases(self):
return 1
def __str__(self):
return "%s (%s)" % (self._testMethodName, self.__class__)
def __repr__(self):
return "<%s testMethod=%s>" % \
(self.__class__, self._testMethodName)
def __exc_info(self):
"""Return a version of sys.exc_info() with the traceback frame
minimised; usually the top level of the traceback frame is not
needed.
"""
exctype, excvalue, tb = sys.exc_info()
if sys.platform[:4] == 'java': ## tracebacks look different in Jython
return (exctype, excvalue, tb)
newtb = tb.tb_next
if newtb is None:
return (exctype, excvalue, tb)
return (exctype, excvalue, newtb)
## methods for use by the test cases
def fail(self, msg=None):
"""Fail immediately, with the given message."""
raise self.failureException, msg
def failIf(self, expr, msg=None):
"Fail the test if the expression is true."
if expr: raise self.failureException, msg
def failUnless(self, expr, msg=None):
"""Fail the test unless the expression is true."""
if not expr: raise self.failureException, msg
def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
"""Fail unless an exception of class excClass is thrown
by callableObj when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
"""
try:
apply(callableObj, args, kwargs)
except excClass:
return
else:
if hasattr(excClass,'__name__'): excName = excClass.__name__
else: excName = str(excClass)
raise self.failureException, excName
def failUnlessEqual(self, first, second, msg=None):
"""Fail if the two objects are unequal as determined by the '!='
operator.
"""
if first != second:
raise self.failureException, (msg or '%s != %s' % (first, second))
def failIfEqual(self, first, second, msg=None):
"""Fail if the two objects are equal as determined by the '=='
operator.
"""
if first == second:
raise self.failureException, (msg or '%s == %s' % (first, second))
def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
"""Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero.
Note that decimal places (from zero) is usually not the same
as significant digits (measured from the most signficant digit).
"""
if round(second-first, places) != 0:
raise self.failureException, \
(msg or '%s != %s within %s places' % (`first`, `second`, `places` ))
def failIfAlmostEqual(self, first, second, places=7, msg=None):
"""Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero.
Note that decimal places (from zero) is usually not the same
as significant digits (measured from the most signficant digit).
"""
if round(second-first, places) == 0:
raise self.failureException, \
(msg or '%s == %s within %s places' % (`first`, `second`, `places`))
## aliases
assertEqual = assertEquals = failUnlessEqual
assertNotEqual = assertNotEquals = failIfEqual
assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
assertRaises = failUnlessRaises
assert_ = failUnless
class FunctionTestCase(TestCase):
"""A test case that wraps a test function.
This is useful for slipping pre-existing test functions into the
PyUnit framework. Optionally, set-up and tidy-up functions can be
supplied. As with TestCase, the tidy-up ('tearDown') function will
always be called if the set-up ('setUp') function ran successfully.
"""
def __init__(self, testFunc, setUp=None, tearDown=None,
description=None):
TestCase.__init__(self)
self.__setUpFunc = setUp
self.__tearDownFunc = tearDown
self.__testFunc = testFunc
self.__description = description
def setUp(self):
if self.__setUpFunc is not None:
self.__setUpFunc()
def tearDown(self):
if self.__tearDownFunc is not None:
self.__tearDownFunc()
def runTest(self):
self.__testFunc()
def id(self):
return self.__testFunc.__name__
def __str__(self):
return "%s (%s)" % (self.__class__, self.__testFunc.__name__)
def __repr__(self):
return "<%s testFunc=%s>" % (self.__class__, self.__testFunc)
def describe(self):
if self.__description is not None: return self.__description
doc = self.__testFunc.__doc__
return doc and string.strip(string.split(doc, "\n")[0]) or None
## aliases
shortDescription = describe
class TestSuite:
"""A test suite is a composite test consisting of a number of TestCases.
For use, create an instance of TestSuite, then add test case instances.
When all tests have been added, the suite can be passed to a test
runner, such as TextTestRunner. It will run the individual test cases
in the order in which they were added, aggregating the results. When
subclassing, do not forget to call the base class constructor.
"""
def __init__(self, tests=(), suiteName=None):
self._tests = []
self._testMap = {}
self.suiteName = suiteName
self.addTests(tests)
def __repr__(self):
return "<%s tests=%s>" % (self.__class__, pprint.pformat(self._tests))
__str__ = __repr__
def countTestCases(self):
cases = 0
for test in self._tests:
cases = cases + test.countTestCases()
return cases
def addTest(self, test):
self._tests.append(test)
if isinstance(test, TestSuite) and test.suiteName:
name = test.suiteName
elif isinstance(test, TestCase):
#print test, test._testMethodName
name = test._testMethodName
else:
name = test.__class__.__name__
self._testMap[name] = test
def addTests(self, tests):
for test in tests:
self.addTest(test)
def getTestForName(self, name):
return self._testMap[name]
def run(self, result):
return self(result)
def __call__(self, result):
for test in self._tests:
if result.shouldStop:
break
test(result)
return result
def debug(self):
"""Run the tests without collecting errors in a TestResult"""
for test in self._tests: test.debug()
##############################################################################
# Text UI
##############################################################################
class StreamWrapper:
def __init__(self, out=sys.stdout, err=sys.stderr):
self._streamOut = out
self._streamErr = err
def write(self, txt):
self._streamOut.write(txt)
self._streamOut.flush()
def writeln(self, *lines):
for line in lines:
self.write(line + '\n')
if not lines:
self.write('\n')
def writeErr(self, txt):
self._streamErr.write(txt)
def writelnErr(self, *lines):
for line in lines:
self.writeErr(line + '\n')
if not lines:
self.writeErr('\n')
class _TextTestResult(TestResult, StreamWrapper):
_separatorWidth = 70
_sep1 = '='
_sep2 = '-'
_errorSep1 = '*'
_errorSep2 = '-'
_errorSep3 = ''
def __init__(self,
stream=sys.stdout,
errStream=sys.stderr,
verbosity=1,
explain=False):
TestResult.__init__(self)
StreamWrapper.__init__(self, out=stream, err=errStream)
self._verbosity = verbosity
self._showAll = verbosity > 1
self._dots = (verbosity == 1)
self._explain = explain
## startup and shutdown methods
def beginTests(self):
self._startTime = time.time()
def endTests(self):
self._stopTime = time.time()
self._timeTaken = float(self._stopTime - self._startTime)
def stop(self):
self.shouldStop = 1
## methods called for each test
def startTest(self, test):
TestResult.startTest(self, test)
if self._showAll:
self.write("%s (%s)" %( test.id(), test.describe() ) )
self.write(" ... ")
def addSuccess(self, test):
TestResult.addSuccess(self, test)
if self._showAll:
self.writeln("ok")
elif self._dots:
self.write('.')
def addError(self, test, err):
TestResult.addError(self, test, err)
if self._showAll:
self.writeln("ERROR")
elif self._dots:
self.write('E')
if err[0] is KeyboardInterrupt:
self.stop()
def addFailure(self, test, err):
TestResult.addFailure(self, test, err)
if self._showAll:
self.writeln("FAIL")
elif self._dots:
self.write('F')
## display methods
def summarize(self):
self.printErrors()
self.writeSep2()
run = self.testsRun
self.writeln("Ran %d test%s in %.3fs" %
(run, run == 1 and "" or "s", self._timeTaken))
self.writeln()
if not self.wasSuccessful():
self.writeErr("FAILED (")
failed, errored = map(len, (self.failures, self.errors))
if failed:
self.writeErr("failures=%d" % failed)
if errored:
if failed: self.writeErr(", ")
self.writeErr("errors=%d" % errored)
self.writelnErr(")")
else:
self.writelnErr("OK")
def writeSep1(self):
self.writeln(self._sep1 * self._separatorWidth)
def writeSep2(self):
self.writeln(self._sep2 * self._separatorWidth)
def writeErrSep1(self):
self.writeln(self._errorSep1 * self._separatorWidth)
def writeErrSep2(self):
self.writeln(self._errorSep2 * self._separatorWidth)
def printErrors(self):
if self._dots or self._showAll:
self.writeln()
self.printErrorList('ERROR', self.errors)
self.printErrorList('FAIL', self.failures)
def printErrorList(self, flavour, errors):
for test, err in errors:
self.writeErrSep1()
self.writelnErr("%s %s (%s)" % (flavour, test.id(), test.describe() ))
if self._explain:
expln = test.explain()
if expln:
self.writeErrSep2()
self.writeErr( expln )
self.writelnErr()
self.writeErrSep2()
for line in apply(traceback.format_exception, err):
for l in line.split("\n")[:-1]:
self.writelnErr(l)
self.writelnErr("")
class TextTestRunner:
def __init__(self,
stream=sys.stdout,
errStream=sys.stderr,
verbosity=1,
explain=False):
self._out = stream
self._err = errStream
self._verbosity = verbosity
self._explain = explain
## main methods
def run(self, test):
result = self._makeResult()
result.beginTests()
test( result )
result.endTests()
result.summarize()
return result
## internal methods
def _makeResult(self):
return _TextTestResult(stream=self._out,
errStream=self._err,
verbosity=self._verbosity,
explain=self._explain,
)
##############################################################################
# Locating and loading tests
##############################################################################
class TestLoader:
"""This class is responsible for loading tests according to various
criteria and returning them wrapped in a Test
"""
testMethodPrefix = 'test'
sortTestMethodsUsing = cmp
suiteClass = TestSuite
def loadTestsFromTestCase(self, testCaseClass):
"""Return a suite of all tests cases contained in testCaseClass"""
return self.suiteClass(tests=map(testCaseClass,
self.getTestCaseNames(testCaseClass)),
suiteName=testCaseClass.__name__)
def loadTestsFromModule(self, module):
"""Return a suite of all tests cases contained in the given module"""
tests = []
for name in dir(module):
obj = getattr(module, name)
if type(obj) == types.ClassType and issubclass(obj, TestCase):
tests.append(self.loadTestsFromTestCase(obj))
return self.suiteClass(tests)
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = string.split(name, '.')
if module is None:
if not parts:
raise ValueError, "incomplete test name: %s" % name
else:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__(string.join(parts_copy,'.'))
break
except ImportError:
del parts_copy[-1]
if not parts_copy: raise
parts = parts[1:]
obj = module
for part in parts:
if isinstance(obj, TestSuite):
obj = obj.getTestForName(part)
else:
obj = getattr(obj, part)
if type(obj) == types.ModuleType:
return self.loadTestsFromModule(obj)
elif type(obj) == types.ClassType and issubclass(obj, TestCase):
return self.loadTestsFromTestCase(obj)
elif type(obj) == types.UnboundMethodType:
return obj.im_class(obj.__name__)
elif isinstance(obj, TestSuite):
return obj
elif isinstance(obj, TestCase):
return obj
elif callable(obj):
test = obj()
if not isinstance(test, TestCase) and \
not isinstance(test, TestSuite):
raise ValueError, \
"calling %s returned %s, not a test" %(obj,test)
return test
else:
raise ValueError, "don't know how to make test from: %s" % obj
def loadTestsFromNames(self, names, module=None):
"""Return a suite of all tests cases found using the given sequence
of string specifiers. See 'loadTestsFromName()'.
"""
suites = []
for name in names:
suites.append(self.loadTestsFromName(name, module))
return self.suiteClass(suites)
def getTestCaseNames(self, testCaseClass):
"""Return a sorted sequence of method names found within testCaseClass.
"""
testFnNames = filter(lambda n,p=self.testMethodPrefix: n[:len(p)] == p,
dir(testCaseClass))
for baseclass in testCaseClass.__bases__:
for testFnName in self.getTestCaseNames(baseclass):
if testFnName not in testFnNames: # handle overridden methods
testFnNames.append(testFnName)
if self.sortTestMethodsUsing:
testFnNames.sort(self.sortTestMethodsUsing)
return testFnNames
defaultTestLoader = TestLoader()
##############################################################################
# Patches for old functions: these functions should be considered obsolete
##############################################################################
def _makeLoader(prefix, sortUsing, suiteClass=None):
loader = TestLoader()
loader.sortTestMethodsUsing = sortUsing
loader.testMethodPrefix = prefix
if suiteClass: loader.suiteClass = suiteClass
return loader
def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
##############################################################################
# Facilities for running tests from the command line
##############################################################################
class TestProgram:
"""A command-line program that runs a set of tests; this is primarily
for making test modules conveniently executable.
"""
USAGE = """\
Usage: %(progName)s [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
-e, --expain Output extra test details if there is a failure or error
Examples:
%(progName)s - run default set of tests
%(progName)s MyTestSuite - run suite 'MyTestSuite'
%(progName)s MyTestSuite.MyTestCase - run suite 'MyTestSuite'
%(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
%(progName)s MyTestCase - run all 'test*' test methods
in MyTestCase
"""
def __init__(self, module='__main__', defaultTest=None,
argv=None, testRunner=None, testLoader=defaultTestLoader,
testSuite=None):
if type(module) == type(''):
self.module = __import__(module)
for part in string.split(module,'.')[1:]:
self.module = getattr(self.module, part)
else:
self.module = module
if argv is None:
argv = sys.argv
self.test = testSuite
self.verbosity = 1
self.explain = 0
self.defaultTest = defaultTest
self.testRunner = testRunner
self.testLoader = testLoader
self.progName = os.path.basename(argv[0])
self.parseArgs(argv)
self.runTests()
def usageExit(self, msg=None):
if msg: print msg
print self.USAGE % self.__dict__
sys.exit(2)
def parseArgs(self, argv):
import getopt
try:
options, args = getopt.getopt(argv[1:], 'hHvqer',
['help','verbose','quiet','explain', 'raise'])
for opt, value in options:
if opt in ('-h','-H','--help'):
self.usageExit()
if opt in ('-q','--quiet'):
self.verbosity = 0
if opt in ('-v','--verbose'):
self.verbosity = 2
if opt in ('-e','--explain'):
self.explain = True
if len(args) == 0 and self.defaultTest is None and self.test is None:
self.test = self.testLoader.loadTestsFromModule(self.module)
return
if len(args) > 0:
self.testNames = args
else:
self.testNames = (self.defaultTest,)
self.createTests()
except getopt.error, msg:
self.usageExit(msg)
def createTests(self):
if self.test == None:
self.test = self.testLoader.loadTestsFromNames(self.testNames,
self.module)
def runTests(self):
if self.testRunner is None:
self.testRunner = TextTestRunner(verbosity=self.verbosity,
explain=self.explain)
result = self.testRunner.run(self.test)
self._cleanupAfterRunningTests()
sys.exit(not result.wasSuccessful())
def _cleanupAfterRunningTests(self):
"""A hook method that is called immediately prior to calling
sys.exit(not result.wasSuccessful()) in self.runTests().
"""
pass
main = TestProgram
##############################################################################
# Executing this module from the command line
##############################################################################
if __name__ == "__main__":
main(module=None)
# vim: shiftwidth=4 tabstop=4 expandtab
| skyostil/tracy | src/generator/Cheetah/Tests/unittest_local_copy.py | Python | mit | 34,313 | 0.003934 |
import ssl
import logging
import tornado.ioloop
import tornado.web
import sys
from tornado import httpclient
from functools import partial
from sqlalchemy import create_engine, func
from sqlalchemy.orm import scoped_session, sessionmaker
from create_receive_handler import ReceiveHandler
from wallet_notify_handler import WalletNotifyHandler
from block_notify_handler import BlockNotifyHandler
from authproxy import AuthServiceProxy
class ApiReceiveApplication(tornado.web.Application):
def __init__(self, options, instance_name):
self.options = options
self.instance_name = instance_name
handlers = [
(r"/api/receive", ReceiveHandler),
(r"/api/walletnotify/(?P<txid>[^\/]+)", WalletNotifyHandler),
(r"/api/blocknotify/(?P<hash>[^\/]+)", BlockNotifyHandler),
]
settings = dict(
cookie_secret='cookie_secret'
)
tornado.web.Application.__init__(self, handlers, **settings)
input_log_file_handler = logging.handlers.TimedRotatingFileHandler( self.options.log, when='MIDNIGHT')
formatter = logging.Formatter('%(asctime)s - %(message)s')
input_log_file_handler.setFormatter(formatter)
self.bitcoind = AuthServiceProxy(self.options.rpc_url )
self.paytxfee = self.bitcoind.getinfo()['paytxfee']
self.replay_logger = logging.getLogger(self.instance_name)
self.replay_logger.setLevel(logging.DEBUG)
self.replay_logger.addHandler(input_log_file_handler)
self.replay_logger.info('START')
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
self.replay_logger.addHandler(ch)
from models import Base, db_bootstrap
engine = create_engine( self.options.db_engine, echo=self.options.db_echo)
Base.metadata.create_all(engine)
self.db_session = scoped_session(sessionmaker(bind=engine))
db_bootstrap(self.db_session)
self.log_start_data()
def invoke_callback_url(self, forwarding_address):
url = forwarding_address.get_callback_url()
self.log('EXECUTE', 'curl ' + url)
context = ssl._create_unverified_context()
http_client = httpclient.AsyncHTTPClient(defaults=dict(ssl_options=context))
http_client.fetch(url, partial(self.on_handle_callback_url, forwarding_address.id ))
def on_handle_callback_url(self, forwarding_address_id, response ):
from models import ForwardingAddress
forwarding_address = ForwardingAddress.get_by_id(self.db_session, forwarding_address_id)
if response.error:
self.log('ERROR', str(response.error))
forwarding_address.callback_number_of_errors += 1
self.db_session.add(forwarding_address)
self.db_session.commit()
else:
if response.body == '*ok*':
forwarding_address.is_confirmed_by_client = True
self.db_session.add(forwarding_address)
self.db_session.commit()
def log(self, command, key, value=None):
#if len(logging.getLogger().handlers):
# logging.getLogger().handlers = [] # workaround to avoid stdout logging from the root logger
log_msg = command + ',' + key
if value:
try:
log_msg += ',' + value
except Exception,e :
try:
log_msg += ',' + str(value)
except Exception,e :
try:
log_msg += ',' + unicode(value)
except Exception,e :
log_msg += ', [object]'
self.replay_logger.info( log_msg )
def log_start_data(self):
self.log('PARAM','BEGIN')
self.log('PARAM','port' ,self.options.port)
self.log('PARAM','log' ,self.options.log)
self.log('PARAM','db_echo' ,self.options.db_echo)
self.log('PARAM','db_engine' ,self.options.db_engine)
self.log('PARAM','rpc_url' ,self.options.rpc_url)
self.log('PARAM','END')
from models import ForwardingAddress
fwd_address_list = self.db_session.query(ForwardingAddress)
for fwd_address in fwd_address_list:
self.log('DB_ENTITY', 'FORWARDING_ADDRESS', fwd_address)
bitcoin_info = self.bitcoind.getinfo()
self.log('INFO', 'BITCOIND_GETINFO', str(bitcoin_info))
def clean_up(self):
pass
| bzero/bitex | apps/api_receive/api_receive_application.py | Python | gpl-3.0 | 4,247 | 0.014834 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('fruit', '0002_fruit_cover_image'),
]
operations = [
migrations.AlterField(
model_name='fruit',
name='created',
field=models.DateTimeField(verbose_name='created', db_index=True, editable=False, default=django.utils.timezone.now),
),
migrations.AlterField(
model_name='fruit',
name='deleted',
field=models.BooleanField(verbose_name='deleted', db_index=True, default=False),
),
]
| jsmesami/naovoce | src/fruit/migrations/0003_added_indexes.py | Python | bsd-3-clause | 702 | 0.002849 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2021 Luca Falavigna
#
# Author: Luca Falavigna <dktrkranz@debian.org>
#
# 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; version 3 of the License.
#
# 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 St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# Deb-o-Matic documentation build configuration file
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'Deb-o-Matic'
copyright = '2007-2021, Luca Falavigna'
version = '0.25'
release = '0.25'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
html_use_index = True
htmlhelp_basename = 'Deb-o-Maticdoc'
latex_documents = [
('index', 'Deb-o-Matic.tex', 'Deb-o-Matic Documentation',
'Luca Falavigna', 'manual', 'True')]
latex_elements = {
'classoptions': ',oneside',
'babel': '\\usepackage[english]{babel}'}
man_pages = [
('index', 'deb-o-matic', 'Deb-o-Matic Documentation',
['Luca Falavigna'], 1)]
| debomatic/debomatic | docs/conf.py | Python | gpl-3.0 | 1,509 | 0 |
import pytest
@pytest.fixture(scope="module")
def states(loaders):
return loaders.states
@pytest.fixture(scope="module")
def modules(loaders):
return loaders.modules
| saltstack/salt | tests/pytests/functional/states/conftest.py | Python | apache-2.0 | 178 | 0 |
#!/usr/bin/env python
"""
@package mi.dataset.parser.flord_l_wfp_sio_mule
@file marine-integrations/mi/dataset/parser/flord_l_wfp_sio_mule.py
@author Maria Lutz
@brief Parser for the flord_l_wfp_sio_mule dataset driver
Release notes:
Initial Release
"""
__author__ = 'Maria Lutz'
__license__ = 'Apache 2.0'
import re
import struct
import ntplib
from mi.core.log import get_logger ; log = get_logger()
from mi.core.common import BaseEnum
from mi.core.instrument.data_particle import DataParticle, DataParticleKey
from mi.core.exceptions import SampleException, DatasetParserException, UnexpectedDataException
from mi.dataset.parser.sio_mule_common import SioMuleParser, SIO_HEADER_MATCHER
from mi.dataset.parser.WFP_E_file_common import HEADER_BYTES, STATUS_BYTES, STATUS_BYTES_AUGMENTED, STATUS_START_MATCHER
E_HEADER_REGEX = b'(\x00\x01\x00{5,5}\x01\x00{7,7}\x01)([\x00-\xff]{8,8})' # E header regex for global sites
E_HEADER_MATCHER = re.compile(E_HEADER_REGEX)
E_GLOBAL_SAMPLE_BYTES = 30
class DataParticleType(BaseEnum):
SAMPLE = 'flord_l_wfp_instrument'
class FlordLWfpSioMuleParserDataParticleKey(BaseEnum):
# params collected for the flord_l_wfp_instrument stream
RAW_SIGNAL_CHL = 'raw_signal_chl'
RAW_SIGNAL_BETA = 'raw_signal_beta' # corresponds to 'ntu' from E file
RAW_INTERNAL_TEMP = 'raw_internal_temp'
WFP_TIMESTAMP = 'wfp_timestamp'
class FlordLWfpSioMuleParserDataParticle(DataParticle):
_data_particle_type = DataParticleType.SAMPLE
def _build_parsed_values(self):
"""
Take something in the data format and turn it into
an array of dictionaries defining the data in the particle
with the appropriate tag.
@throws SampleException If there is a problem with sample creation
"""
fields_prof = struct.unpack('>I f f f f f h h h', self.raw_data)
result = [self._encode_value(FlordLWfpSioMuleParserDataParticleKey.RAW_SIGNAL_CHL, fields_prof[6], int),
self._encode_value(FlordLWfpSioMuleParserDataParticleKey.RAW_SIGNAL_BETA, fields_prof[7], int),
self._encode_value(FlordLWfpSioMuleParserDataParticleKey.RAW_INTERNAL_TEMP, fields_prof[8], int),
self._encode_value(FlordLWfpSioMuleParserDataParticleKey.WFP_TIMESTAMP, fields_prof[0], int)]
return result
class FlordLWfpSioMuleParser(SioMuleParser):
def __init__(self,
config,
state,
stream_handle,
state_callback,
publish_callback,
exception_callback,
*args, **kwargs):
super(FlordLWfpSioMuleParser, self).__init__(config,
stream_handle,
state,
self.sieve_function,
state_callback,
publish_callback,
exception_callback,
*args,
**kwargs)
def parse_chunks(self):
"""
Parse out any pending data chunks in the chunker. If
it is a valid data piece, build a particle, update the position and
timestamp. Go until the chunker has no more valid data.
@retval a list of tuples with sample particles encountered in this
parsing, plus the state. An empty list of nothing was parsed.
"""
result_particles = []
(timestamp, chunk) = self._chunker.get_next_data()
while (chunk != None):
# Parse/match the SIO header
sio_header_match = SIO_HEADER_MATCHER.match(chunk)
end_of_header = sio_header_match.end(0)
sample_count = 0
if sio_header_match.group(1) == 'WE':
log.trace('read_state: %s', self._read_state)
# Parse/match the E file header
e_header_match = E_HEADER_MATCHER.search(chunk[end_of_header:end_of_header+HEADER_BYTES])
if e_header_match:
payload = chunk[end_of_header+HEADER_BYTES:-1] # '-1' to remove the '\x03' end-of-record marker
data_split = self.we_split_function(payload)
if data_split:
for ii in range(0,len(data_split)):
e_record = payload[data_split[ii][0]:data_split[ii][1]]
if not STATUS_START_MATCHER.match(e_record[0:STATUS_BYTES]):
fields = struct.unpack('>I', e_record[0:4])
self._timestamp = ntplib.system_to_ntp_time(float(fields[0]))
if len(e_record) == E_GLOBAL_SAMPLE_BYTES:
sample = self._extract_sample(FlordLWfpSioMuleParserDataParticle,
None,
e_record,
self._timestamp)
if sample:
# create particle
result_particles.append(sample)
sample_count += 1
else:
self._exception_callback(UnexpectedDataException("Found unexpected data."))
else: # no e header match
self._exception_callback(UnexpectedDataException("Found unexpected data."))
self._chunk_sample_count.append(sample_count)
(timestamp, chunk) = self._chunker.get_next_data()
return result_particles
def we_split_function(self, raw_data):
"""
Sort through the raw data to identify new blocks of data that need processing.
"""
form_list = []
"""
The Status messages can have an optional 2 bytes on the end, and since the
rest of the data consists of relatively unformated packed binary records,
detecting the presence of that optional 2 bytes can be difficult. The only
pattern we have to detect is the STATUS_START field ( 4 bytes FF FF FF F[A-F]).
We peel this appart by parsing backwards, using the end-of-record as an
additional anchor point.
"""
parse_end_point = len(raw_data)
while parse_end_point > 0:
# look for a status message at postulated message header position
header_start = STATUS_BYTES_AUGMENTED
# look for an augmented status
if STATUS_START_MATCHER.match(raw_data[parse_end_point-STATUS_BYTES_AUGMENTED:parse_end_point]):
# A hit for the status message at the augmented offset
# NOTE, we don't need the status messages and only deliver a stream of
# samples to build_parsed_values
parse_end_point = parse_end_point-STATUS_BYTES_AUGMENTED
# check if this is an unaugmented status
elif STATUS_START_MATCHER.match(raw_data[parse_end_point-STATUS_BYTES:parse_end_point]):
# A hit for the status message at the unaugmented offset
# NOTE: same as above
parse_end_point = parse_end_point-STATUS_BYTES
else:
# assume if not a stat that hit above, we have a sample. Mis-parsing will result
# in extra bytes at the end and a sample exception.
form_list.append((parse_end_point-E_GLOBAL_SAMPLE_BYTES, parse_end_point))
parse_end_point = parse_end_point-E_GLOBAL_SAMPLE_BYTES
# if the remaining bytes are less than data sample bytes, all we might have left is a status sample
if parse_end_point != 0 and parse_end_point < STATUS_BYTES and parse_end_point < E_GLOBAL_SAMPLE_BYTES and parse_end_point < STATUS_BYTES_AUGMENTED:
self._exception_callback(UnexpectedDataException("Error sieving WE data, inferred sample/status alignment incorrect"))
return_list = []
return return_list
# Because we parsed this backwards, we need to reverse the list to deliver the data in the correct order
return_list = form_list[::-1]
log.debug("returning we sieve/split list %s", return_list)
return return_list
| ooici/marine-integrations | mi/dataset/parser/flord_l_wfp_sio_mule.py | Python | bsd-2-clause | 8,191 | 0.021121 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.