prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from django.test import TestCase
from django.contrib.auth import authenticate
from userena.backends import UserenaAuthenticationBackend
from userena.utils import get_user_model
User = get_user_model()
class UserenaAuthenticationBackendTests(TestCase):
"""
Test the ``UserenaAuthenticationBackend`` which should return a ``User``
when supplied with a username/email and a correct password.
"""
fixtures = ['users',]
backend = UserenaAuthenticationBackend()
def test_with_username(self):
""" Test the backend when usernames are supplied. """
# Invalid usernames or passwords
invalid_data_dicts = [
# Invalid password
{'identification': 'john',
'password': 'inhalefish'},
# Invalid username
{'identification': 'alice',
'password': 'blowfish'},
]
for invalid_dict in invalid_data_dicts:
result = self.backend.authenticate(identification=invalid_dict['identification'],
password=invalid_dict['password'])
self.failIf(isinstance(result, User))
# Valid username and password
result = self.backend.authenticate(identification='john',
password='blowfish')
self.failUnless(isinstance(result, User))
def test_with_email(self):
""" Test the backend when email address is supplied """
# Invalid e-mail adressses or passwords
invalid_data_dicts = [
# Invalid password
{'identification': 'john@example.com',
'password': 'inhalefish'},
# Invalid e-mail address
{'identification': 'alice@example.com',
'password': 'blowfish'},
]
for invalid_dict in invalid_data_dicts:
result = self.backend.authenticate(identification=invalid_dict['identification'],
password=invalid_dict['password'])
self.failIf(isinstance(result, User))
# Valid e-email address and password
result = self.backend.authenticate(identification='john@example.com',
password='blowfish')
self.failUnless(isinstance(result, User))
de | f test_get_user(self):
""" Test that the user is returned """
user = self.backend.get_user(1)
self.failUnlessEqual(user.username, 'john')
# None should be returned when false id.
user = s | elf.backend.get_user(99)
self.failIf(user)
|
#
# genxmlif, Release 0.9.0
# file: __init__.py
#
# genxmlif package file
#
# history:
# 2005-04-25 rl created
#
# Copyright (c) 2005-2008 by Roland Leuthe. All rights reserved.
#
# --------------------------------------------------------------------
# The generic XML interface is
#
# Copyright (c) 2005-2008 by Roland Leuthe
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR A | NY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# -------------------------------------------- | ------------------------
######################################################################
# PUBLIC DEFINITIONS
######################################################################
# supported XML interfaces
XMLIF_MINIDOM = "XMLIF_MINIDOM"
XMLIF_4DOM = "XMLIF_4DOM"
XMLIF_ELEMENTTREE = "XMLIF_ELEMENTTREE"
# namespace definitions
XINC_NAMESPACE = "http://www.w3.org/2001/XInclude"
# definition of genxmlif path
import os
GENXMLIF_DIR = os.path.dirname(__file__)
########################################
# central function to choose the XML interface to be used
#
def chooseXmlIf (xmlIf, verbose=0, useCaching=1, processXInclude=1):
if xmlIf == XMLIF_MINIDOM:
import xmlifMinidom
return xmlifMinidom.XmlInterfaceMinidom(verbose, useCaching, processXInclude)
elif xmlIf == XMLIF_4DOM:
import xmlif4Dom
return xmlif4Dom.XmlInterface4Dom(verbose, useCaching, processXInclude)
elif xmlIf == XMLIF_ELEMENTTREE:
import xmlifElementTree
return xmlifElementTree.XmlInterfaceElementTree(verbose, useCaching, processXInclude)
else:
raise AttributeError, "Unknown XML interface: %s" %(xmlIf)
########################################
# define own exception for GenXmlIf errors
# The following errors/exceptions are mapped to a GenxmlIf exception:
# - Expat errors
# - XInclude errors
#
class GenXmlIfError (StandardError):
pass
|
ls.command.install_data import install_data
from distutils.command.build import build
from distutils.dep_util import newer
from distutils.log import warn, info, error
from distutils.errors import DistutilsFileError
import glob
import os
import sys
import subprocess
import platform
from terminatorlib.version import APP_NAME, APP_VERSION
PO_DIR = 'po'
MO_DIR = os.path.join('build', 'mo')
CSS_DIR = os.path.join('terminatorlib', 'themes')
class TerminatorDist(Distribution):
global_options = Distribution.global_options + [
("build-documentation", None, "Build the documentation"),
("install-documentation", None, "Install the documentation"),
("without-gettext", None, "Don't build/install gettext .mo files"),
("without-icon-cache", None, "Don't attempt to run gtk-update-icon-cache")]
def __init__ (self, *args):
self.without_gettext = False
self.without_icon_cache = False
Distribution.__init__(self, *args)
class BuildData(build):
def run (self):
build.run (self)
if not self.distribution.without_gettext:
# Build the translations
for po in glob.glob (os.path.join (PO_DIR, '*.po')):
lang = os.path.basename(po[:-3])
mo = os.path.join(MO_DIR, lang, 'LC_MESSAGES', 'terminator.mo')
directory = os.path.dirname(mo)
if not os.path.exists(directory):
info('creating %s' % directory)
os.makedirs(directory)
if newer(po, mo):
info('compiling %s -> %s' % (po, mo))
try:
rc = subprocess.call(['msgfmt', '-o', mo, po])
if rc != 0:
raise Warning, "msgfmt returned %d" % rc
except Exception, e:
error("Building gettext files failed. Ensure you have gettext installed. Alternatively, try setup.py --without-gettext [build|install]")
error("Error: %s" % str(e))
sys.exit(1)
TOP_BUILDDIR='.'
INTLTOOL_MERGE='intltool-merge'
desktop_in='data/terminator.desktop.in'
desktop_data='data/terminator.desktop'
rc = os.system ("C_ALL=C " + INTLTOOL_MERGE + " -d -u -c " + TOP_BUILDDIR +
"/po/.intltool-merge-cache " + TOP_BUILDDIR + "/po " +
desktop_in + " " + desktop_data)
if rc != 0:
# run the desktop_in through a command to strip the "_" characters
with open(desktop_in) as file_in, open(desktop_data, 'w') as file_data:
[file_data.write(line.lstrip('_')) for line in file_in]
appdata_in='data/terminator.appdata.xml.in'
appdata_data='data/terminator.appdata.xml'
rc = os.system ("C_ALL=C " + INTLTOOL_MERGE + " -x -u -c " + TOP_BUILDDIR +
"/po/.intltool-merge-cache " + TOP_BUILDDIR + "/po " +
appdata_in + " " + appdata_data)
if rc != 0:
# run the appdata_in through a command to strip the "_" characters
with open(appdata_in) as file_in, open(appdata_data, 'w') as file_data:
[file_data.write(line.replace('<_','<').replace('</_','</')) for line in file_in]
class Uninstall(Command):
description = "Attempt an uninstall from an install --record file"
user_options = [('manifest=', None, 'Installation record filename')]
def initialize_options(self):
self.manifest = None
def finalize_options(self):
pass
def get_command_name(self):
return 'uninstall'
def run(self):
f = None
self.ensure_filename('manifest')
try:
try:
if not self.manifest:
raise DistutilsFileError("Pass manifest with --manifest=file")
f = open(self.manifest)
files = [file.strip() for file in f]
except IOError, e:
raise DistutilsFileError("unable to open install manifest: %s", str(e))
finally:
if f:
f.close()
for file in files:
if os.path.isfile(file) or os.path.islink(file):
info("removing %s" % repr(file))
if not self.dry_run:
try:
os.unlink(file)
except OSError, e:
warn("could not delete: %s" % repr(file))
elif not os.path.isdir(file):
info("skipping %s" % repr(file))
dirs = set()
for file in reversed(sorted(files)):
dir = os.path.dirname(file)
if dir not in dirs and os.path.isdir(dir) and len(os.listdir(dir)) == 0:
dirs.add(dir)
# Only nuke empty Python library directories, else we could destroy
# e.g. locale directories we're the only app with a .mo installed for.
if dir.find("site-packages/") > 0:
info("removing %s" % repr(dir))
if not self.dry_run:
try:
os.rmdir(dir)
except OSError, e:
warn("could not remove directory: %s" % str(e))
else:
info("skipping empty directory %s" % repr(dir))
class InstallData(install_data):
def run (self):
self.data_files.extend (self._find_css_files ())
self.data_files.extend (self._find_mo_files ())
install_data.run (self)
if not self.distribution.without_icon_cache:
self._update_icon_cache ()
# We should do this on uninstall too
def _update_icon_cache(self):
info("running gtk-update-icon-cache")
try:
subprocess.call(["gtk-update-icon-cache", "-q", "-f", "-t", os.path.join(self.install_dir, "share/icons/hicolor")])
except Exception, e:
warn("updating the GTK icon cache failed: %s" % str(e))
def _find_mo_files (self):
data_files = []
if not self.distribution.without_gettext:
for mo in glob.glob (os.path.join (MO_DIR, '*', 'LC_MESSAGES', 'terminator.mo')):
lang = os.path.basename(os.path.dirname(os.path.dirname(mo)))
dest = os.path.join('share', 'locale', lang, 'LC_MESSAGES')
data_files.append((dest, [mo]))
return data_files
def _find_css_files (self):
data_files = []
for css_dir in glob.glob (os.path.join (CSS_DIR, '*')):
srce = glob.glob (os.path.join(css_dir, 'gtk-3.0', 'apps', '*.css'))
dest = os.path.join('share', 'terminator', css_dir, 'gtk-3.0', 'apps')
data_files.append((dest, srce))
return data_files
class Test(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
impor | t subprocess
import sys
errno = subprocess.call(['bash', 'run_tests'])
raise SystemExit(errno)
if platform.system() in ['FreeBSD', 'OpenBSD']:
man_dir = 'man'
else:
man_dir = 's | hare/man'
setup(name=APP_NAME,
version=APP_VERSION,
description='Terminator, the robot future of terminals',
author='Chris Jones',
author_email='cmsj@tenshu.net',
url='https://gnometerminator.blogspot.com/p/introduction.html',
license='GNU GPL v2',
scripts=['terminator', 'remotinator'],
data_files=[
('bin', ['terminator.wrapper']),
('share/appdata', ['data/terminator.appdata.xml']),
('share/applications', ['data/terminator.desktop']),
(os.path.join(man_dir, 'man1'), ['doc/terminator.1']),
(os.path.join(man_dir, 'man5'), ['doc/terminator_config.5']),
('share/pixmaps', ['data/icons/hicolor/48x48/apps/terminator.png']),
('share/icons/hicolor/scalable/apps', glob.glob('data/icons/hicolor/scalable/apps/*.svg')),
('share/icons/hicolor/16x16/apps', glob.glob('data/icons/hicolor/16x16/apps/*.png')),
('share/icons/hicolor/22x22/apps', glob.glob('data/icons/hicolor/22x22/apps/*.png')),
('share/icons/hicolor/24x24/apps', glob.glob('data/icons/hicolor/24x24/apps/*.png')),
('share/icons/hicolor/32x32/apps', glob.glob('data/icons/hicolor/32x32/apps/*.png')),
('share/icons/hicolor/48x48/apps', glob.glob('data/icons/hicolor/48x48/apps/*.png')),
('share/icons/hicolor/16x16/actions', glob.glob('data/icons/hicolor/16x16/actions/*.png')),
('share/icons/hicolor/16x16/status', glob.glob('data/icons/hicolor/16x16/status/*.png')),
('share/icons/HighContrast/scalable/apps', glob.glob |
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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 t | he 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.
# ------------------------------------------------------------------
#
# Copied from the bigmuddy collector
#
from google.protobuf.message import Message
from google.protobuf.descriptor import FieldDescriptor
DECODE_FN_MAP = {
FieldDescriptor.TYPE_DOUBLE: float,
FieldDescriptor.TYPE_FLOAT: float,
FieldDescriptor.TYPE_INT32: int,
FieldDescriptor.TYPE_INT64: long,
FieldDescriptor.TYPE_UINT32: int,
FieldDescriptor.TYPE_UINT64: long,
FieldDescriptor.TYPE_SINT32: int,
FieldDescriptor.TYPE_SINT64: long,
FieldDescriptor.TYPE_FIXED32: int,
FieldDescriptor.TYPE_FIXED64: long,
FieldDescriptor.TYPE_SFIXED32: int,
FieldDescriptor.TYPE_SFIXED64: long,
FieldDescriptor.TYPE_BOOL: bool,
FieldDescriptor.TYPE_STRING: unicode,
FieldDescriptor.TYPE_BYTES: lambda b: bytes_to_string(b),
FieldDescriptor.TYPE_ENUM: int,
}
def bytes_to_string (bytes):
"""
Convert a byte array into a string aa:bb:cc
"""
return ":".join(["{:02x}".format(int(ord(c))) for c in bytes])
def field_type_to_fn(msg, field):
if field.type == FieldDescriptor.TYPE_MESSAGE:
# For embedded messages recursively call this function. If it is
# a repeated field return a list
result = lambda msg: proto_to_dict(msg)
elif field.type in DECODE_FN_MAP:
result = DECODE_FN_MAP[field.type]
else:
raise TypeError("Field %s.%s has unrecognised type id %d" % (
msg.__class__.__name__, field.name, field.type))
return result
def proto_to_dict(msg):
result_dict = {}
extensions = {}
for field, value in msg.ListFields():
conversion_fn = field_type_to_fn(msg, field)
# Skip extensions
if not field.is_extension:
# Repeated fields result in an array, otherwise just call the
# conversion function to store the value
if field.label == FieldDescriptor.LABEL_REPEATED:
result_dict[field.name] = [conversion_fn(v) for v in value]
else:
result_dict[field.name] = conversion_fn(value)
return result_dict
|
import subprocess
import math
def launch(script_name, num_partitions, num_machines, pos, coordinator, machine_name, debug=False):
if num_machines > num_partitions:
raise RuntimeError("Need mor | e partitions than machine")
machine_size = int(math.ceil(float(num_partitions) / float(num_machines)))
start = pos * machine_size
end = min((pos+1)*machine_size, num_partitions)
processes = []
#launch content server processes
for i in range(start, end):
print("Starting processs #" + str(i))
if debug:
p = subprocess.Popen(["python3-dbg", script_name, coordinator, machine_name, str(i)])
else:
p = subprocess.Popen([script_na | me, coordinator, machine_name, str(i)])
processes.append(p)
while processes:
p = processes.pop()
p.wait()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# frc_rekt documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 12 00:19:47 2017.
#
# 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.
# 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.
#
import os
import sys
sys.path.insert(0, o | s.path.abspath(os.path.join(os.path.dirname(__file__), os.pa | th.pardir)))
# -- 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.todo',
'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'frc_rekt'
copyright = '2017, Author'
author = '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 = ''
# The full version, including alpha/beta/rc tags.
release = ''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- 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 = 'alabaster'
# 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 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']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'frc_rektdoc'
# -- 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': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# 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 = [
(master_doc, 'frc_rekt.tex', 'frc\\_rekt Documentation',
'Author', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'frc_rekt', 'frc_rekt Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'frc_rekt', 'frc_rekt Documentation',
author, 'frc_rekt', 'One line description of project.',
'Miscellaneous'),
]
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
|
: disable
def test_conversion_from_keras_v2(self):
x = [-1, 0, 1, 2, 3, 4]
y = [-3, -1, 1, 3, 5, 7]
model = tf.keras.models.Sequential(
[tf.keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x, y, epochs=1)
converter = lite.TFLiteConverterV2.from_keras_model(model)
mock_metrics = mock.create_autospec(
metrics.TFLiteConverterMetrics, instance=True)
converter._tflite_metrics = mock_metrics
converter.convert()
mock_metrics.assert_has_calls([
mock.call.increase_counter_converter_attempt(),
mock.call.increase_counter_converter_success(),
mock.call.export_metrics(),
mock.call.set_converter_param('inference_type', 'tf.float32'),
mock.call.set_converter_param('target_ops', 'TFLITE_BUILTINS'),
mock.call.set_converter_param('optimization_default', 'False'),
], any_order=True) # pyformat: disable
def _createV1SavedModel(self, shape):
"""Create a simple SavedModel."""
saved_model_dir = os.path.join(self.get_temp_dir(), 'simple_savedmodel')
with tf.Graph().as_default():
with tf.compat.v1.Session() as sess:
in_tensor_1 = tf.compat.v1.placeholder(
shape=shape, dtype=tf.float32, name='inputB')
in_tensor_2 = tf.compat.v1.placeholder(
shape=shape, dtype=tf.float32, name='inputA')
variable_node = tf.Variable(1.0, name='variable_node')
out_tensor = in_tensor_1 + in_tensor_2 * variable_node
inputs = {'x': in_tensor_1, 'y': in_tensor_2}
outputs = {'z': out_tensor}
sess.run(tf.compat.v1.variables_initializer([variable_node]))
saved_model.simple_save(sess, saved_model_dir, inputs, outputs)
return saved_model_dir
def test_conversion_from_saved_model(self):
saved_model_dir = self._createV1SavedModel(shape=[1, 16, 16, 3])
converter = lite.TFLiteSavedModelConverter(saved_model_dir, set(['serve']),
['serving_default'])
converter.experimental_new_converter = True
mock_metrics = mock.create_autospec(
metrics.TFLiteConverterMetrics, instance=True)
converter._tflite_metrics = mock_metrics
time.process_time = mock.Mock(side_effect=np.arange(1, 1000, 2).tolist())
converter.convert()
mock_metrics.assert_has_calls([
mock.call.increase_counter_converter_attempt(),
mock.call.increase_counter_converter_success(),
mock.call.set_converter_latency(2000),
mock.call.export_metrics(),
mock.call.set_converter_param('enable_mlir_converter', 'True'),
], any_order=True) # pyformat: disable
def test_conversion_from_saved_model_v2(self):
saved_model_dir = self._createV1SavedModel(shape=[1, 16, 16, 3])
converter = lite.TFLiteConverterV2.from_saved_model(saved_model_dir)
converter.experimental_new_converter = False
mock_metrics = mock.create_autospec(
metrics.TFLiteConverterMetrics, instance=True)
converter._tflite_metrics = mock_metrics
converter.convert()
mock_metrics.assert_has_calls([
mock.call.increase_counter_converter_attempt(),
mock.call.increase_counter_converter_success(),
mock.call.export_metrics(),
mock.call.set_converter_param('enable_mlir_converter', 'False'),
mock.call.set_converter_param('api_version', '2'),
], any_order=True) # pyformat: disable
def disable_converter_counter_metrics(self, tflite_metrics):
def empty_func():
pass
tflite_metrics.increase_counter_converter_attempt = empty_func
tflite_metrics.increase_counter_converter_success = empty_func
def test_export_at_conversion_done(self):
saved_model_dir = self._createV1SavedModel(shape=[1, 16, 16, 3])
converter = lite.TFLiteConverterV2.from_saved_model(saved_model_dir)
tflite_metrics = converter._tflite_metrics
mock_exporter = mock.MagicMock()
tflite_metrics._metrics_exporter = mock_exporter
self.disable_converter_counter_metrics(tflite_metrics)
mock_exporter.ExportMetrics.assert_not_called()
converter.convert()
mock_exporter.ExportMetrics.assert_called_once()
tflite_metrics.__del__()
mock_exporter.ExportMetrics.assert_called_once()
def test_export_at_exit(self):
saved_model_dir = self._createV1SavedModel(shape=[1, 16, 16, 3])
converter = lite.TFLiteConverterV2.from_saved_model(saved_model_dir)
tflite_metrics = converter._tflite_metrics
mock_exporter = mock.MagicMock()
tflite_metrics._metrics_exporter = mock_exporter
self.disable_converter_counter_metrics(tflite_metrics)
mock_exporter.ExportMetrics.assert_not_called()
tflite_metrics.__del__()
mock_exporter.ExportMetrics.assert_called_once()
def mock_ngrams(data, width, axis=-1, string_separator=' ', name=None):
"""This mock Ngrams lack the width attr, causing conversion to fail."""
experimental_implements = [
'name: "tftext:Ngrams"',
'attr { key: "axis" value { i: %d } }' % axis,
'attr { key: "reduction_type" value { s: "STRING_JOIN" } }',
'attr { key: "string_separator" value { s: "%s" } }' % string_separator,
]
experimental_implements = ' '.join(experimental_implements)
@tf.function(experimental_implements=experimental_implements)
def func(data):
with ops.name_scope(name, 'NGrams', [data, width]):
data = ragged_tensor.convert_to_tensor_or_ragged_tensor(data, name='data')
slices = []
for start in range(width):
stop = None if start - width + 1 == 0 else start - width + 1
if axis >= 0:
idx = [slice(None)] * axis + [slice(start, stop)]
else:
idx = [Ellipsis, slice(start, stop)] + [slice(None)] * (-axis - 1)
slices.append(data[idx])
# Stack the slices.
stack_axis = axis + 1 if axis >= 0 else axis
windowed_data = array_ops.stack(slices, stack_axis)
return string_ops.reduce_join(
windowed_data, axis=axis, separator=string_separator)
return func(data)
class ConverterErrorMetricTest(test_util.TensorFlowTestCase,
parameterized.TestCase):
"""Testing conversion error metric."""
def setUp(self):
super(ConverterErrorMetricTest, self).setUp()
# Mock metrics instance except errors so other test cases are not affected.
mock_attempt = mock.create_autospec(monitoring.Counter, instance=True)
self._counter_conversion_attempt = metrics._counter_conversion_attempt
metrics._counter_conversion_attempt = mock_attempt
mock_success = mock.create_autospec(monitoring.Counter, instance=True)
self._counter_conversion_success = metrics._counter_conversion_success
metrics._counter_conversion_success = mock_success
mock_params = mock.create_autospec(monitoring.StringGauge, instance=True)
self._gauge_conversion_params = metrics._gauge_conversion_params
metrics._gauge_conversion_params = mock_params
def tearDown(self):
super(ConverterErrorMetricTest, self).tearDown()
# # Restore metrics instances.
metrics._counter_conversion_attempt = self._counter_conversion_attempt
metrics._counter_conversion_success = self._counter_conversion_success
metrics._gauge_conversion_params = self._gauge_conversion_params
def conve | rt_and_check_location_info(self,
converter,
expected_type,
expected_sources=None):
# The custom attribute of ConverterError can't be accessed with
# assertRaises so use try-catch block instead.
try:
tflite_model = converter.convert()
self.asser | tIsNone(tflite_model)
except ConverterError as converter_error:
# pylint: disable=g-assert-in-except
self.assertLen(converter_error.errors, 1)
location = converter_error.errors[0].location
self.assertEqual(location.type, expected_type)
if expected_sources:
debug_string = str(location)
for source in expected_sources:
self.assertIn(source, debug_string)
# pylint: enable=g-assert-in |
# Copyright 2015-2017 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language gove | rning permissions and limitations
# under the License.
from .linkstate import LinkState # noqa
from .node.local_router_id import LocalRouterID # noqa
from .node.name import NodeName # noqa
from .node.isisarea import ISISArea # noqa
from .node.sr_capabilities import SRCapabilities # noqa
from .node.sr_algorithm import SRAlgorithm # noqa
from .node.node_ | msd import NodeMSD # noqa
from .node.nodeflags import NodeFlags # noqa
from .node.opa_node_attr import OpaNodeAttr # noqa
from .node.sid_or_label import SIDorLabel # noqa
from .node.srlb import SRLB # noqa
from .link.admingroup import AdminGroup # noqa
from .link.remote_router_id import RemoteRouterID # noqa
from .link.max_bw import MaxBandwidth # noqa
from .link.max_rsv_bw import MaxResvBandwidth # noqa
from .link.unsrv_bw import UnrsvBandwidth # noqa
from .link.te_metric import TeMetric # noqa
from .link.link_name import LinkName # noqa
from .link.igp_metric import IGPMetric # noqa
from .link.adj_seg_id import AdjSegID # noqa
from .link.link_identifiers import LinkIdentifiers # noqa
from .link.link_msd import LinkMSD # noqa
from .link.lan_adj_sid import LanAdjSegID # noqa
from .link.srlg import SRLGList # noqa
from .link.mplsmask import MplsMask # noqa
from .link.protection_type import ProtectionType # noqa
from .link.opa_link_attr import OpaLinkAttr # noqa
from .link.peer_node_sid import PeerNodeSID # noqa
from .link.peer_adj_sid import PeerAdjSID # noqa
from .link.peer_set_sid import PeerSetSID # noqa
from .link.unidirect_link_delay import UnidirectLinkDelay # noqa
from .link.min_max_link_delay import MinMaxUnidirectLinkDelay # noqa
from .link.unidirect_delay_var import UnidirectDelayVar # noqa
from .link.unidirect_packet_loss import UnidirectPacketLoss # noqa
from .link.unidirect_residual_bw import UnidirectResidualBw # noqa
from .link.unidirect_avail_bw import UnidirectAvailBw # noqa
from .link.unidirect_bw_util import UnidirectBwUtil # noqa
from .prefix.prefix_metric import PrefixMetric # noqa
from .prefix.prefix_sid import PrefixSID # noqa
from .prefix.prefix_igp_attr import PrefixIGPAttr # noqa
from .prefix.src_router_id import SrcRouterID # noqa
from .prefix.igpflags import IGPFlags # noqa
from .prefix.igp_route_tag_list import IGPRouteTagList # noqa
from .prefix.ext_igp_route_tag_list import ExtIGPRouteTagList # noqa
from .prefix.ospf_forward_addr import OspfForwardingAddr # noqa
|
n the prefix header is
instead compiled, and all other compilations in the project get an
additional |-include path_to_compiled_header| instead.
+ Compiled prefix headers have the extension gch. There is one gch file for
every language used in the project (c, cc, m, mm), since gch files for
different languages aren't compatible.
+ gch files themselves are built with the target's normal cflags, but they
obviously don't get the |-include| flag. Instead, they need a -x flag that
describes their language.
+ All o files in the target need to depend on the gch file, to make sure
it's built before any o file is built.
This class helps with some of these tasks, but it needs help from the build
system for writing dependencies to the gch files, for writing build commands
for the gch files, and for figuring out the location of the gch files.
"""
def __init__(self, xcode_settings,
gyp_path_to_build_path, gyp_path_to_build_output):
"""If xcode_settings is None, all methods on this class are no-ops.
Args:
gyp_path_to_build_path: A function that takes a gyp-relative path,
and returns a path relative to the build directory.
gyp_path_to_build_output: A function that takes a gyp-relative path and
a language code ('c', 'cc', 'm', or 'mm'), and that returns a path
to where the output of precompiling that path for that language
should be placed (without the trailing '.gch').
"""
# This doesn't support per-configuration prefix headers. Good enough
# for now.
self.header = None
self.compile_headers = False
if xcode_settings:
self.header = xcode_settings.GetPerTargetSetting('GCC_PREFIX_HEADER')
self.compile_headers = xcode_settings.GetPerTargetSetting(
'GCC_PRECOMPILE_PREFIX_HEADER', default='NO') != 'NO'
self.compiled_headers = {}
if self.header:
if self.compile_headers:
for lang in ['c', 'cc', 'm', 'mm']:
self.compiled_headers[lang] = gyp_path_to_build_output(
self.header, lang)
self.header = gyp_path_to_build_path(self.header)
def _CompiledHeader(self, lang, arch):
assert self.compile_headers
h = self.compiled_headers[lang]
if arch:
h += '.' + arch
return h
def GetInclude(self, lang, arch=None):
"""Gets the cflags to include the prefix header for language |lang|."""
if self.compile_headers and lang in self.compiled_headers:
return '-include %s' % self._CompiledHeader(lang, arch)
elif self.header:
return '-include %s' % self.header
else:
return ''
def _Gch(self, lang, arch):
"""Returns the actual file name of the prefix header for language |lang|."""
assert self.compile_headers
return self._CompiledHeader(lang, arch) + '.gch'
def GetObjDependencies(self, sources, objs, arch=None):
"""Given a list of source files and the corresponding object files, returns
a list of (source, object, gch) tuples, where |gch| is the build-directory
relative path to the gch file each object file depends on. |compilable[i]|
has to be the source file belonging to |objs[i]|."""
if not self.header or not self.compile_headers:
return []
result = []
for source, obj in zip(sources, objs):
ext = os.path.splitext(source)[1]
lang = {
'.c': 'c',
'.cpp': 'cc', '.cc': 'cc', '.cxx': 'cc',
'.m': 'm',
'.mm': 'mm',
}.get(ext, None)
if lang:
result.append((source, obj, self._Gch(lang, arch)))
return result
def GetPchBuildCommands(self, arch=None):
"""Returns [(path_to_gch, language_flag, language, header)].
|path_to_gch| and |header| are relative to the build directory.
"""
if not self.header or not self.compile_headers:
return []
return [
(self._Gch('c', arch), '-x c-header', 'c', self.header),
(self._Gch('cc', arch), '-x c++-header', 'cc', self.header),
(self._Gch('m', arch), '-x objective-c-header', 'm', self.header),
(self._Gch('mm', arch), '-x objective-c++-header', 'mm', self.header),
]
def MergeGlobalXcodeSettingsToSpec(global_dict, spec):
"""Merges the global xcode_settings dictionary into each configuration of the
target represented by spec. For keys that are both in the global and the local
xcode_settings dict, the local key gets precendence.
"""
# The xcode generator special-cases global xcode_settings and does something
# that amounts to merging in the global xcode_settings into each local
# xcode_settings dict.
global_xcode_settings = global_dict.get('xcode_settings', {})
for config in spec['configurations'].values():
if 'xcode_settings' in config:
new_settings = global_xcode_settings.copy()
new_settings.update(config['xcode_settings'])
config['xcode_settings'] = new_settings
def IsMacBundle(flavor, spec):
"""Returns if |spec| should be treated as a bundle.
Bundles are directories with a certain subdirectory structure, instead of
just a single file. Bundle rules do not produce a binary but also package
resources into that directory."""
is_mac_bundle = (int(spec.get('mac_bundle', 0)) != 0 and flavor == 'mac')
if is_mac_bundle:
assert spec['type'] != 'none', (
'mac_bundle targets cannot have type none (target "%s")' %
spec['target_name'])
return is_mac_bundle
def GetMacBundleResources(product_dir, xcode_settings, resources):
"""Yields (output, resource) pairs for every resource in |resources|.
Only call this for mac bundle targets.
Args:
product_dir: Path to the directory containing the output bundle,
relative to the build directory.
xcode_settings: The XcodeSettings of the current target.
resources: A list of bundle resources, relative to the build directory.
"""
dest = os.path.join(product_dir,
xcode_settings.GetBundleResourceFolder())
for res in resources:
output = dest
# The make generator doesn't support it, so forbid it everywhere
# to keep the generators more interchangable.
assert ' ' not in res, (
"Spaces in resource filenames not supported (%s)" % res)
# Split into (path,file).
res_parts = os.path.split(res)
# Now split the path into (prefix,maybe.lproj).
lproj_parts = os.path.split(res_parts[0])
# If the resource lives in a .lproj bundle, add that to the destination.
if lproj_parts[1].endswith('.lproj'):
output = os.path.join(output, lproj_parts[1])
output = os.path.join(output, res_parts[1])
# Compiled XIB files are referred to by .nib.
if output.endswith('.xib'):
output = output[0:-3] + 'nib'
yield output, res
def GetMacInfoPlist(product_dir, xcode_settings, gyp_path_to_build_path):
"""Returns (info_plist, dest_plist, defines, extra_env), where:
* |info_plist| is the source plist path, relative to the
build directory,
* |dest_plist| is the destination plist path, relative to the
build directory,
* |defines| is a list of preprocessor defines | (empty if the plist
shouldn't be preprocessed,
* |extra_env| is a dict of env variables that should be exported when
invoking |mac_tool copy-info-plist|.
Only call thi | s for mac bundle targets.
Args:
product_dir: Path to the directory containing the output bundle,
relative to the build directory.
xcode_settings: The XcodeSettings of the current target.
gyp_to_build_path: A function that converts paths relative to the
current gyp file to paths relative to the build direcotry.
"""
info_plist = xcode_settings.GetPerTargetSetting('INFOPLIST_FILE')
if not info_plist:
return None, None, [], {}
# The make generator doesn't support it, so forbid it everywhere
# to keep the generators more interchangable.
assert ' ' not in info_plist, (
"Spaces in Info.plist filenames not supported (%s)" % info_plist)
info_plist = gyp_path_to_build_path(info_plist)
# If explicitly set to preprocess the plist, invoke the C preprocessor and
# specify any |
import time
from random import random
| import traceback
WARN_TIME = 3600.
def wait(check,timeout=None,delay=0.5, *args,**kwarg):
start_time = time.time()
warned = False
while True:
try:
result = check(*args,**kwarg)
break
except Exception as exc:
if timeo | ut and (time.time()-start_time) > timeout:
raise exc
#if (time.time()-start_time) > WARN_TIME and not warned:
#print "wait(): warning, waiting for a long time - \n%s" % traceback.format_exc()
#warned = True
time.sleep( delay*(1.+0.2*random()) )
return result
#class wait(object):
#def __init__(self,block=True, timeout=None, interval=1.0):
#self.block = block
#self.timeout = timeout
#self.interval = interval
#self._start_time = time.time()
#def __iter__(self):
#return self
#def next(self):
#if self.timeout and (time.time()-self._start_time) > self.timeout:
#raise StopIteration
#time.sleep(self.interval)
#try:
#return True
#except:
#print 'caught'
#for now in wait(timeout=None):
#print 'hello!'
|
': 'public'}),
('last_name',
{'label': _('Last Name'),
'identifier': 'user.last_name',
'visibility': 'public'}),
('organization',
{'label': _('Organization'),
'identifier': 'user.organization',
'visibility': 'public'}),
('make_info_public',
{'label': _('Make Info Visible'),
'identifier': 'user.make_info_public',
'visibility': 'private',
'template': "treemap/field/make_info_public_div.html"}),
('email',
{'label': _('Email'),
'identifier': 'user.email',
'visibility': 'private'}),
('allow_email_contact',
{'label': _('Email Updates'),
'identifier': 'user.allow_email_contact',
'visibility': 'private',
'template': "treemap/field/email_subscription_div.html"})
])
def user_audits(request, username):
user = get_object_or_404(User, username=username)
instance_id = request.GET.get('instance_id', None)
instance = (get_instance_or_404(pk=instance_id)
if instance_id else None)
params = get_audits_params(request)
return get_audits(request.user, instance, request.GET.copy(), user=user,
**params)
def instance_user_audits(request, instance_url_name, username):
instance = get_instance_or_404(url_name=instance_url_name)
return HttpResponseRedirect(
reverse('user_audits', kwargs={'username': username})
+ '?instance_id=%s' % instance.pk)
def update_user(request, user):
new_values = json_from_request(request) or {}
for key in new_values:
try:
model, field = dotted_split(key, 2, cls=ValueError)
if model != 'user':
raise ValidationError(
'All fields should be prefixed with "user."')
if field not in USER_PROFILE_FIELDS:
raise ValidationError(field + ' is not an updatable field')
except ValueError:
raise ValidationError('All fields should be prefixed with "user."')
setattr(user, field, new_values[key])
try:
user.save()
return {"ok": True}
except ValidationError as ve:
raise ValidationError(package_field_errors('user', ve))
def upload_user_photo(request, user):
"""
Saves a user profile photo whose data is in the request.
The callee or decorator is reponsible for ensuring request.user == user
"""
user.photo, user.thumbnail = save_image_from_request(
request, name_prefix="user-%s" % user.pk, thumb_size=(85, 85))
user.save_with_user(request.user)
return {'url': user.thumbnail.url}
def instance_user(request, instance_url_name, username):
instance = get_instance_or_404(url_name=instance_url_name)
url = reverse('user', kwargs={'username': username}) +\
'?instance_id=%s' % instance.pk
return HttpResponseRedirect(url)
def profile_to_user(request):
if request.user and request.user.username:
return HttpResponseRedirect('/users/%s/' % request.user.username)
else:
return HttpResponseRedirect(settings.LOGIN_URL)
def forgot_username(request):
user_email = request.POST['email']
if not user_email:
raise ValidationError({
'user.email': [_('Email field is required')]
})
users = User.objects.filter(email=user_email)
# Don't reveal if we don't have that email, to prevent email harvesting
if len(users) == 1:
user = users[0]
password_reset_url = request.build_absolute_uri(
reverse('auth_password_reset'))
subject = _('Account Recovery')
body = render_to_string('treemap/partials/forgot_username_email.txt',
{'user': user,
'password_url': password_reset_url})
user.email_user(subject, body, settings.DEFAULT_FROM_EMAIL)
return {'email': user_email}
def resend_activation_email_page(request):
return {'username': request.GET.get('username')}
def resend_activation_email(request):
username = request.POST['username']
def error(error):
return render(request, 'treemap/resend_activation_email.html',
{'username': username, 'error': error})
if not username:
return error(_('Username field is required'))
users = User.objects \
.filter(username=username)
if len(users) != 1:
return error(_('There is no user with that username'))
user = users[0]
if user.is_active:
return error(_('This user has already been verified'))
success = RegistrationProfile.objects.resend_activation_mail(
users[0].email, RequestSite(request), request)
if not success:
return error(_('Unable to resend activation email'))
return {'u | ser': user}
def _small_feature_photo_url(feature):
feature = feature.cast_to_subtype()
if feature.is_plot:
tree = feature.current_tree()
i | f tree:
photos = tree.photos()
else:
photos = MapFeaturePhoto.objects.none()
else:
photos = feature.photos()
if len(photos) > 0:
return photos[0].thumbnail.url
else:
return None
def user(request, username):
user = get_object_or_404(User, username=username)
instance_id = request.GET.get('instance_id', None)
instance = (get_instance_or_404(pk=instance_id)
if instance_id else None)
query_vars = QueryDict(mutable=True)
if instance_id:
query_vars['instance_id'] = instance_id
audit_dict = get_audits(request.user, instance, query_vars,
user=user, should_count=True)
reputation = user.get_reputation(instance) if instance else None
favorites_qs = Favorite.objects.filter(user=user).order_by('-created')
favorites = [{
'map_feature': f.map_feature,
'title': f.map_feature.title(),
'instance': f.map_feature.instance,
'address': f.map_feature.address_full,
'photo': _small_feature_photo_url(f.map_feature)
} for f in favorites_qs]
public_fields = []
private_fields = []
for field in USER_PROFILE_FIELDS.values():
field_tuple = (field['label'], field['identifier'],
field.get('template', "treemap/field/div.html"))
if field['visibility'] == 'public' and user.make_info_public is True:
public_fields.append(field_tuple)
else:
private_fields.append(field_tuple)
return {'user': user,
'its_me': user.id == request.user.id,
'reputation': reputation,
'instance_id': instance_id,
'instances': get_user_instances(request.user, user, instance),
'total_edits': audit_dict['total_count'],
'audits': audit_dict['audits'],
'next_page': audit_dict['next_page'],
'public_fields': public_fields,
'private_fields': private_fields,
'favorites': favorites}
def users(request, instance):
max_items = request.GET.get('max_items', None)
query = request.GET.get('q', None)
users_qs = InstanceUser.objects \
.filter(instance=instance)\
.order_by('user__username')\
.values('user_id', 'user__username',
'user__first_name', 'user__last_name',
'user__make_info_public')
if query:
users_qs = users_qs.filter(user__username__icontains=query)\
.order_by(
RawSQL('treemap_user.username ILIKE %s OR NULL', (query,)),
RawSQL('treemap_user.username ILIKE %s OR NULL',
(query + '%',)),
Length('user__username'),
'user__username'
)
if max_items:
users_qs = users_qs[:int(max_items)]
def annotate_user_dict(udict):
user = {
'id': udict['user_id'],
'username': udict['user__username'],
'first_name': '',
'last_name': ''
}
if udict['user__make_info_public']:
user['first_na |
import re
import json
import sqlite3
import nltk
stop = nltk.corpus.stopwords.words("english")
stop.append('rt')
contractions = []
with open('contractions.txt', 'rb') as f:
contractions = [c.strip() for c in f.readlines()]
lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
url_regex = re.compile(r"http[s]?[^\s]*")
contractions_regex = re.compile("|".join(contractions))
first_tweet = None
con = sqlite3.connect("D:/TWEETS/2014-11-05-22-45-54.db")
c = con.cursor()
with open("out.csv", "wb") as o | ut_file:
for row in c.execute("SELECT tweet FROM tweets"):
if first_tweet is None:
first_tweet = row[0]
j = json.loads(row[0])
tweet_id = j['id']
timestamp = j['timestamp_ms']
text = j['text']
text = text.lower()
text = url_regex.sub('', text)
text = contractions_regex.sub('', text)
all_to | kens = tokenizer.tokenize(text)
tokens = []
for token in all_tokens:
token = lemmatizer.lemmatize(token)
if token not in stop:
tokens.append(token)
#items = [str(id), json.dumps(text)] + [token.encode('utf8') for token in tokens]
items = [str(tweet_id), str(timestamp)] + [token.encode('utf8') for token in tokens]
out_file.write(" ".join(items) + "\n")
with open("tweet.json", "wb") as f:
f.write(first_tweet)
con.close() |
# Copyright (c) 2013 Alon Swartz <alon@turnkeylinux.org>
#
# This file is part of OctoHub.
#
# OctoHub 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. |
import simplejson as json
class ResponseError(Exception):
"""Accessible attributes: error
error (AttrDict): Parsed error response
"""
def __init__(self, error):
Exception.__init__(self, error)
self.error = error
def __str__(self):
return json.dumps(self.error, indent=1)
class OctoHubError(Exception):
pass
|
lename = os.path.basename(fieldfile.name)
if filename.endswith('.fastq.gz') or filename.endswith('.fastq'):
print('File extension for {} confirmed valid'.format(filename))
else:
raise ValidationError(
_('%(file)s does not end with .fastq or .fastq.gz'),
params={'filename': filename},
)
class ProjectMulti(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
project_title = models.CharField(max_length=256)
description = models.CharField(max_length=200, blank=True)
date = models.DateTimeField(auto_now_add=True)
forward_id = models.CharField(max_length=256, default='_R1')
reverse_id = models.CharField(max_length=256, default='_R2')
def __str__(self):
return self.project_title
class Sample(models.Model):
project = models.ForeignKey(ProjectMulti, on_delete=models.CASCADE, related_name='samples')
file_R1 = models.FileField(upload_to='%Y%m%d%s', blank=True)
file_R2 = models.FileField(upload_to='%Y%m%d%s', blank=True)
file_fasta = models.FileField(upload_to='%Y%m%d%s', blank=True)
title = models.CharField(max_length=200, blank=True)
genesippr_status = models.CharField(max_length=128,
default="Unprocessed")
sendsketch_status = models.CharField(max_length=128,
default="Unprocessed")
confindr_status = models.CharField(max_length=128,
default="Unprocessed")
genomeqaml_status = models.CharField(max_length=128,
default="Unprocessed")
amr_status = models.CharField(max_length=128,
default="Unprocessed")
def __str__(self):
return self.title
class GenomeQamlResult(models.Model):
class Meta:
verbose_name_plural = "GenomeQAML Results"
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='genomeqaml_result')
predicted_class = models.CharField(max_length=128, default='N/A')
percent_fail = models.CharField(max_length=128, default='N/A')
percent_pass = models.CharField(max_length=128, default='N/A')
percent_reference = models.CharField(max_length=118, default='N/A')
def __str__(self):
return '{}'.format(self.sample)
class SendsketchResult(models.Model):
class Meta:
verbose_name_plural = "Sendsketch Results"
def __str__(self):
return 'pk {}: Rank {}: Sample {}'.format(self.pk, self.rank, self.sample.pk)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE)
rank = models.CharField(max_length=8, default='N/A')
wkid = models.CharField(max_length=256, default='N/A')
kid = models.CharField(max_length=256, default='N/A')
ani = models.CharField(max_length=256, default='N/A')
complt = models.CharField(max_length=256, default='N/A')
contam = models.CharField(max_length=256, default='N/A')
matches = models.CharField(max_length=256, default='N/A')
unique = models.CharField(max_length=256, default='N/A')
nohit = models.CharField(max_length=256, default='N/A')
taxid = models.CharField(max_length=256, default='N/A')
gsize = models.CharField(max_length=256, default='N/A')
gseqs = models.CharField(max_length=256, default='N/A')
taxname = models.CharField(max_length=256, default='N/A')
class GenesipprResults(models.Model):
# For admin panel
def __str__(self):
return '{}'.format(self.sample)
# TODO: Accomodate seqID
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='genesippr_results')
# genesippr.csv
strain = models.CharField(max_length=256, default="N/A")
genus = models.CharField(max_length=256, default="N/A")
# STEC
serotype = models.CharField(max_length=256, default="N/A")
o26 = models.CharField(max_length=256, default="N/A")
o45 = models.CharField(max_length=256, default="N/A")
o103 = models.CharField(max_length=256, default="N/A")
o111 = models.CharField(max_length=256, default="N/A")
o121 = models.CharField(max_length=256, default="N/A")
o145 = models.CharField(max_length=256, default="N/A")
o157 = models.CharField(max_length=256, default="N/A")
uida = models.CharField(max_length=256, default="N/A")
eae = models.CharField(max_length=256, default="N/A")
eae_1 = models.CharField(max_length=256, default="N/A")
vt1 = models.CharField(max_length=256, default="N/A")
vt2 = models.CharField(max_length=256, default="N/A")
vt2f = models.CharField(max_length=256, default="N/A")
# listeria
igs = models.CharField(max_length=256, default="N/A")
hlya = models.CharField(max_length=256, default="N/A")
inlj = models.CharField(max_length=256, default="N/A")
# salmonella
inva = models.CharField(max_length=256, default="N/A")
stn = models.CharField(max_length=256, default="N/A")
def inva_number(self):
return float(self.inva.split('%')[0])
def uida_number(self):
return float(self.uida.split('%')[0])
def vt1_number(self):
return float(self.vt1.split('%')[0])
def vt2_number(self):
return float(self.vt2.split('%')[0])
def vt2f_number(self):
return float(self.vt2f.split('%')[0])
def eae_number(self):
return float(self.eae.split('%')[0])
def eae_1_number(self):
return float(self.eae_1.split('%')[0])
def hlya_number(self):
return float(self.hlya.split('%')[0])
def igs_number(self):
return float(self.igs.split('%')[0])
def inlj_number(self):
return float(self.inlj.split('%')[0])
class Meta:
verbose_name_plural = "Genesippr Results"
class GenesipprResultsSixteens(models.Model):
class Meta:
verbose_name_plural = "SixteenS Results"
def __str__(self):
return '{}'.format(self.sample)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='sixteens_results')
# sixteens_full.csv
strain = models.CharField(max_length=256, default="N/A")
gene = models.CharField(max_length=256, default="N/A")
percentidentity = models.CharField(max_length=256, default="N/A")
genus = models.CharField(max_length=256, default="N/A")
foldcoverage = models.CharField(max_length=256, default="N/A")
@property
def gi_accession(self):
# Split by | delimiter, pull second element which should be the GI#
gi_accession = self.gene.split('|')[1]
return gi_accession
class GenesipprResultsGDCS(models.Model):
class Meta:
verbose_name_plural = "GDCS Results"
def __str__(self):
return '{}'.format(self.sample)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_ | name='gdcs_results')
# GDCS.csv
strain = models.CharField(max_length=256, default="N/A")
genus = models.CharField(max_length=256, default="N/A")
matches = models.CharField(max_length=256, default="N/A")
meancoverage = models.CharField(max_length=128, default="N/A")
passfail = models.CharField(max_length=16, default="N/A")
allele_dict = JSONField(blank=True, null=True, default=dict)
class ConFindrResults(models.Model):
class Meta:
| verbose_name_plural = 'Confindr Results'
def __str__(self):
return '{}'.format(self.sample)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='confindr_results')
strain = models.CharField(max_length=256, default="N/A")
genera_present = models.CharField(max_length=256, default="N/A")
contam_snvs = models.CharField(max_length=256, default="N/A")
contaminated = models.CharField(max_length=256, default="N/A")
class GenesipprResultsSerosippr(models.Model):
class Meta:
verbose_name_plural = "Serosippr Results"
def __str__(self):
return '{}'.format(self.sample)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE)
class AMRResult(models.Model):
class Meta:
verbose_name_plural = 'AMR Results'
def __str__(self):
return '{}'.format(self.samp |
# Copyright 2016 Open Source Robotics Foundation, 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 distribu | ted 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 ament_flake8.main import main_with_errors
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d code style errors / warnings | :\n' % len(errors) + \
'\n'.join(errors)
|
import os
from setuptools import setup, find_packages
from jw2html import VERSION
setup(
name='JW2HTML',
version=VERSION,
description='JW2HTML converts an issue of the Jungle World from the website to a single HTML file to be used for epub conversion by e.g. calibre.',
long_description='Alas | , there is no epub version of the Jungle World, http://jungle-world.com . Hence this little module to download the current issue and pack it into one HTML file which can then be converted to epub (using e.g. http://calibre-ebook.com). It also downloads the cover image for easy inclusion when creating the book in calibre.',
license='GPL',
keywords='jungle world newspaper html epub convert',
url='https://github.com/mar | morkuchen/jw2html',
author='marmorkuchen',
author_email='marmorkuchen@kodeaffe.de',
packages=find_packages(),
include_package_data=True,
data_files=[
('doc', ['README.rst', 'LICENSE']),
(os.path.join(os.sep, 'etc'), ['jw2html.ini',]),
],
entry_points={
'console_scripts': [
'jw2html = jw2html:main',
]
},
install_requires=[
'beautifulsoup4',
],
)
|
# coding: utf8
from functools import wraps
from logging import getLogger
logger = getLogger(__name__)
__author__ = 'marcos.costa'
class request_logger(object):
def __init__(self, method=None):
self.method = method
def __call__(self, func):
method = self.method
if method is None:
method = func.func_name
@wra | ps(func)
def wrapper(instance, request, *args, **kwargs):
response = func(instance, request, *args, **kwargs)
msg = ("\nCalled method: {method}\nrequest: {request}"
"\nresponse: {response}").format(method=method,
request=request,
response=response)
logger.info(msg)
return | response
return wrapper |
from werkzeug.local import LocalProxy
from . import extension_access
def extension_access_proxy(name): |
return LocalProxy(lambda: getattr(extension_access, name, None))
# Mostly for backwards compatibility
cache = extension_access_proxy("cache")
mongo = extension_access_proxy("mongo")
mai | l = extension_access_proxy("mail")
admin = extension_access_proxy("admin")
rest_api = extension_access_proxy("rest_api")
markdown = extension_access_proxy("markdown")
assets = extension_access_proxy("assets")
|
import AI.pad
import AI.state
class Character:
def __init__(self, pad_path):
self.action_list = []
self.last_action = 0
self.pad = AI.pad.Pad(pad_path)
self.state = AI.state.State()
#Set False to enable character selection
self.test_mode = True
self.sm = AI.state_manager.StateManager(self.state, self.test_mode)
#test_mode = False, Selects character each run
def make_action(self, mm):
if self.state.menu == AI.state.Menu.Game:
self.advance()
elif self.state.menu == AI.state.Menu.Characters:
mm.pick_fox(self.state, self.pad)
elif self.state.menu == AI.state.Menu.Stages:
self.pad.tilt_stick(AI.pad.Stick.C, 0.5, 0.5)
elif self.state.menu == AI.state.Menu.PostGame:
mm.press_start_lots(self.state, self.pad)
#test_mode = True, AI starts fighting each run, saves time during testing
def make_action_test(self, mm):
if self.state.menu == AI.state.Menu.Game:
self.advance()
elif self.state.menu == AI.state.Menu.PostGame:
mm.press_start_lots(self.state, self.pad)
#implemented by each character to decide what to do
#includes some states where each character will respond the same
def logic(self):
if AI.state.is_spawning(self.state.players[2].action_state):
self.tilt_stick(60, 'DOWN')
self.tilt_stick(3, None)
#compare AI's current state
def compare_AI_state(self, test_state):
return self.state.players[2].action_state is test_state
#compare P1 current state
def compare_P1_state(self, test_state):
return self.state.players[0].action_state is test_state
#executes button presses defined in action_list, runs logic() once list is empty
de | f advance(self):
while self.action_list:
wait, func, args = self.action_list[0]
if self.state.frame - self.last_action < wait:
return
else:
self.action_list.pop(0)
| if func is not None:
func(*args)
self.last_action = self.state.frame
else:
self.logic()
'''Methods simulate controller input; appends necessary tuple to action_list'''
def press_button(self, wait, button):
self.action_list.append((wait, self.pad.press_button, [button]))
def release_button(self, wait, button):
self.action_list.append((wait, self.pad.release_button, [button]))
def tilt_stick(self, wait, direction):
if direction is 'UP':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.MAIN, 0.5, 1.0]))
elif direction is 'DOWN':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.MAIN, 0.5, 0.0]))
elif direction is 'DOWN_LEFT':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.MAIN, 0.25, 0.25]))
elif direction is 'DOWN_RIGHT':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.MAIN, 0.75, 0.25]))
elif direction is 'RIGHT':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.MAIN, 1.0, 0.5]))
elif direction is 'LEFT':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.MAIN, 0.0, 0.5]))
elif direction is None:
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.MAIN, 0.5, 0.5]))
def tilt_c_stick(self, wait, direction):
if direction is 'UP':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.C, 0.5, 1.0]))
elif direction is 'DOWN':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.C, 0.5, 0.0]))
elif direction is 'RIGHT':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.C, 1.0, 0.5]))
elif direction is 'LEFT':
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.C, 0.0, 0.5]))
elif direction is None:
self.action_list.append((wait, self.pad.tilt_stick, [AI.pad.Stick.C, 0.5, 0.5]))
def press_trigger(self, wait, amount):
self.action_list.append((wait, self.pad.press_trigger, [AI.pad.Trigger.L, amount]))
def wait(self, wait):
self.action_list.append((wait, None, []))
'''Execute actions shared among all characters'''
def style(self, wait):
pass
def side_b(self, wait):
self.tilt_stick(wait, 'RIGHT')
self.press_button(1, AI.pad.Button.B)
self.release_button(2, AI.pad.Button.B)
self.tilt_stick(2, None)
def shield(self, wait, length):
self.press_trigger(wait, 0.3)
self.press_trigger(length, 0.0)
def dashdance(self, wait, length):
self.wait(wait)
for _ in range(length):
self.tilt_stick(4, 'LEFT')
self.tilt_stick(4, 'RIGHT')
self.tilt_stick(1, None)
def shorthop(self, wait):
self.press_button(wait, AI.pad.Button.X)
self.release_button(1, AI.pad.Button.X)
'''Execute similar actions that is dependent on character frame data'''
def wavedash(self, wait, direction, wait_airdodge):
self.tilt_stick(wait, direction)
self.shorthop(1)
self.press_button(wait_airdodge, AI.pad.Button.L)
self.release_button(2, AI.pad.Button.L)
self.tilt_stick(1, None)
def shorthop_nair(self, wait, wait_attack, wait_ff):
self.shorthop(wait)
self.press_button(wait_attack, AI.pad.Button.A)
self.release_button(1, AI.pad.Button.A)
self.tilt_stick(wait_ff, 'DOWN')
self.tilt_stick(3, None)
self.press_trigger(2, 0.5)
self.press_trigger(1, 0.0)
|
import sys
folder_loc = sys.argv[1]
filename =sys.argv[2]
fileobj = open(folder_loc + filename);
flag=0
real_rev = open(folder_loc + "real_"+filename,"w+")
fake_rev = open(folder_loc + "fake_"+filename,"w+")
for line in fileobj:
for i in range(len(line)):
if (line[i] == '[' | and flag == 0): #for beginning of real reviews
flag = 1
elif (line[i-1]==']' and flag == 1): #for end of real reviews
flag = 2
elif (line[i]=='[' and flag == 2) | : #for beginning of fake reviews
flag = 3
elif (line[i-1] == ']' and flag == 3): #for end of fake reviews
flag = 4
if(flag ==1):
real_rev.write(line[i])
elif(flag==3):
fake_rev.write(line[i])
|
# -*- coding: utf-8 -*-
"""tests decoration handling functions that are used by checks"""
from translate.filters import decoration
def test_spacestart():
"""test operation of spacestart()"""
assert decoration.spacestart(" Start") == " "
assert decoration.spacestart(u"\u0020\u00a0Start") == u"\u0020\u00a0"
# non-breaking space
assert decoration.spacestart(u"\u00a0\u202fStart") == u"\u00a0\u202f"
# Some exotic spaces
assert decoration.spacestart(u"\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200aStart") == u"\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a"
def test_isvalidaccelerator():
"""test the isvalidaccelerator() function"""
# Mostly this tests the old code path where acceptlist is None
assert n | ot decoration.isvalidaccelerator(u"")
assert decoration.isvalidaccelerator(u"a")
assert decoration.isvalidaccelerator(u"1")
assert not decoration.isvalidaccelerator(u"ḽ")
# Test new code path where we actually have an acceptlist
assert decoration.isvalidaccelerator(u"a", u"aeiou")
assert decoration.isvalidaccelerator(u"ḽ", u"ḓṱḽṋṅ")
assert not decoration.isvalidacc | elerator(u"a", u"ḓṱḽṋṅ")
def test_find_marked_variables():
"""check that we can identify variables correctly, the first returned
value is the start location, the second returned value is the actual
variable sans decoations"""
variables = decoration.findmarkedvariables("The <variable> string", "<", ">")
assert variables == [(4, "variable")]
variables = decoration.findmarkedvariables("The $variable string", "$", 1)
assert variables == [(4, "v")]
variables = decoration.findmarkedvariables("The $variable string", "$", None)
assert variables == [(4, "variable")]
variables = decoration.findmarkedvariables("The $variable string", "$", 0)
assert variables == [(4, "")]
variables = decoration.findmarkedvariables("The &variable; string", "&", ";")
assert variables == [(4, "variable")]
variables = decoration.findmarkedvariables("The &variable.variable; string", "&", ";")
assert variables == [(4, "variable.variable")]
def test_getnumbers():
"""test operation of getnumbers()"""
assert decoration.getnumbers(u"") == []
assert decoration.getnumbers(u"No numbers") == []
assert decoration.getnumbers(u"Nine 9 nine") == ["9"]
assert decoration.getnumbers(u"Two numbers: 2 and 3") == ["2", "3"]
assert decoration.getnumbers(u"R5.99") == ["5.99"]
# TODO fix these so that we are able to consider locale specific numbers
#assert decoration.getnumbers(u"R5,99") == ["5.99"]
#assert decoration.getnumbers(u"1\u00a0000,99") == ["1000.99"]
assert decoration.getnumbers(u"36°") == [u"36°"]
assert decoration.getnumbers(u"English 123, Bengali \u09e7\u09e8\u09e9") == [u"123", u"\u09e7\u09e8\u09e9"]
def test_getfunctions():
"""test operation of getfunctions()"""
assert decoration.getfunctions(u"") == []
assert decoration.getfunctions(u"There is no function") == []
assert decoration.getfunctions(u"Use the getfunction() function.") == ["getfunction()"]
assert decoration.getfunctions(u"Use the getfunction1() function or the getfunction2() function.") == ["getfunction1()", "getfunction2()"]
assert decoration.getfunctions(u"The module.getfunction() method") == ["module.getfunction()"]
assert decoration.getfunctions(u"The module->getfunction() method") == ["module->getfunction()"]
assert decoration.getfunctions(u"The module::getfunction() method") == ["module::getfunction()"]
assert decoration.getfunctions(u"The function().function() function") == ["function().function()"]
assert decoration.getfunctions(u"Deprecated, use function().") == ["function()"]
assert decoration.getfunctions(u"Deprecated, use function() or other().") == ["function()", "other()"]
|
# POS Census v0.1
# Copyright (c) 2012 Andrew Austin
# 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/>.
#
# Names and data specific to Eve Online are Copyright CCP Games H.F.
import eveapi
import csv
import sqlite3
# Put your API information here
keyID = XXXXXXX
vCode = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# Put the system ID you want to take a census of here
systemID = XXXXXXXXX
def build_database():
"""
Build a sqlite3 database from the mapDenormalize.csv data file.
"""
print "Building database...\n"
conn = sqlite3.Connection("mapData.db")
c = conn.cursor()
c.execute('''CREATE TABLE mapDenormalize (id int, name text)''')
reader = csv.reader(open('mapDenormalize.csv'))
# Skip the header row
next(reader)
# Build a list from which we'll populate the sqlite DB
records = []
for row in reader:
records.append((int(row[0]), row[11]))
print "Inserting %s rows to mapData.db..." % len(records)
c.executemany("INSERT INTO mapDenormalize VALUES (?,?)", records)
conn.commit()
conn.close()
class POS:
"""
A POS object, contains a location string, and lists of chas and smas.
The lists of chas and smas are lists of (itemID, name) tuples.
"""
def __init__(self, name, location, x, y, z, smas=[], chas=[]):
self.name = name
self.location = location
self.smas = smas
self.chas = chas
self.x = x
self.y = y
self.z = z
def report(self):
"""
Output the report for this POS.
"""
print "*****************************"
print "POS: %s at %s" % (self.name, self.location)
print "\t %s CHAs:" % len(self.chas)
for cha in self.chas:
print "\t \t itemID: %s \t Name: %s" % (cha[0], cha[1])
print "\t %s SMAs:" % len(self.smas)
for sma in self.smas:
print "\t \t itemID: %s \t Name: %s" % (sma[0], sma[1])
print "*****************************"
def is_owner(self, x, y, z):
"""
Returns True if the given x,y,z coordinates are within 350km of the POS.
"""
minx = self.x - 350000
maxx = self.x + 350000
miny = self.y - 350000
maxy = self.y + 350000
minz = self.z - 350000
maxz = self.z + 350000
return minx <= x <= maxx and miny <= y <= maxy and minz <= z <= maxz
def generate_report():
"""
Main entry point for the program.
Generates POS objects StarbaseList API and populates them
using AssetList and Locations API calls.
"""
api = eveapi.EVEAPIConnection()
auth = api.auth(keyID=keyID, vCode=vCode)
conn = sqlite3.Connection('mapData.db')
c = conn.cursor()
print "Downloading Corporation Asset List..."
assets = auth.corp.AssetList()
print "Downloading Starbase List..."
starbases = auth.corp.StarbaseList()
rawCHAList = []
rawSMAList = []
poslist = []
for asset in ass | ets.assets:
if asset.locationID == systemID:
if asset.typeID == 17621:
rawCHAList.append(asset.itemID)
if asset.typeID == 12237:
rawSMAList.append(asset.itemID)
print "Bui | lding POS List..."
for pos in starbases.starbases:
locationapi = auth.corp.Locations(IDs=pos.itemID).locations[0]
moon = c.execute("SELECT name from mapDenormalize WHERE id = %s" % pos.moonID).fetchone()[0]
poslist.append(POS(name=locationapi.itemName,
location=moon, smas=[], chas=[], x=locationapi.x,
y=locationapi.y, z=locationapi.z))
print "Processing SMAs..."
for sma in rawSMAList:
locationapi = auth.corp.Locations(IDs=sma).locations[0]
x = locationapi.x
y = locationapi.y
z = locationapi.z
name = locationapi.itemName
for pos in poslist:
if pos.is_owner(x=x, y=y, z=z):
pos.smas.append((sma, name))
print "Processing CHAs..."
for cha in rawCHAList:
locationapi = auth.corp.Locations(IDs=cha).locations[0]
x = locationapi.x
y = locationapi.y
z = locationapi.z
name = locationapi.itemName
for pos in poslist:
if pos.is_owner(x=x, y=y, z=z):
pos.chas.append((cha, name))
print "Displaying Report..."
for pos in poslist:
pos.report()
# Make sure we enter at generate_report()
if __name__ == "__main__":
generate_report()
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from librar | y.modules.bigip_vcmp_guest import Parameters
from library.modules.bigip_vcmp_guest import ModuleManager
from library.modules.bigip_vcmp_guest import ArgumentSpec
| # In Ansible 2.8, Ansible changed import paths.
from test.units.compat import unittest
from test.units.compat.mock import Mock
from test.units.compat.mock import patch
from test.units.modules.utils import set_module_args
except ImportError:
try:
from ansible.modules.network.f5.bigip_vcmp_guest import Parameters
from ansible.modules.network.f5.bigip_vcmp_guest import ModuleManager
from ansible.modules.network.f5.bigip_vcmp_guest import ArgumentSpec
# Ansible 2.8 imports
from units.compat import unittest
from units.compat.mock import Mock
from units.compat.mock import patch
from units.modules.utils import set_module_args
except ImportError:
raise SkipTest("F5 Ansible modules require the f5-sdk Python library")
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
initial_image='BIGIP-12.1.0.1.0.1447-HF1.iso',
mgmt_network='bridged',
mgmt_address='1.2.3.4/24',
vlans=[
'vlan1',
'vlan2'
]
)
p = Parameters(params=args)
assert p.initial_image == 'BIGIP-12.1.0.1.0.1447-HF1.iso'
assert p.mgmt_network == 'bridged'
def test_module_parameters_mgmt_bridged_without_subnet(self):
args = dict(
mgmt_network='bridged',
mgmt_address='1.2.3.4'
)
p = Parameters(params=args)
assert p.mgmt_network == 'bridged'
assert p.mgmt_address == '1.2.3.4/32'
def test_module_parameters_mgmt_address_cidr(self):
args = dict(
mgmt_network='bridged',
mgmt_address='1.2.3.4/24'
)
p = Parameters(params=args)
assert p.mgmt_network == 'bridged'
assert p.mgmt_address == '1.2.3.4/24'
def test_module_parameters_mgmt_address_subnet(self):
args = dict(
mgmt_network='bridged',
mgmt_address='1.2.3.4/255.255.255.0'
)
p = Parameters(params=args)
assert p.mgmt_network == 'bridged'
assert p.mgmt_address == '1.2.3.4/24'
def test_module_parameters_mgmt_route(self):
args = dict(
mgmt_route='1.2.3.4'
)
p = Parameters(params=args)
assert p.mgmt_route == '1.2.3.4'
def test_module_parameters_vcmp_software_image_facts(self):
# vCMP images may include a forward slash in their names. This is probably
# related to the slots on the system, but it is not a valid value to specify
# that slot when providing an initial image
args = dict(
initial_image='BIGIP-12.1.0.1.0.1447-HF1.iso/1',
)
p = Parameters(params=args)
assert p.initial_image == 'BIGIP-12.1.0.1.0.1447-HF1.iso/1'
def test_api_parameters(self):
args = dict(
initialImage="BIGIP-tmos-tier2-13.1.0.0.0.931.iso",
managementGw="2.2.2.2",
managementIp="1.1.1.1/24",
managementNetwork="bridged",
state="deployed",
vlans=[
"/Common/vlan1",
"/Common/vlan2"
]
)
p = Parameters(params=args)
assert p.initial_image == 'BIGIP-tmos-tier2-13.1.0.0.0.931.iso'
assert p.mgmt_route == '2.2.2.2'
assert p.mgmt_address == '1.1.1.1/24'
assert '/Common/vlan1' in p.vlans
assert '/Common/vlan2' in p.vlans
class TestManager(unittest.TestCase):
def setUp(self):
self.spec = ArgumentSpec()
self.patcher1 = patch('time.sleep')
self.patcher1.start()
def tearDown(self):
self.patcher1.stop()
def test_create_vlan(self, *args):
set_module_args(dict(
name="guest1",
mgmt_network="bridged",
mgmt_address="10.10.10.10/24",
initial_image="BIGIP-13.1.0.0.0.931.iso",
server='localhost',
password='password',
user='admin'
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
# Override methods to force specific logic in the module to happen
mm = ModuleManager(module=module)
mm.create_on_device = Mock(return_value=True)
mm.exists = Mock(return_value=False)
mm.is_deployed = Mock(side_effect=[False, True, True, True, True])
mm.deploy_on_device = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
assert results['name'] == 'guest1'
|
from __future__ import division, print_function
from os.path import join, split, dirname
import os
import sys
from distutils.dep_util import newer
from distutils.msvccompiler import get_build_version as get_msvc_build_version
def needs_mingw_ftime_workaround():
# We need the mingw workaround for _ftime if the msvc runtime version is
# 7.1 or above and we build with mingw ...
# ... but we can't easily detect compiler version outside distutils command
# context, so we will need to detect in randomkit whether we build with gcc
msver = get_msvc_build_version()
if msver and msver >= 8:
return True
return False
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration, get_mathlibs
config = Configuration('random', parent_package, top_path)
def generate_libraries(ext, build_dir):
config_cmd = config.get_config_cmd()
libs = get_mathlibs()
tc = testcode_wincrypt()
if config_cmd.try_run(tc):
libs.append('Advapi32')
ext.libraries.extend(libs)
return None
# enable unix large file support on 32 bit systems
# (64 bit off_t, lseek -> lseek64 etc.)
defs = [('_FILE_OFFSET_BITS', '64'),
('_LARGEFILE_SOURCE', '1'),
('_LARGEFILE64_SOURCE', '1'),
]
if needs_mingw_ftime_workaround():
defs.append(("NPY_NEEDS_MINGW_TIME_WORKAROUND", None))
libs = []
# Configure mtrand
try:
import cffi
have_cffi = True
except ImportError:
have_cffi = False
if have_cffi:
#create the dll/so for the cffi version
if sys.platform == 'win32':
libs.append('Advapi32')
defs.append(('_MTRAND_DLL',None))
config.add_shared_library('_mtrand',
sources=[join('mtrand', x) for x in
['randomkit.c', 'distributions.c', 'initarray.c']],
build_info = {
'libraries': libs,
'depends': [join('mtrand', '*.h'),
],
'macros': defs,
}
)
else:
config.add_extension('mtrand',
sources=[join('mtrand', x) for x in
['mtrand.c', 'randomkit.c', 'initarray.c',
| 'distributions.c']]+[generate_librar | ies],
libraries=libs,
depends=[join('mtrand', '*.h'),
join('mtrand', '*.pyx'),
join('mtrand', '*.pxi'),],
define_macros=defs,
)
config.add_data_files(('.', join('mtrand', 'randomkit.h')))
config.add_data_dir('tests')
return config
def testcode_wincrypt():
return """\
/* check to see if _WIN32 is defined */
int main(int argc, char *argv[])
{
#ifdef _WIN32
return 0;
#else
return 1;
#endif
}
"""
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
|
# -*- coding: UTF-8 -*-
"""
Options quotes.
"""
import os
import json
import logging
from datetime import datetime
import collections
import requests
from landscape.finance import consts, database, dates, utils
from landscape.finance.volatility import math
OptionQuote = collections.namedtuple(
'OptionQuote',
'symbol type expiration strike date time bid ask stock iv_bid iv_ask')
CBOE_URL = 'http://www.cboe.com/DelayedQuote/QuoteTableDownload.aspx'
current_dir = os.path.dirname(__file__)
with open(os.path.join(current_dir, 'data/cboe_headers.json')) as f:
CBOE_HEADERS = json.load(f)
with open(os.path.join(current_dir, 'data/cboe_post_data.json')) as f:
CBOE_POST_DATA = json.load(f)
CBOE_POST_DATA_TICKER_KEY = 'ctl00$ctl00$AllContent$ContentMain$' \
'QuoteTableDownloadCtl1$txtTicker'
MONTHS = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
SKIP_SYMBOLS = ['SPXW', 'SPXQ', 'SPY7', 'SPYJ', 'VXX2']
def save_quote(db, quote):
"""Saves quote to database"""
expiration = database.encode_date(quote.expiration)
date = database.encode_date(quote.date)
time = database.encode_time(quote.time)
db.execute('UPDATE options SET time=?, bid=?, ask=?, stock=?, ' \
'iv_bid=?, iv_ask=? ' \
'WHERE symbol=? AND type=? AND expiration=? ' \
'AND strike=? AND date=?;', [time, quote.bid, quote.ask,
quote.stock, quote.iv_bid, quote.iv_ask, quote.symbol,
quote.type, expiration, quote.strike, date])
if db.rowcount == 0:
db.execute('INSERT INTO options VALUES ' \
'(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
[quote.symbol, quote.type, expiration, quote.strike,
date, time, quote.bid, quote.ask, quote.stock,
quote.iv_bid, quote.iv_ask])
def quote_factory(_, row):
"""Converts row to quote"""
symbol, type_, expiration, strike, date, time, \
bid, ask, stock, iv_bid, iv_ask = row
expiration = database.decode_date(expiration)
date = database.decode_date(date)
time = database.decode_time(time)
return OptionQuote(symbol, type_, expiration, strike, date, time,
bid, ask, stock, iv_bid, iv_ask)
def _fetch_data(symbol):
"""Fetches realtime (delayed) options quotes from CBOE as a raw text.
Args:
symbol (str): Symbol to fetch.
Returns:
str: Raw quotes, or None if failed.
"""
logger = logging.getLogger(__name__)
logger.info('Fetching options quotes from CBOE for %s ...', symbol)
data = dict(CBOE_POST_DATA)
data[CBOE_POST_DATA_TICKER_KEY] = symbol
response = requests.post(CBOE_URL, data=data, headers=CBOE_HEADERS)
if response.status_code == 200:
return response.text
else:
logger.error('Cannot fetch options quotes from CBOE for %s', symbol)
def _parse_data(symbol, data, is_eod, db_name=None, timestamp=None):
"""Parses realtime (delayed) options quotes from CBOE and saves to
database.
Args:
symbol (str): Symbol.
data (str): Raw quotes for the symbol.
is_eod (bool): If True: mark received quotes as EOD (time=None),
if False: store actual time.
db_name (str): Optional database name.
timestamp (datetime): Optional datetime for the data.
Returns:
list: List of OptionQuote objects.
"""
logger = logging.getLogger(__name__)
if timestamp is None:
timestamp = dates.get_database_timestamp()
date = timestamp.date()
time = None if is_eod else timestamp.time()
quotes = []
stock_price = None
expirations = dates.get_expirations(symbol)
with database.connect_db(db_name) as db:
for line in data.splitlines():
values = line.strip().split(',')
if (len(values) == 4) and (stock_price is None):
stock_price = utils.to_float(values[1])
continue
if len(values) != 15:
continue
if values[0] == 'Calls' or values[0].find('-') >= 0:
continue
code_values = values[0].split(' ')
if len(code_values) != 4:
continue
position = code_values[3].find(code_values[0])
if code_values[3][1:position] in SKIP_SYMBOLS:
continue
expiration_year = 2000 + int(code_values[0])
expiration_month = MONTHS[code_values[1]]
expiration_day = int(code_values[3][position + 2:position + 4])
expiration = datetime(expiration_year, expiration_month,
expiration_day).date()
if expiration not in expirations:
continue
strike = utils.to_float(code_values[2])
for type_, bid, ask in [
(consts.CALL, values[3], values[4]),
(consts.PUT, values[10], values[11]),
]:
bid = utils.to_float(bid)
ask = utils.to_float(ask)
quote = OptionQuote(
symbol, type_, expiration, strike, date, time,
bid, ask, stock_price, None, None)
| iv_bid = math.calc_iv(quote, bid) * 100
iv_ask = math.calc_iv(quote, ask) * 100
quote = OptionQuote(
symbol, | type_, expiration, strike, date, time,
bid, ask, stock_price, iv_bid, iv_ask)
save_quote(db, quote)
quotes.append(quote)
logger.info('... quotes parsed: %d', len(quotes))
return quotes
def fetch_realtime(symbol, db_name=None):
"""Fetches realtime (delayed) options quotes from CBOE and saves to
database.
Args:
symbol (str): Symbol to fetch.
db_name (str): Optional database name.
Returns:
list: list of OptionQuote objects
"""
data = _fetch_data(symbol)
return _parse_data(symbol, data, False, db_name) if data else []
def fetch_historical(symbol, db_name=None):
"""Actually stores realtime data to database.
There's no free EOD options quotes provider so you need to call this method
at the end of each business day.
Args:
symbol: Symbol to fetch.
db_name (str): Optional database name.
Returns:
Number of quotes fetched.
"""
data = _fetch_data(symbol)
return len(_parse_data(symbol, data, True, db_name)) if data else 0
def query_historical(symbol, date, db_name=None):
"""Queries historical quotes from local database for given symbol and date.
Mimics fetch_realtime.
Args:
symbol (str): Stock symbol.
date (date): Date to query.
db_name (str): Optional database name.
Returns:
See fetch_realtime.
"""
with database.connect_db(db_name) as db:
db.row_factory = quote_factory
db.execute('SELECT * FROM options WHERE symbol=? AND date=?;',
[symbol, database.encode_date(date)])
return db.fetchall()
|
import string
# Manages Local "database" for ZBWarDrive:
# This keeps track of current ZBWarDrive and Sniffing Device State.
# It is different from the online logging database.
class ZBScanDB:
"""
API to interact with the "database" storing information
for the zbscanning program.
"""
def __init__(self):
self.channels = {11:None, 12:None, 13:None, 14:None, 15:None, 16:None, 17:None, 18:None, 19:None, 20:None, 21:None, 22:None, 23:None, 24:None, 25:None, 26:None}
# Devices is indexed by deviceId and stores a 4-tuple of device string, device serial, current status, and current channel
self.devices = {}
def close(self):
pass
# Add a new devices to the D | B
def store_devices(self, devid, devstr, devserial):
self.devices[devid] = (devstr, devserial, 'Free', None)
# R | eturns the devid of a device marked 'Free',
# or None if there are no Free devices in the DB.
def get_devices_nextFree(self):
for devid, dev in self.devices.items():
if dev[2] == 'Free':
return devid
def update_devices_status(self, devid, newstatus):
if devid not in self.devices:
return None
(devstr, devserial, _, chan) = self.devices[devid]
self.devices[devid] = (devstr, devserial, newstatus, chan)
def update_devices_start_capture(self, devid, channel):
if devid not in self.devices:
return None
(devstr, devserial, _, _) = self.devices[devid]
self.devices[devid] = (devstr, devserial, "Capture", channel)
# Add a new network to the DB
def store_networks(self, key, spanid, source, channel, packet):
if channel not in self.channels:
return None
# TODO note this only stores the most recent in the channel
self.channels[channel] = (key, spanid, source, packet)
# Return the channel of the network identified by key,
# or None if it doesn't exist in the DB.
def get_networks_channel(self, key):
#print "Looking up channel for network with key of %s" % (key)
for chan, data in self.channels:
if data[0] == key: return chan
return None
def channel_status_logging(self, chan):
'''
Returns False if we have not seen the network or are not currently
logging it's channel, and returns True if we are currently logging it.
@return boolean
'''
if chan == None: raise Exception("None given for channel number")
elif chan not in self.channels: raise Exception("Invalid channel")
for dev in self.devices.values():
if dev[3] == chan and dev[2] == 'Capture':
return True
return False
# end of ZBScanDB class
def toHex(bin):
return ''.join(["%02x" % ord(x) for x in bin])
|
"""Support for interfacing with Monoprice 6 zone home audio controller."""
import logging
import voluptuous as vol
from homeassistant.components.media_player import MediaPlayerDevice, PLATFORM_SCHEMA
from homeassistant.components.media_player.const import (
SUPPORT_SELECT_SOURCE,
SUPPORT_TURN_OFF,
SUPPORT_TURN_ON,
SUPPORT_VOLUME_MUTE,
SUPPORT_VOLUME_SET,
SUPPORT_VOLUME_STEP,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_NAME,
CONF_PORT,
STATE_OFF,
STATE_ON,
)
import homeassistant.helpers.config_validation as cv
from .const import DOMAIN, SERVICE_RESTORE, SERVICE_SNAPSHOT
_LOGGER = logging.getLogger(__name__)
SUPPORT_MONOPRICE = (
SUPPORT_VOLUME_MUTE
| SUPPORT_VOLUME_SET
| SUPPORT_VOLUME_STEP
| SUPPORT_TURN_ON
| SUPPORT_TURN_OFF
| SUPPORT_SELECT_SOURCE
)
ZONE_SCHEMA = vol.Schema({vol.Required(CONF_NAME): cv.string})
SOURCE_SCHEMA = vol.Schema({vol.Required(CONF_NAME): cv.string})
CONF_ZONES = "zones"
CONF_SOURCES = "sources"
DATA_MONOPRICE = "monoprice"
# Valid zone ids: 11-16 or 21-26 or 31-36
ZONE_IDS = vol.All(
vol.Coerce(int),
vol.Any(
vol.Range(min=11, max=16), vol.Range(min=21, max=26), vol.Range(min=31, max=36)
),
)
# Valid source ids: 1-6
SOURCE_IDS = vol.All(vol.Coerce(int), vol.Range(min=1, max=6))
MEDIA_PLAYER_SCHEMA = vol.Schema({ATTR_ENTITY_ID: cv.comp_entity_ids})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_PORT): cv.string,
vol.Required(CONF_ZONES): vol.Schema({ZONE_IDS: ZONE_SCHEMA}),
vol.Required(CONF_SOURCES): vol.Schema({SOURCE_IDS: SOURCE_SCHEMA}),
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Monoprice 6-zone amplifier platform."""
port = config.get(CONF_PORT)
from serial import SerialException
from pymonoprice import get_monoprice
try:
monoprice = get_monoprice(port)
except SerialException:
_LOGGER.error("Error connecting to Monoprice controller")
return
sources = {
source_id: extra[CONF_NAME] for source_id, extra in config[CONF_SOURCES].items()
}
hass.data[DATA_MONOPRICE] = []
for zone_id, extra in config[CONF_ZONES].items():
_LOGGER.info("Adding zone %d - %s", zone_id, extra[CONF_NAME])
hass.data[DATA_MONOPRICE].append(
MonopriceZone(monoprice, sources, zone_id, extra[CONF_NAME])
)
add_entities(hass.data[DATA_MONOPRICE], True)
def service_handle(service):
"""Handle for services."""
entity_ids = service.data.get(ATTR_ENTITY_ID)
if entity_ids:
devices = [
device
for device in hass.data[DATA_MONOPRICE]
if device.entity_id in entity_ids
]
else:
devices = hass.data[DATA_MONOPRICE]
for device in devices:
if service.service == SERVICE_SNAPSHOT:
| device.snapshot()
elif service.service == SERVICE_RESTORE:
device.restore()
hass.services.register(
DOMAIN, SERVICE_SNAPSHOT, service_handle, schema=MEDIA_PLAYER_SCHEMA
)
hass.services.register(
DOMAIN, SERVICE_RESTORE, service_handle, schema=MEDIA_PLAYER_SCHEMA
)
class MonopriceZone(MediaPlayerDevice):
"""Representation of a Monoprice amplifier zone."""
def __init__(self, monoprice, sources, zone_id, zone_name):
| """Initialize new zone."""
self._monoprice = monoprice
# dict source_id -> source name
self._source_id_name = sources
# dict source name -> source_id
self._source_name_id = {v: k for k, v in sources.items()}
# ordered list of all source names
self._source_names = sorted(
self._source_name_id.keys(), key=lambda v: self._source_name_id[v]
)
self._zone_id = zone_id
self._name = zone_name
self._snapshot = None
self._state = None
self._volume = None
self._source = None
self._mute = None
def update(self):
"""Retrieve latest state."""
state = self._monoprice.zone_status(self._zone_id)
if not state:
return False
self._state = STATE_ON if state.power else STATE_OFF
self._volume = state.volume
self._mute = state.mute
idx = state.source
if idx in self._source_id_name:
self._source = self._source_id_name[idx]
else:
self._source = None
return True
@property
def name(self):
"""Return the name of the zone."""
return self._name
@property
def state(self):
"""Return the state of the zone."""
return self._state
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
if self._volume is None:
return None
return self._volume / 38.0
@property
def is_volume_muted(self):
"""Boolean if volume is currently muted."""
return self._mute
@property
def supported_features(self):
"""Return flag of media commands that are supported."""
return SUPPORT_MONOPRICE
@property
def media_title(self):
"""Return the current source as medial title."""
return self._source
@property
def source(self):
"""Return the current input source of the device."""
return self._source
@property
def source_list(self):
"""List of available input sources."""
return self._source_names
def snapshot(self):
"""Save zone's current state."""
self._snapshot = self._monoprice.zone_status(self._zone_id)
def restore(self):
"""Restore saved state."""
if self._snapshot:
self._monoprice.restore_zone(self._snapshot)
self.schedule_update_ha_state(True)
def select_source(self, source):
"""Set input source."""
if source not in self._source_name_id:
return
idx = self._source_name_id[source]
self._monoprice.set_source(self._zone_id, idx)
def turn_on(self):
"""Turn the media player on."""
self._monoprice.set_power(self._zone_id, True)
def turn_off(self):
"""Turn the media player off."""
self._monoprice.set_power(self._zone_id, False)
def mute_volume(self, mute):
"""Mute (true) or unmute (false) media player."""
self._monoprice.set_mute(self._zone_id, mute)
def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
self._monoprice.set_volume(self._zone_id, int(volume * 38))
def volume_up(self):
"""Volume up the media player."""
if self._volume is None:
return
self._monoprice.set_volume(self._zone_id, min(self._volume + 1, 38))
def volume_down(self):
"""Volume down media player."""
if self._volume is None:
return
self._monoprice.set_volume(self._zone_id, max(self._volume - 1, 0))
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-13 18:08
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='ProxyGrantingTicket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('session_key', models.CharField(blank=True, max_length=255, null=True)),
('pgtiou', models.CharField(blank=True, max_length=255, null=True)),
('pgt', models.CharField(blank=True, max_length=255, null=True)),
('date', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='SessionTicket',
fields=[
('id', models.AutoField(auto_created=True, prima | ry_key=True, serialize=False, verbose_name='ID')),
('session_key', models.CharField(max_length=255)),
('ticket', models.CharField(max_length=255)),
],
),
migrations.AlterUniqueTogether(
name='proxygrantingticket',
unique_together | =set([('session_key', 'user')]),
),
]
|
from numpy.testing import *
import numpy as np
import lulu
import lulu.connected_region_handler as crh
class TestLULU:
img = np.zeros((5, 5)).astype(int)
img[0, 0:5] = 0
img[:, 4] = 1
img[1:3, 1:4] = 2
"""
[[0 0 0 0 1]
[0 2 2 2 1]
[0 2 2 2 1]
[0 0 0 0 1]
[0 0 0 0 1]]
"""
def test_connected_regions(self):
labels, regions = lulu.c | onnected_regions(self.img)
assert_array_equal(labels, self.img)
assert_equal(len(regions), 3)
crh.set_value(regions[0], 5)
assert_array_equal(crh.todense(regions[0]),
[[5, 5, 5, 5, 0],
[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0],
| [5, 5, 5, 5, 0],
[5, 5, 5, 5, 0]])
assert_array_equal(crh.todense(regions[1]),
[[0, 0, 0, 0, 1],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 1]])
assert_array_equal(crh.todense(regions[2]),
[[0, 0, 0, 0, 0],
[0, 2, 2, 2, 0],
[0, 2, 2, 2, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
class TestReconstruction:
def test_basic(self):
img = np.random.randint(255, size=(200, 200))
pulses = lulu.decompose(img)
img_, areas, area_count = lulu.reconstruct(pulses, img.shape)
# Write assert this way so that we can see how many
# pixels mismatch as a percent of the total nr of pixels
assert_array_equal(img_, img)
assert_equal(np.sum(img_ != img) / float(np.prod(img.shape)) * 100,
0, "Percentage mismatch =")
if __name__ == "__main__":
run_module_suite()
|
#!/usr/bin/env python
from hts_barcode_checker import Taxon, TaxonDB
import logging, datetime, argparse, sqlite3
# NCBI taxonomy tree database 10.6084/m9.figshare.4620733
parser = argparse.ArgumentParser(description = 'Create a table containing the CITES species')
parser.add_argument('-db', '--CITES_db', metavar='CITES database name', dest='db',type=str,
help='Name and path to the output location for the CITES database')
parser.add_argument('-csv', '--CITES_dump', metavar='CITES CSV dump', dest='dmp', type=str,
help='Location of the CSV dump downloaded from CITES')
parser.add_argument('-ncbi', '--NCBI_taxonomy', metavar='NCBI taxonomy tree database', dest='n', type=str,
help='Location of sqlite database with NCBI taxonomy tree')
parser.add_argument('-l', '--logging', metavar='log level', dest='l', type=str,
help = 'Set log level to: debug, info, warning (default) or critical see readme for more details.', default='warning')
parser.add_argument('-lf', '--log_file', metavar='log file', dest='lf', type=str,
help = 'Path to the log file')
args = parser.parse_args()
def main ():
# configure logger
log_level = getattr(logging, args.l.upper(), None)
log_format = '%(funcName)s [%(lineno)d]: %(levelname)s: %(message)s'
if not isinstance(log_level, int):
raise ValueError('Invalid log level: %s' % loglevel)
return
if args.lf == '':
logging.basicConfig(format=log_format, level=log_level)
else:
| logging.basicConfig(filename=args.lf, filemode='a', format=log_format, level=log_level)
# instantiate DB object, parse CITES dump
db = TaxonDB(date=str(datetime.datetime.now()))
db.from_dump(args.dmp)
# configure local sqlite database
conn = sqlite3.connect(args.n)
curr = conn.cursor()
# iterate over parsed taxa, resolve NCBI taxid and expand higher taxa
counter = 1
expanded = []
for taxon in db.taxa:
taxon.tnrs(cursor=curr)
result = ta | xon.expand(cursor=curr)
for taxid in result.keys():
expanded.append(Taxon(
appendix=taxon.appendix,
name=taxon.name,
description=taxon.description,
footnotes=taxon.footnotes,
ncbi={taxid:result[taxid]}
))
logging.info('%d/%d' % ( counter, len(db.taxa) ))
counter += 1
# write output
for taxon in expanded:
db.taxa.append(taxon)
handle = open(args.db, 'w')
db.to_csv(handle)
handle.close()
if __name__ == "__main__":
main()
|
{
'name':
'client_referred_to_backend_%s_short_stream_%s' %
(transport_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
}],
'backend_configs': [{
'transport_sec': backend_sec,
}],
'fallback_configs': [],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_referred_to_backend()
def generate_client_referred_to_backend_fallback_broken():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in ['alts', 'tls', 'google_default_credentials']:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = []
if transport_sec == 'tls':
skip_langs += ['java']
if balancer_short_stream:
skip_langs += ['java']
config = {
'name':
'client_referred_to_backend_fallback_broken_%s_short_stream_%s'
% (transport_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
}],
'backend_configs': [{
'transport_sec': backend_sec,
}],
'fallback_configs': [{
'transport_sec': 'insecure',
}],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_referred_to_backend_fallback_broken()
def generate_client_referred_to_backend_multiple_backends():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in [
'insecure', 'alts', 'tls', 'google_default_credentials'
]:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = []
if transport_sec == 'tls':
skip_langs += ['java']
if balancer_short_stream:
skip_langs += ['java']
config = {
'name':
'client_referred_to_backend_multiple_backends_%s_short_stream_%s'
% (transport_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
}],
'backend_configs': [{
'transport_sec': backend_sec,
}, {
'transport_sec': backend_sec,
}, {
'transport_sec': backend_sec,
}, {
'transport_sec': backend_sec,
}, {
'transport_sec': backend_sec,
}],
'fallback_configs': [],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_referred_to_backend_multiple_backends()
def generate_client_falls_back_because_no_backends():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in [
'insecure', 'alts', 'tls', 'google_default_credentials'
]:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = ['go', 'java']
if transport_sec == 'tls':
skip_langs += ['java']
if balancer_short_stream:
skip_langs += ['java']
config = {
'name':
'client_falls_back_because_no_backends_%s_short_stream_%s' %
(transport_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
}],
'backend_configs': [],
'fallback_configs': [{
'transport_sec': fallback_sec,
}],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_falls_back_because_no_backends()
def generate_client_falls_back_because_balancer_connection_broken():
all_configs = []
for transport_sec in ['alts', 'tls', 'google_default_credentials']:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = []
if transport_sec == 'tls':
skip_langs = ['java']
config = {
'name':
'client_falls_back_because_balancer_connection_broken_%s' %
transport_sec,
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': 'insecure',
'short_stream': False,
}],
'backend_configs': [],
'fallback_configs': [{
'transport_sec': fallback_sec,
}],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_falls_back_because_balancer_connection_broken()
def generate_client_referred_to_backend_multiple_balancers():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in [
'insecure', 'alts', 'tls', 'google_default_credentials'
]:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = []
| if transport_sec == 'tls':
skip_langs += ['java']
if balancer_short_stream:
skip_langs += ['java']
config = {
'name':
'client_referred_to_backend_multiple_balancers_%s_short_stream_%s'
% (trans | port_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
],
'backend_configs': [{
'transport_se |
# postgresql/ext.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is r | eleased under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from ...sql import expression
from ...sql import elements
from ...sql import functions
from ...sql.schema import ColumnCollectionConstraint
from .array import ARRAY
class aggregate_order_by(expression.ColumnElement):
"""Represent a Postgresql aggregate order by expression.
E.g.::
from sqlalchemy.dialects.postgresql import aggregate_order_by
| expr = func.array_agg(aggregate_order_by(table.c.a, table.c.b.desc()))
stmt = select([expr])
would represent the expression::
SELECT array_agg(a ORDER BY b DESC) FROM table;
Similarly::
expr = func.string_agg(
table.c.a,
aggregate_order_by(literal_column("','"), table.c.a)
)
stmt = select([expr])
Would represent::
SELECT string_agg(a, ',' ORDER BY a) FROM table;
.. versionadded:: 1.1
.. seealso::
:class:`.array_agg`
"""
__visit_name__ = 'aggregate_order_by'
def __init__(self, target, order_by):
self.target = elements._literal_as_binds(target)
self.order_by = elements._literal_as_binds(order_by)
def self_group(self, against=None):
return self
def get_children(self, **kwargs):
return self.target, self.order_by
def _copy_internals(self, clone=elements._clone, **kw):
self.target = clone(self.target, **kw)
self.order_by = clone(self.order_by, **kw)
@property
def _from_objects(self):
return self.target._from_objects + self.order_by._from_objects
class ExcludeConstraint(ColumnCollectionConstraint):
"""A table-level EXCLUDE constraint.
Defines an EXCLUDE constraint as described in the `postgres
documentation`__.
__ http://www.postgresql.org/docs/9.0/\
static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE
"""
__visit_name__ = 'exclude_constraint'
where = None
def __init__(self, *elements, **kw):
"""
:param \*elements:
A sequence of two tuples of the form ``(column, operator)`` where
column must be a column name or Column object and operator must
be a string containing the operator to use.
:param name:
Optional, the in-database name of this constraint.
:param deferrable:
Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
issuing DDL for this constraint.
:param initially:
Optional string. If set, emit INITIALLY <value> when issuing DDL
for this constraint.
:param using:
Optional string. If set, emit USING <index_method> when issuing DDL
for this constraint. Defaults to 'gist'.
:param where:
Optional string. If set, emit WHERE <predicate> when issuing DDL
for this constraint.
"""
columns = []
render_exprs = []
self.operators = {}
expressions, operators = zip(*elements)
for (expr, column, strname, add_element), operator in zip(
self._extract_col_expression_collection(expressions),
operators
):
if add_element is not None:
columns.append(add_element)
name = column.name if column is not None else strname
if name is not None:
# backwards compat
self.operators[name] = operator
expr = expression._literal_as_text(expr)
render_exprs.append(
(expr, name, operator)
)
self._render_exprs = render_exprs
ColumnCollectionConstraint.__init__(
self,
*columns,
name=kw.get('name'),
deferrable=kw.get('deferrable'),
initially=kw.get('initially')
)
self.using = kw.get('using', 'gist')
where = kw.get('where')
if where is not None:
self.where = expression._literal_as_text(where)
def copy(self, **kw):
elements = [(col, self.operators[col])
for col in self.columns.keys()]
c = self.__class__(*elements,
name=self.name,
deferrable=self.deferrable,
initially=self.initially)
c.dispatch._update(self.dispatch)
return c
def array_agg(*arg, **kw):
"""Postgresql-specific form of :class:`.array_agg`, ensures
return type is :class:`.postgresql.ARRAY` and not
the plain :class:`.types.ARRAY`.
.. versionadded:: 1.1
"""
kw['type_'] = ARRAY(functions._type_from_args(arg))
return functions.func.array_agg(*arg, **kw)
|
#
"""test_python_compat - Python output compatibility tests"""
# Copyright © 2012-2018 James Rowe <jnrowe@gmail.com>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of versionah.
#
# versionah is free software: you can redistribute it a | nd/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.
#
# versionah 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
# versionah. If not, see <http://www.gnu.org/licenses/>.
from os import getenv
from shutil import which
from subprocess import PIPE, call
from pytest import mark, skip
from versionah.cmdline import CliVersion
@mark.requires_exec
@mark.requires_write
@mark.parametrize('interp', [
'python2.6',
'python2.7',
'python3.2',
'python3.3',
])
def test_python_compatibility(interp, tmpdir):
if not which(interp):
skip('Interpreter {!r} unavailable'.format(interp))
file_loc = tmpdir.join('test_wr.py').strpath
CliVersion('1.0.1').write(file_loc, 'py')
retval = call([interp, '-W', 'all', file_loc], stdout=PIPE,
stderr=PIPE)
assert retval == 0
# Test interps not available on travis-ci.org, but available on all our test
# machines
@mark.skipif(getenv('TRAVIS_PYTHON_VERSION'), reason='Unavailable on travis')
@mark.requires_exec
@mark.requires_write
@mark.parametrize('interp', [
'python2.4',
'python2.5',
'python3.1',
'python3.4',
])
def test_python_compatibility_extra(interp):
if not which(interp):
skip('Interpreter {!r} unavailable'.format(interp))
test_python_compatibility(interp)
|
''' Test bug 389: http://bugs.openbossa.org/show_bug | .cgi?id=389'''
import sys
import unittest
from helper import UsesQApplication
from PySide import QtCore,QtGui
class BugTest(UsesQApplication):
def testCase(self):
s = QtGui.QWidget().style()
i = s.standardIcon(QtGui.QStyle.SP_TitleBarMinButton)
self.assertEqual(type(i), QtGui.QIcon)
|
if __name__ == '__main__':
unittest.main()
|
from django.contrib import admin
from models import *
from cards. | actions import export_as_xls
class ScanAdmin(admin.ModelAdmin):
list_filter = ['readerLocation', 'added']
search_fields = ['card__code']
# Register your models here.
admin.site.register(Batch)
admin.site.register(Card)
admin.site.register(Reader)
admin.site.register(Location)
admin.site.register(ReaderLocation)
admin.site.register(Scan, ScanAdmin)
class MyAdmin(admin.ModelAdmin):
actions = [export_as_xls]
admin.site.add_actio | n(export_as_xls)
|
from django.contrib. | auth.backends import ModelBackend
from django.contrib.sites.models import Site
from socialregistration.contrib.twitter.models import TwitterProfile
class TwitterAuth(ModelBackend):
def authenticate(self, twitter_id=None):
try:
return TwitterProfile.objects.get(
twitter_id=twitter_id,
site=Site.objects.get_current()
).user
except TwitterProfile.DoesNotExist:
| return None
|
import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.AnyValidator):
def __init_ | _(self, plotly_name="size", parent_name="histogram2d.xbins", **kwargs):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs
| )
|
info=[]
for line in open('./info_mappable_50.txt').read().rstrip().split('\n'):
a=line.split('\t')
info.append(a[0])
line_out=''
line_out2=''
seq=''
index=0
for line in open('./seqList_mappable_50.fa'):
if line[0]=='>':
if seq:
replace=seq[7:-7]
| if replace!=ref:
print header
seq_alt=seq[:7]+alt+seq[-7:]
line_out+='>'+header+'_ref'+'\n'+seq+'\n'
line_out2+='>'+header+'_alt'+'\n'+seq_alt+'\n'
header=info[index]
ref_alt=header.split('_')[1]
[ref,alt]=re | f_alt.split('>')
index+=1
seq=''
if index/1000000==index/1000000.0:
print index
else:
seq+=line.split('\n')[0]
if seq:
replace=seq[7:-7]
if replace!=ref:
print header
seq_alt=seq[:7]+alt+seq[-7:]
line_out+='>'+header+'_ref'+'\n'+seq+'\n'
line_out2+='>'+header+'_alt'+'\n'+seq_alt+'\n'
open('./seqList_mappable_50_ref.fa','wb').write(line_out)
open('./seqList_mappable_50_alt.fa','wb').write(line_out2)
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "clone.settings")
from django.co | re.management import execute_from_command_line
execute_from_command_line(sys.ar | gv)
|
# coding: utf8
# OeQ autogenerated lookup function for 'Window/Wall Ratio East in correlation to year of construction, based on the source data of the survey for the "German Building Typology developed by the "Institut für Wohnen und Umwelt", Darmstadt/Germany, 2011-2013'
import math
import numpy as np
import oeqLookuptable as oeq
def get(*xin):
l_lookup = oeq.lookuptable(
[
1849,0.031,
1850,0.031,
1851,0.03,
1852,0.027,
1853,0.024,
1854,0.025,
1855,0.03,
1856,0.042,
1857,0.06,
1858,0.082,
1859,0.105,
1860,0.128,
1861,0.15,
1862,0.168,
1863,0.18,
1864,0.18,
1865,0.18,
1866,0.18,
1867,0.18,
1868,0.179,
1869,0.179,
1870,0.179,
1871,0.18,
1872,0.18,
1873,0.18,
1874,0.18,
1875,0.18,
1876,0.18,
1877,0.18,
1878,0.18,
1879,0.18,
1880,0.18,
1881,0.18,
1882,0.18,
1883,0.18,
1884,0.18,
1885,0.18,
1886,0.18,
1887,0.18,
1888,0.18,
1889,0.18,
1890,0.18,
1891,0.18,
1892,0.18,
1893,0.18,
1894,0.18,
1895,0.18,
1896,0.18,
1897,0.18,
1898,0.18,
1899,0.18,
1900,0.18,
1901,0.18,
1902,0.18,
1903,0.18,
1904,0.18,
1905,0.18,
1906,0.18,
1907,0.18,
1908,0.179,
1909,0.179,
1910,0.179,
1911,0.18,
1912,0.18,
1913,0.18,
1914,0.18,
1915,0.18,
1916,0.168,
1917,0.15,
1918,0.128,
1919,0.105,
1920,0.082,
1921,0.06,
1922,0.042,
1923,0.03,
1924,0.025,
1925,0.024,
1926,0.027,
1927,0.03,
1928,0.031,
1929,0.031,
1930,0.031,
1931,0.03,
1932,0.03,
1933,0.03,
1934,0.03,
1935,0.03,
1936,0.03,
1937,0.03,
1938,0.03,
1939,0.03,
194 | 0,0.03,
1941,0.03,
1942,0.03,
1943,0.03,
1944,0.03,
1945,0.03,
1946,0.029,
1947,0.026,
1948,0.02,
1949,0.012,
1950,0.003,
1951,0,
1952,0,
1953,0,
1954,0.014,
1955,0.036,
1956,0.062,
1957,0.09,
1958,0.118,
1959,0.144,
1960,0.165,
1961,0.18,
1962,0.18,
1963,0.18,
1964,0.18,
1965,0.18,
1966,0.173 | ,
1967,0.166,
1968,0.158,
1969,0.15,
1970,0.141,
1971,0.133,
1972,0.125,
1973,0.12,
1974,0.118,
1975,0.117,
1976,0.118,
1977,0.12,
1978,0.121,
1979,0.12,
1980,0.113,
1981,0.1,
1982,0.078,
1983,0.053,
1984,0.028,
1985,0.01,
1986,0.002,
1987,0.002,
1988,0.006,
1989,0.01,
1990,0.011,
1991,0.01,
1992,0.009,
1993,0.01,
1994,0.013,
1995,0.019,
1996,0.025,
1997,0.03,
1998,0.034,
1999,0.036,
2000,0.038,
2001,0.04,
2002,0.043,
2003,0.045,
2004,0.048,
2005,0.05,
2006,0.051,
2007,0.051,
2008,0.05,
2009,0.05,
2010,0.05,
2011,0.05,
2012,0.05,
2013,0.05,
2014,0.05,
2015,0.05,
2016,0.05,
2017,0.05,
2018,0.05,
2019,0.05,
2020,0.05,
2021,0.05])
return(l_lookup.lookup(xin))
|
try:
from django.contrib.auth.tests.utils import skipIfCustomUser
except ImportError:
| def skipIfCustomU | ser(wrapped):
return wrapped
|
rmitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of ytranslate nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""This file contains the SharpEditor class."""
import wx
from ytranslate.tools import t
class SharpEditor(wx.Panel):
"""SharpScript editor panel.
This panel can be added into dialogs that have to support SharpScript
editing. On the top, at the left of the panel, is an optional
text field to edit SharpScript directly. To the right is a list
of functions already associated with this entry. After buttons
to edit and remove is a second list with new functions to be added.
"""
def __init__(self, dialog, engine, sharp, object, attribute,
text=False, escape=False):
"""Creates the frame.
Arguments:
dialog: the parent dialog.
engine: the game engine.
sharp: the SharpScript engine.
object: the object containing the field to be edited.
attribute: the attribute's name of the object to edit.
text (default to False): should a text field be added?
escape (default to false): the #send calls are removed.
If the SharpEditor is to modify a trigger, for instance,
particularly its "action" attribute, the trigger is the object
and "action" is the attribute's name.
"""
wx.Panel.__init__(self, dialog)
self.engine = engine
self.sharp_engine = sharp
self.object = object
self.attribute = attribute
self.text = None
self.escape = escape
script = getattr(self.object, self.attribute)
self.functions = sorted(sharp.functions.values(),
key=lambda function: function.name)
self.functions = [f for f in self.functions if f.description]
# Shape
sizer = wx.BoxSizer(wx.VERTICAL)
top = wx.BoxSizer(wx.HORIZONTAL)
bottom = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(sizer)
# Insert a text field
if text:
s_text = wx.BoxSizer(wx.VERTICAL)
l_text = wx.StaticText(self, label=t("common.action"))
t_text = wx.TextCtrl(self, value=script, style=wx.TE_MULTILINE)
self.text = t_text
s_text.Add(l_text)
s_text.Add(t_text)
top.Add(s_text)
# List of current functions
self.existing = wx.ListCtrl(self,
style=wx.LC_REPORT | wx.LC_SINGLE_SEL)
self.existing.InsertColumn(0, t("common.action"))
# Buttons
self.edit = wx.Button(self, label=t("ui.button.edit"))
self.remove = wx.Button(self, label=t("ui.button.remove"))
top.Add(self.existing)
top.Add(self.edit)
top.Add(self.remove)
self.populate_existing()
# List of functions
self.choices = wx.ListCtrl(self, style=wx.LC_REPORT | wx.LC_SINGLE_SEL)
self.choices.InsertColumn(0, t("common.description"))
self.populate_list()
bottom.Add(self.choices)
# Add button
self.add = wx.Button(self, label=t("ui.button.add_action"))
bottom.Add(self.add)
# Event binding
self.add.Bind(wx.EVT_BUTTON, self.OnAdd)
self.edit.Bind(wx.EVT_BUTTON, self.OnEdit)
self.remove.Bind(wx.EVT_BUTTON, self.OnRemove)
def populate_list(self):
"""Populate the list with function names."""
self.choices.DeleteAllItems()
for function in self.functions:
try:
description = t("sharp.{name}.description".format(
name=function.name))
except ValueError:
description = function.description
self.choices.Append((description, ))
self.choices.Select(0)
self.choices.Focus(0)
def populate_existing(self):
"""Populate the list with existing functions."""
self.existing.DeleteAllItems()
script = getattr(self.object, self.attribute)
if self.text:
self.text.SetValue(script)
lines = self.sharp_engine.format(script, return_str=False)
for line in lines:
self.existing.Append((line, ))
self.existing.Select(0)
self.existing.Focus(0)
if lines:
self.existing.Enable()
self.edit.Enable()
self.remove.Enable()
else:
self.existing.Disable()
self.edit.Disable()
self.remove.Disable()
def OnAdd(self, e):
"""The 'add' button is pressed."""
index = self.choices.GetFirstSelected()
try:
function = self.functions[index] |
except IndexError:
wx.MessageBox(t("ui.message.sharp.missing"),
t("ui.message.error"), wx.OK | wx.ICON_ERROR)
else:
| dialog = AddEditFunctionDialog(self.engine, self.sharp_engine,
function, self.object, self.attribute, escape=self.escape)
dialog.ShowModal()
self.populate_existing()
self.existing.SetFocus()
def OnEdit(self, e):
"""The 'edit' button is pressed."""
index = self.existing.GetFirstSelected()
script = getattr(self.object, self.attribute)
lines = self.sharp_engine.format(script, return_str=False)
try:
line = lines[index]
except IndexError:
wx.MessageBox(t("ui.message.sharp.missing"),
t("ui.message.error"), wx.OK | wx.ICON_ERROR)
else:
name, arguments, flags = self.sharp_engine.extract_arguments(line)
function = self.sharp_engine.functions[name[1:]]
dialog = AddEditFunctionDialog(self.engine, self.sharp_engine,
function, self.object, self.attribute, index,
escape=self.escape)
dialog.ShowModal()
self.populate_existing()
self.existing.SetFocus()
def OnRemove(self, e):
"""The 'remove' button is pressed."""
index = self.existing.GetFirstSelected()
script = getattr(self.object, self.attribute)
lines = self.sharp_engine.format(script, return_str=False)
try:
line = lines[index]
except IndexError:
wx.MessageBox(t("ui.message.sharp.missing"),
t("ui.message.error"), wx.OK | wx.ICON_ERROR)
else:
value = wx.MessageBox(t("ui.message.sharp.remove",
line=line), t("ui.alert.confirm"),
wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
if value == wx.YES:
del lines[index]
content = "\n".join(lines)
setattr(self.object, self.attribute, content)
self.populate_existing()
self.existing.SetFocus()
class AddEditFunctionDialog(wx.Dialog):
|
try:
import exceptions
except ImportError: # Python 3
import builtins as exceptions
class ObjectToReturn:
| def __init__(s | elf, name):
self.name = name
def __str__(self):
return self.name
def exception(self, name, msg=""):
exception = getattr(exceptions, name)
raise exception(msg)
|
# encoding: utf-8
"""
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase
class ObjCDataFormatterNSError(ObjCDataFormatterTestCase):
@skipUnlessDarwin
def test_nserror_with_run_command(self):
"""Test formatters for NSError."""
self.appkit_tester_impl(self.nserror_data_formatter_commands)
def nserror_data_formatter_commands(self):
self.expect(
'frame variable nserror', substrs=['domain: @"F | oobar" - code: 12'])
self.expect(
'frame variable nserrorptr',
substrs=['domain: @"Foobar" - code: 12'])
self.expect(
'frame variable nserror->_userInfo', substrs=['2 key/value pairs'])
self.expect(
'frame variable nserror->_us | erInfo --ptr-depth 1 -d run-target',
substrs=['@"a"', '@"b"', "1", "2"])
|
from app import write_entries
import datetime
import ra | ndom
ts = datetime.datetime.now().strftime("%Y-%m-%d%H:%M-%S")
offset = random.randrange(0, 1475)
print("Enter user=%s" % ts)
print("Enter email=%s" % offset)
prime = write_entries.delay(ts, offset)
| |
fro | m enum import Enum
class ImageAlignType(Enum):
"""Image alignment"""
Default = 1
Left = 2
Right = 3
Cente | r = 4
|
import decor
from flask import Blueprint, redirect, request, url_for
import os, json
def construct_bp(gcal, JSON_DENT):
ALLOWED_ORIGIN = "*"
# JSON_DENT = 4
gcal_api = Blueprint('gcal_api', __name__, url_prefix="/gcal")
# GOOGLE CALENDAR API Routes
# Authenication routes
@gcal_api.route('/auth2callback')
def gauth_callback():
return redirect(gcal.auth_callback(request.args.get('code')))
@gcal_api.route('/gauth')
def gauth_call():
return redirect(gcal.get_auth_uri())
@gcal_api.route('/isauth')
def gauth_isauth():
return json.dumps({'is_needed': not gcal.need_auth()})
@gcal_api.route('/istblexist')
def gauth_istblex():
return json.dumps({'is_exist': gcal.if_cal_tbl()})
@gcal_api.route('/deauth')
def gauth_deauth():
return redirect(gcal.deauth_usr())
# Get todays events
@gcal_api.route('/today', methods=['GET','OPTIONS'])
@decor.crossdomain(origin=ALLOWED_ORIGIN)
def gcal_today():
return json.dumps(gcal.get_today(), indent=JSON_DENT)
# Get calendars
@gcal_api.route('/calendars', methods=['GET','OPTIONS'])
@decor.crossdomain(origin=ALLOWED_ORIGIN)
def gcal_cals():
return json.dumps(gcal.get_cals(), indent=JSON_DENT)
# Save calendars
@gcal_api.route('/add/calendars', methods=['POST','OPTIONS'])
@decor.crossdomain(origin=ALLOWED_ORIGIN)
def gcal_save_cals():
# print request.form.getlist('ids[]')
gcal.add_cals(request.form.getlist('ids[]'))
# | print request.form
redirect(url_for('setcal' | ))
# return json.dumps(gcal.get_ucals(), indent=JSON_DENT)
return '<meta http-equiv="refresh" content ="0; URL=http://localhost:5000/setcal">'
# Get todays events
@gcal_api.route('/mail', methods=['GET'])
def gcal_mail():
return json.dumps(gcal.get_mail(), indent=JSON_DENT)
# === JSON Error Handling ===
# @gcal_api.errorhandler(400)
# def err_400(e):
# return '{"status": 400, "message":"Bad request"}', 400
@gcal_api.errorhandler(404)
def err_404(e):
return '{"status": 404, "message":"Page not found"}', 404
@gcal_api.errorhandler(500)
def err_500(e):
return '{"status": 500, "message":"Internal server error"}', 500
return gcal_api
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource. | org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@google | groups.com
from thumbor.filters import BaseFilter, filter_method
from thumbor.utils import logger
ALLOWED_FORMATS = ["png", "jpeg", "jpg", "gif", "webp"]
class Filter(BaseFilter):
@filter_method(BaseFilter.String)
async def format(self, file_format):
if file_format.lower() not in ALLOWED_FORMATS:
logger.debug("Format not allowed: %s", file_format.lower())
self.context.request.format = None
else:
logger.debug("Format specified: %s", file_format.lower())
self.context.request.format = file_format.lower()
|
import numpy as np
import json
import scipy as sci
def get_decimal_delta(data, index,decimals):
'''
This function calculates the difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:param decimals: Number of decimal places to round to (default: 0).
If decimals is negative, it specifies the number of positions to the left of the decimal point.
:return: a list of distances between all values in the column
'''
res = []
for t1, t2 in zip(data[:-1,int(index)], data[1:,int(index)]):
res.append(np.around(np.float64(t2) - np.float64(t1),decimals))
return np.array(res)
def get_delta(data, index):
'''
This function calculates the difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:param decimals: Number of decimal places to round to (default: 0).
If decimals is negative, it specifies the number of positions to the left of the decimal point.
:return: a list of distances between all values in the column
'''
realsol = []
i=1
while i < len(data[0:,index]):
intervall = data[i, index] - data[i - 1,index]
realsol.append(intervall)
i += 1
realsol = np.array(realsol)
return realsol
def get_average_delta(data, index):
'''
This function calculates the average difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:return: average between all values in the column
'''
deltas = get_decimal_delta(data, index, 7)
return sum(deltas) / len(deltas)
def numerical_approx(data, diff_Value1_Index, diff_Value2_Index = 0):
'''
This method derives one Data Column by another
Zeitwerte
Example: d Speed / d Time = Acceleration
:param data: the pandas DataFrame of the data
:param diff_Value1_Index: Index of the Column to get the derivative of
:param diff_Value2_Index: Index of the deriving Column (Usually the Time index)
:return:
'''
diff_Value = []
diff_Value.append(np.float_(0.000))
data = np.array(json.loads(data), dtype=np.float64)
for v1, t1 in zip(get_delta(data, int(diff_Value1_Index)), get_delta(da | ta, int(diff_Value2_Index))):
diff_Value.append(v1 / t1)
return np.asarray(diff_Value)
def trapez_for_each(data, index_x, index_y):
"""
This method integrates the given Values with the Trapeziodal Rule
:param index_x: index der X Achse
:param index_y: index der Y Achse
:return: integrated Values from x,y
"""
i = 1
sol = []
data =np.array(json | .loads(data),dtype=np.float64)
#data =np.array(json.loads(data),dtype=np.float_)
while i < len(data[:,index_x]):
res = sci.trapz(data[0:i, index_y], data[0:i, index_x])
res = np.float_(res)
sol.append(res)
i += 1
i = 0
realsol = []
while i < len(sol):
intervall = sol[i] - sol[i - 1]
if i == 0:
realsol.append(np.float_(0))
realsol.append(intervall)
i += 1
realsol= np.array(realsol)
return realsol
|
import Adafruit_BBIO | .GPIO as GPIO
import time
a=0
b=0
def derecha(channel):
global a
a+=1
print 'cuenta derecha es {0}'.format(a)
def izquierda(channel):
global b
b+=1
print 'cuenta izquierda es {0}'.format(b)
GPIO.setup("P9_11", GPIO.IN)
GPIO.setup("P9_13", GPIO.IN)
GPIO.add_event_detect("P9_11", GPIO.BOTH)
GPIO.add_event_detect("P9_13", GPIO.BOTH)
GPI | O.add_event_callback("P9_11",derecha)
GPIO.add_event_callback("P9_13",izquierda)
#if GPIO.event_detected("GPIO_31"):
# print "event detected"
while True:
print "cosas pasan"
time.sleep(1)
|
, 'compare_genome_features']
async_check_methods['GenomeFeatureComparator.compare_genome_features_check'] = ['GenomeFeatureComparator', 'compare_genome_features']
class AsyncJobServiceClient(object):
def __init__(self, timeout=30 * 60, token=None,
ignore_authrc=True, trust_all_ssl_certificates=False):
url = environ.get('KB_JOB_SERVICE_URL', None)
if url is None and config is not None:
url = config.get('job-service-url')
if url is None:
raise ValueError('Neither \'job-service-url\' parameter is defined in '+
'configuration nor \'KB_JOB_SERVICE_URL\' variable is defined in system')
scheme, _, _, _, _, _ = _urlparse.urlparse(url)
if scheme not in ['http', 'https']:
raise ValueError(url + " isn't a valid http url")
self.url = url
self.timeout = int(timeout)
self._headers = dict()
self.trust_all_ssl_certificates = trust_all_ssl_certificates
if token is None:
raise ValueError('Authentication is required for async methods')
self._headers['AUTHORIZATION'] = token
if self.timeout < 1:
raise ValueError('Timeout value must be at least 1 second')
def _call(self, method, params, json_rpc_call_context = None):
arg_hash = {'method': method,
'params': params,
'version': '1.1',
'id': str(_random.random())[2:]
}
if json_rpc_call_context:
arg_hash['context'] = json_rpc_call_context
body = json.dumps(arg_hash, cls=JSONObjectEncoder)
ret = _requests.post(self.url, data=body, headers=self._headers,
timeout=self.timeout,
verify=not self.trust_all_ssl_certificates)
if ret.status_code == _requests.codes.server_error:
if 'content-type' in ret.headers and ret.headers['content-type'] == 'application/json':
err = json.loads(ret.text)
if 'error' in err:
raise ServerError(**err['error'])
else:
raise ServerError('Unknown', 0, ret.text)
else:
raise ServerError('Unknown', 0, ret.text)
if ret.status_code != _requests.codes.OK:
ret.raise_for_status()
resp = json.loads(ret.text)
if 'result' not in resp:
raise ServerError('Unknown', 0, 'An unknown server error occurred')
return resp['result']
def run_job(self, run_job_params, json_rpc_call_context = None):
return self._call('KBaseJobService.run_job', [run_job_params], json_rpc_call_context)[0]
def check_job(self, job_id, json_rpc_call_context = None):
return self._call('KBaseJobService.check_job', [job_id], json_rpc_call_context)[0]
class JSONRPCServiceCustom(JSONRPCService):
def call(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = self.call_py(ctx, jsondata)
if result is not None:
return json.dumps(result, cls=JSONObjectEncoder)
return None
def _call_method(self, ctx, request):
"""Calls given method with given params and retu | rns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method) - 1:
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
| if(not self._vargs(method) and len(params) >
self._max_args(method) - 1):
raise InvalidParamsError('too many arguments')
result = method(ctx, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = method(ctx, **params)
else: # No params
result = method(ctx)
except JSONRPCError:
raise
except Exception as e:
# log.exception('method %s threw an exception' % request['method'])
# Exception was raised inside the method.
newerr = ServerError()
newerr.trace = traceback.format_exc()
newerr.data = e.message
raise newerr
return result
def call_py(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
rdata = jsondata
# we already deserialize the json string earlier in the server code, no
# need to do it again
# try:
# rdata = json.loads(jsondata)
# except ValueError:
# raise ParseError
# set some default values for error handling
request = self._get_default_vals()
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = self._handle_request(ctx, request)
# Don't respond to notifications
if respond is None:
return None
return respond
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
self._fill_request(request_, rdata_)
requests.append(request_)
for request_ in requests:
respond = self._handle_request(ctx, request_)
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
return responds
# Nothing to respond.
return None
else:
# empty dict, list or wrong type
raise InvalidRequestError
def _handle_request(self, ctx, request):
"""Handles given request and returns its response."""
if self.method_data[request['method']].has_key('types'): # @IgnorePep8
self._validate_params_types(request['method'], request['params'])
result = self._call_method(ctx, request)
# Do not respond to notifications.
if request['id'] is None:
return None
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
return respond
class MethodContext(dict):
def __init__(self, logger):
self['client_ip'] = None
self['user_id'] = None
self['authenticated'] = None
self['token'] = None
self['module'] = None
self['method'] = None
self['call_id'] = None
self['rpc_context'] = None
self._debug_levels = set([7, 8, 9, 'DEBUG', 'DEBUG2', 'DEBUG3'])
self._logger = logger
def log_err(self, message):
self._log(log.ERR, message)
def log_info(self, message):
self._log(log.INFO, message)
def log_debug(self, message, level=1):
if level in self._debug_levels:
pass
else:
level = int(level)
if level < 1 or level > 3:
raise ValueError("Illegal log level: " + str(level))
level = level + 6
self._log(level, message)
def set_log_level(s |
# coding=utf-8
# Copyright 2022 The Google Research 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.
"""Functions for generating a logistic dataset.
x ~ N(0, I_d)
y ~ Bernoulli(sigmoid(-(1/temp) w^T x))
"""
import jax
from jax import numpy as jnp
def logistic_dataset_init_param(dim, r, rng_key):
param0 = jax.random.normal(rng_key, (dim, 1))
param0_norm = jnp.linalg.norm(param0)
param = param0 / param0_norm * r
return param
def logistic_dataset_gen_data(num, w, dim, temp, rng_key):
"""Samples data from a standard Gaussian with binary noisy labels.
Args:
num: An integer denoting the number of data points.
w: An array of size dim x odim, the weight vector used to generate labels.
dim: An integer denoting the number of inp | ut dimensions.
temp: A float denoting the temperature parameter controlling | label noise.
rng_key: JAX random number generator key.
Returns:
x: An array of size dim x num denoting data points.
y_pm: An array of size num x odim denoting +/-1 labels.
"""
rng_subkey = jax.random.split(rng_key, 3)
x = jax.random.normal(rng_subkey[0], (dim, num))
prob = jax.nn.sigmoid(-(1 / temp) * w.T.dot(x))
y = jax.random.bernoulli(rng_subkey[1], (prob))
y_pm = 2. * y - 1
return x, y_pm
def logistic_dataset_gen_train_test(config, rng_key):
"""Creates the train and test sets of a logistic dataset.
Args:
config: Dictionary of parameters.
config.dim: A float denoting input dimensionality.
config.r: A float denoting L2 norm of the true parameters.
config.num_train: An integer denoting the number of training data.
config.num_test: An integer denoting the number of test data.
rng_key: JAX random number generator key.
Returns:
train_data: The tuple (input, label) of training data.
test_data: The tuple (input, label) of test data.
"""
dim = config.dim
temp = config.temperature
rng_subkey = jax.random.split(rng_key, 3)
param = logistic_dataset_init_param(dim, config.r, rng_subkey[0])
train_data = logistic_dataset_gen_data(config.num_train, param, dim, temp,
rng_subkey[1])
test_data = logistic_dataset_gen_data(config.num_test, param, dim, temp,
rng_subkey[2])
return train_data, test_data
def get_train_test_generator(dataset):
if dataset == 'logistic':
return logistic_dataset_gen_train_test
raise NotImplementedError('Dataset not found.')
|
rt_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_raises_regexp
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import ignore_warnings
from sklearn.utils.testing import assert_not_equal
from sklearn.utils.testing import assert_warns_message
from sklearn.base import BaseEstimator
from sklearn.metrics import (f1_score, r2_score, roc_auc_score, fbeta_score,
log_loss, precision_score, recall_score)
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.metrics.scorer import (check_scoring, _PredictScorer,
_passthrough_scorer)
from sklearn.metrics import make_scorer, get_scorer, SCORERS
from sklearn.svm import LinearSVC
from sklearn.pipeline import make_pipeline
from sklearn.cluster import KMeans
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import Ridge, LogisticRegression
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.datasets import make_blobs
from sklearn.datasets import make_classification
from sklearn.datasets import make_multilabel_classification
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.multiclass import OneVsRestClassifier
from sklearn.externals import joblib
REGRESSION_SCORERS = ['r2', 'neg_mean_absolute_error',
'neg_mean_squared_error', 'neg_mean_squared_log_error',
'neg_median_absolute_error', 'mean_absolute_error',
'mean_squared_error', 'median_absolute_error']
CLF_SCORERS = ['accuracy', 'f1', 'f1_weighted', 'f1_macro', 'f1_micro',
'roc_auc', 'average_precision', 'precision',
'precision_weighted', 'precision_macro', 'precision_micro',
'recall', 'recall_weighted', 'recall_macro', 'recall_micro',
'neg_log_loss', 'log_loss',
'adjusted_rand_score' # not really, but works
]
MULTILABEL_ONLY_SCORERS = ['precision_samples', 'recall_samples', 'f1_samples']
def _make_estimators(X_train, y_train, y_ml_train):
# Make estimators that make sense to test various scoring methods
sensible_regr = DummyRegressor(strategy='median')
sensible_regr.fit(X_train, y_train)
sensible_clf = DecisionTreeClassifier(random_state=0)
sensible_clf.fit(X_train, y_train)
sensible_ml_clf = DecisionTreeClassifier(random_state=0)
sensible_ml_clf.fit(X_train, y_ml_train)
return dict(
[(name, sensible_regr) for name in REGRESSION_SCORERS] +
[(name, sensible_clf) for name in CLF_SCORERS] +
[(name, sensible_ml_clf) for name in MULTILABEL_ONLY_SCORERS]
)
X_mm, y_mm, y_ml_mm = None, None, None
ESTIMATORS = None
TEMP_FOLDER = None
def setup_module():
# Create some memory mapped data
global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS
TEMP_FOLDER = tempfile.mkdtemp(prefix='sklearn_test_score_objects_')
X, y = make_classification(n_samples=30, n_features=5, random_state=0)
_, y_ml = make_multilabel_classification(n_samples=X.shape[0],
random_state=0)
filename = os.path.join(TEMP_FOLDER, 'test_data.pkl')
joblib.dump((X, y, y_ml), filename)
X_mm, y_mm, y_ml_mm = joblib.load(filename, mmap_mode='r')
ESTIMATORS = _make_estimators(X_mm, y_mm, y_ml_mm)
def teardown_module():
global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS
# GC closes the mmap file descriptors
X_mm, y_mm, y_ml_mm, ESTIMATORS = None, None, None, None
shutil.rmtree(TEMP_FOLDER)
class EstimatorWithoutFit(object):
"""Dummy estimator to test check_scoring"""
pass
class EstimatorWithFit(BaseEstimator):
"""Dummy estimator to test check_scoring"""
def fit(self, X, y):
return self
class EstimatorWithFitAndScore(object):
"""Dummy estimator to test check_scoring"""
def fit(self, X, y):
return self
def score(self, X, y):
return 1.0
class EstimatorWithFitAndPredict(object):
"""Dummy estimator to test check_scoring"""
def fit(self, X, y):
self.y = y
return self
def predict(self, X):
return self.y
class DummyScorer(object):
"""Dummy scorer that always returns 1."""
def __call__(self, est, X, y):
return 1
def test_all_scorers_repr():
# Test that all scorers have a working repr
for name, scorer in SCORERS.items():
repr(scorer)
def test_check_scoring():
# Test all branches of check_scoring
estimator = EstimatorWithoutFit()
pattern = (r"estimator should be an estimator implementing 'fit' method,"
r" .* was passed")
assert_raises_regexp(TypeError, pattern, check_scoring, estimator)
estimator = EstimatorWithFitAndScore()
estimator.fit([[1]], [1])
scorer = check_scoring(estimator)
assert_true(scorer is _passthrough_scorer)
assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0)
estimator = EstimatorWithFitAndPredict()
estimator.fit([[1]], [1])
pattern = (r"If no scoring is specified, the estimator passed should have"
r" a 'score' method\. The estimator .* does not\.")
assert_raises_regexp(TypeError, pattern, check_scoring, estimator)
scorer = check_scoring(estimator, "accuracy")
assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0)
estimator = EstimatorWithFit()
scorer = check_scoring(estimator, "accuracy")
assert_true(isinstance(scorer, _PredictScorer))
estimator = EstimatorWithFit()
scorer = check_scoring(estimator, allow_none=True)
assert_true(scorer is None)
def test_check_scoring_gridsearchcv():
# test that check_scoring works on GridSearchCV and pipeline.
# slightly redundant non-regression test.
grid = GridSearchCV(LinearSVC(), param_grid={'C': [.1, 1]})
scorer = check_scoring(grid, "f1")
assert_true(isinstance(scorer, _PredictScorer))
pipe = make_pipeline(LinearSVC())
scorer = check_scoring(pipe, "f1")
assert_true(isinstance(scorer, _PredictScorer))
# check that cross_val_score definitely calls the scorer
| # and doesn't make any assumptions about the estimator apart from having a
# fit.
scores = cross_val_score(EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1],
scoring=DummyScorer())
assert_array_equal(scores, 1)
def test_make_scorer():
# Sanity check on the make_scorer factory function.
f = lambda *args: 0
assert_raises(ValueError, make_scorer, f, n | eeds_threshold=True,
needs_proba=True)
def test_classification_scores():
# Test classification scorers.
X, y = make_blobs(random_state=0, centers=2)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = LinearSVC(random_state=0)
clf.fit(X_train, y_train)
for prefix, metric in [('f1', f1_score), ('precision', precision_score),
('recall', recall_score)]:
score1 = get_scorer('%s_weighted' % prefix)(clf, X_test, y_test)
score2 = metric(y_test, clf.predict(X_test), pos_label=None,
average='weighted')
assert_almost_equal(score1, score2)
score1 = get_scorer('%s_macro' % prefix)(clf, X_test, y_test)
score2 = metric(y_test, clf.predict(X_test), pos_label=None,
average='macro')
assert_almost_equal(score1, score2)
score1 = get_scorer('%s_micro' % prefix)(clf, X_test, y_test)
score2 = metric(y_test, clf.predict(X_test), pos_label=None,
average='micro')
assert_almost_equal(score1, score2)
score1 = get_scorer('%s' % prefix)(clf, X_test, y_test)
score2 = metric(y_test, clf.predict(X_test), pos_label=1)
assert_almost_equal(score1, score2)
# test fbeta score that takes an argument
scorer = make_scorer(fbeta_score, beta=2)
score1 = scorer(clf, X_te |
# Purpose: dxf engine for R2007/AC1021
# Created: 12.03.2011
# Copyright (C) , Manfred Moitzi
# License: MIT License
from __future__ import unicode_literals
__author__ = "mozman <mozman@gmx.at>"
from .headervars import VARMAP
from ..ac1018 import AC1018Factory
class AC1021Factory(AC1018Factory):
| HEADERVARS | = dict(VARMAP)
|
from audio.io i | mpo | rt *
|
# -*- encoding: utf-8 -*-
import ast
import inspect
class NameLower(ast.NodeVisitor):
def __init__(self, lowered_names):
self.lowered_names = lowered_names
def visit_FunctionDef(self, node):
code = '__globals = globals()\n'
code += '\n'.join("{0} = __globals['{0}']".format(name) for name in self.lowered_names)
code_ast = ast.parse(code, mode='exec')
node.body[:0] = code_ast.body
self.func = node
def lower_names(*n | amelist | ):
def lower(func):
srclines = inspect.getsource(func).splitlines()
for n, line in enumerate(srclines):
if '@lower_names' in line:
break
src = '\n'.join(srclines[n + 1:])
if src.startswith(' ', '\t'):
src = 'if 1:\n' + src
top = ast.parse(src, mode='exec')
cl = NameLower(namelist)
cl.visit(top)
temp = {}
exec(compile(top, '', 'exec'), temp, temp)
func.__code__ = temp[func.__name__].__code__
return func
return lower
|
.41361256,
1.22474487]
assert_allclose(cA, cA_expect)
assert_allclose(cD, cD_expect)
x_roundtrip = pywt.idwt(cA, cD, 'db2')
assert_allclose(x_roundtrip, x, rtol=1e-10)
# mismatched dtypes OK
x_roundtrip2 = pywt.idwt(cA.astype(np.float64), cD.astype(np.float32),
'db2')
assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7)
assert_(x_roundtrip2.dtype == np.float64)
def test_idwt_mixed_complex_dtype():
x = np.arange(8).astype(float)
x = x + 1j*x[::-1]
cA, cD = pywt.dwt(x, 'db2')
x_roundtrip = pywt.idwt(cA, cD, 'db2')
assert_allclose(x_roundtrip, x, rtol=1e-10)
# mismatched dtypes OK
x_roundtrip2 = pywt.idwt(cA.astype(np.complex128), cD.astype(np.complex64),
'db2')
assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7)
assert_(x_roundtrip2.dtype == np.complex128)
def test_dwt_idwt_dtypes():
wavelet = pywt.Wavelet('haar')
for dt_in, dt_out in zip(dtypes_in, dtypes_out):
x = np.ones(4, dtype=dt_in)
errmsg = "wrong dtype returned for {0} input".format(dt_in)
cA, cD = pywt.dwt(x, wavelet)
assert_(cA.dtype == cD.dtype == dt_out, "dwt: " + errmsg)
x_roundtrip = pywt.idwt(cA, cD, wavelet)
assert_(x_roundtrip.dtype == dt_out, "idwt: " + errmsg)
def test_dwt_idwt_basic_complex():
x = np.asarray([3, 7, 1, 1, -2, 5, 4, 6])
x = x + 0.5j*x
cA, cD = pywt.dwt(x, 'db2')
| cA_expect = np.asarray([5.65685425, 7.39923721, 0.22414387, 3.33677403,
7.77817459])
cA_expect = cA_expect + 0.5j*cA_expect
cD_expect = np.asarray([-2.44948974, -1.60368225, -4.44140056, -0.41361256,
1.22474487])
cD_expect = cD_expect + 0.5j*cD_expect
assert_allclose(cA, cA_expect)
assert_allclose(cD, cD_expect)
x_r | oundtrip = pywt.idwt(cA, cD, 'db2')
assert_allclose(x_roundtrip, x, rtol=1e-10)
def test_dwt_idwt_partial_complex():
x = np.asarray([3, 7, 1, 1, -2, 5, 4, 6])
x = x + 0.5j*x
cA, cD = pywt.dwt(x, 'haar')
cA_rec_expect = np.array([5.0+2.5j, 5.0+2.5j, 1.0+0.5j, 1.0+0.5j,
1.5+0.75j, 1.5+0.75j, 5.0+2.5j, 5.0+2.5j])
cA_rec = pywt.idwt(cA, None, 'haar')
assert_allclose(cA_rec, cA_rec_expect)
cD_rec_expect = np.array([-2.0-1.0j, 2.0+1.0j, 0.0+0.0j, 0.0+0.0j,
-3.5-1.75j, 3.5+1.75j, -1.0-0.5j, 1.0+0.5j])
cD_rec = pywt.idwt(None, cD, 'haar')
assert_allclose(cD_rec, cD_rec_expect)
assert_allclose(cA_rec + cD_rec, x)
def test_dwt_wavelet_kwd():
x = np.array([3, 7, 1, 1, -2, 5, 4, 6])
w = pywt.Wavelet('sym3')
cA, cD = pywt.dwt(x, wavelet=w, mode='constant')
cA_expect = [4.38354585, 3.80302657, 7.31813271, -0.58565539, 4.09727044,
7.81994027]
cD_expect = [-1.33068221, -2.78795192, -3.16825651, -0.67715519,
-0.09722957, -0.07045258]
assert_allclose(cA, cA_expect)
assert_allclose(cD, cD_expect)
def test_dwt_coeff_len():
x = np.array([3, 7, 1, 1, -2, 5, 4, 6])
w = pywt.Wavelet('sym3')
ln_modes = [pywt.dwt_coeff_len(len(x), w.dec_len, mode) for mode in
pywt.Modes.modes]
expected_result = [6, ] * len(pywt.Modes.modes)
expected_result[pywt.Modes.modes.index('periodization')] = 4
assert_allclose(ln_modes, expected_result)
ln_modes = [pywt.dwt_coeff_len(len(x), w, mode) for mode in
pywt.Modes.modes]
assert_allclose(ln_modes, expected_result)
def test_idwt_none_input():
# None input equals arrays of zeros of the right length
res1 = pywt.idwt([1, 2, 0, 1], None, 'db2', 'symmetric')
res2 = pywt.idwt([1, 2, 0, 1], [0, 0, 0, 0], 'db2', 'symmetric')
assert_allclose(res1, res2, rtol=1e-15, atol=1e-15)
res1 = pywt.idwt(None, [1, 2, 0, 1], 'db2', 'symmetric')
res2 = pywt.idwt([0, 0, 0, 0], [1, 2, 0, 1], 'db2', 'symmetric')
assert_allclose(res1, res2, rtol=1e-15, atol=1e-15)
# Only one argument at a time can be None
assert_raises(ValueError, pywt.idwt, None, None, 'db2', 'symmetric')
def test_idwt_invalid_input():
# Too short, min length is 4 for 'db4':
assert_raises(ValueError, pywt.idwt, [1, 2, 4], [4, 1, 3], 'db4', 'symmetric')
def test_dwt_single_axis():
x = [[3, 7, 1, 1],
[-2, 5, 4, 6]]
cA, cD = pywt.dwt(x, 'db2', axis=-1)
cA0, cD0 = pywt.dwt(x[0], 'db2')
cA1, cD1 = pywt.dwt(x[1], 'db2')
assert_allclose(cA[0], cA0)
assert_allclose(cA[1], cA1)
assert_allclose(cD[0], cD0)
assert_allclose(cD[1], cD1)
def test_idwt_single_axis():
x = [[3, 7, 1, 1],
[-2, 5, 4, 6]]
x = np.asarray(x)
x = x + 1j*x # test with complex data
cA, cD = pywt.dwt(x, 'db2', axis=-1)
x0 = pywt.idwt(cA[0], cD[0], 'db2', axis=-1)
x1 = pywt.idwt(cA[1], cD[1], 'db2', axis=-1)
assert_allclose(x[0], x0)
assert_allclose(x[1], x1)
def test_dwt_invalid_input():
x = np.arange(1)
assert_raises(ValueError, pywt.dwt, x, 'db2', 'reflect')
assert_raises(ValueError, pywt.dwt, x, 'haar', 'antireflect')
def test_dwt_axis_arg():
x = [[3, 7, 1, 1],
[-2, 5, 4, 6]]
cA_, cD_ = pywt.dwt(x, 'db2', axis=-1)
cA, cD = pywt.dwt(x, 'db2', axis=1)
assert_allclose(cA_, cA)
assert_allclose(cD_, cD)
def test_dwt_axis_invalid_input():
x = np.ones((3,1))
assert_raises(ValueError, pywt.dwt, x, 'db2', 'reflect')
def test_idwt_axis_arg():
x = [[3, 7, 1, 1],
[-2, 5, 4, 6]]
cA, cD = pywt.dwt(x, 'db2', axis=1)
x_ = pywt.idwt(cA, cD, 'db2', axis=-1)
x = pywt.idwt(cA, cD, 'db2', axis=1)
assert_allclose(x_, x)
def test_dwt_idwt_axis_excess():
x = [[3, 7, 1, 1],
[-2, 5, 4, 6]]
# can't transform over axes that aren't there
assert_raises(ValueError,
pywt.dwt, x, 'db2', 'symmetric', axis=2)
assert_raises(ValueError,
pywt.idwt, [1, 2, 4], [4, 1, 3], 'db2', 'symmetric', axis=1)
def test_error_on_continuous_wavelet():
# A ValueError is raised if a Continuous wavelet is selected
data = np.ones((32, ))
for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
assert_raises(ValueError, pywt.dwt, data, cwave)
cA, cD = pywt.dwt(data, 'db1')
assert_raises(ValueError, pywt.idwt, cA, cD, cwave)
def test_dwt_zero_size_axes():
# raise on empty input array
assert_raises(ValueError, pywt.dwt, [], 'db2')
# >1D case uses a different code path so check there as well
x = np.ones((1, 4))[0:0, :] # 2D with a size zero axis
assert_raises(ValueError, pywt.dwt, x, 'db2', axis=0)
def test_pad_1d():
x = [1, 2, 3]
assert_array_equal(pywt.pad(x, (4, 6), 'periodization'),
[1, 2, 3, 3, 1, 2, 3, 3, 1, 2, 3, 3, 1, 2])
assert_array_equal(pywt.pad(x, (4, 6), 'periodic'),
[3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])
assert_array_equal(pywt.pad(x, (4, 6), 'constant'),
[1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3])
assert_array_equal(pywt.pad(x, (4, 6), 'zero'),
[0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0])
assert_array_equal(pywt.pad(x, (4, 6), 'smooth'),
[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
assert_array_equal(pywt.pad(x, (4, 6), 'symmetric'),
[3, 3, 2, 1, 1, 2, 3, 3, 2, 1, 1, 2, 3])
assert_array_equal(pywt.pad(x, (4, 6), 'antisymmetric'),
[3, -3, -2, -1, 1, 2, 3, -3, -2, -1, 1, 2, 3])
assert_array_equal(pywt.pad(x, (4, 6), 'reflect'),
[1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1])
assert_array_equal(pywt.pad(x, (4, 6), 'antireflect'),
[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# equivalence of various pad_width formats
assert_array_equal(pywt.pad(x, 4, 'periodic'),
pywt.pad(x, (4, 4), 'periodic'))
assert_array_equal(pywt.pad(x, (4, ), 'periodic'),
pywt.pad(x, (4, 4), 'periodic'))
assert_array_equal(pywt.pad(x, [(4, 4) |
from .fields import BitField, Field
from nettest.exceptions import NettestError
import struct
class PacketMeta(type):
def __new__(cls, name, bases, attrs):
fields = attrs.get('fields')
if fields is None:
raise NettestError(_("packet class must have 'fields' field"))
_fields = []
for fieldname in attrs['fields']:
field = attrs.get(fieldname)
if field is None:
for baseclass in bases:
field = getattr(baseclass, fieldname)
if field is not None:
break
else:
raise NettestError(_("field '%s' doesn't exsists in class %s")%(fieldname, name))
if not cls.__check_field_type(cls, field):
raise NettestError(_("field '%s' in class %s should be in type (Field, Packet, list)")%(fieldname, name))
_fields.append((fieldname, field))
if isinstance(field, Field):
attrs[fieldname] = field.default_value
if '_fields' in attrs:
raise NettestError(_("the name '_fields' is reserved in class %s")%(name))
attrs['_fields']= _fields
return super(PacketMeta, cls).__new__(cls, name, bases, attrs)
@staticmethod
def __check_field_type(cls, field):
if not isinstance(field, (Field, Packet, list)):
return False
if isinstance(field, (list)):
for subfield in field:
if not cls.__check_field_type(cls, subfield):
return False
return True
class BitDumper(object):
def __init__(self):
self.data= []
self.data_len = []
self.data_len_sum = 0
def clear(self):
self.data = []
self.data_len = []
self.data_len_sum = 0
def push(self, data, length):
data = int(data)
if data < 0 or data > 2**length:
raise NettestError(_("bit value out of range"))
self.data.append(data)
self.data_len.append(length)
self.data_len_sum += length
def dump(self):
if self.data_len_sum % 8 != 0:
raise NettestError(_("incorrect bit field length"))
data = 0
left_len = self.data_len_sum
index = 0
for field_data in self.data:
data += field_data<<(left_len - self.data_len[index])
left_len -= self.data_len[index]
index += 1
length = self.data_len_sum / 8
if length == 1:
return struct.pack('!B', int(data))
elif length == 2:
return struct.pack('!H', int(data))
elif length == 4:
return struct.pack('!I', int(data))
elif length == 8:
return struct.pack('!Q', int(data))
else:
raise NettestError(_("too long bit field"))
class BitLoader(object):
def __init__(self, packet):
self.fields = []
self.bit_len_sum = 0
self.packet = packet
def clear(self):
self.fields = []
self.bit_len_sum = 0
def push(self, fieldname, field):
self.fields.append((fieldname,field))
self.bit_len_sum += field.length
def load(self, data):
if self.bit_len_sum % 8 != 0:
raise NettestError(_("incorrect bit field length"))
byte_len = int(self.bit_len_sum / 8)
data = data[:byte_len]
loaded_len = 0
for field_name, field in self.fields:
field_data = field.from_netbytes(data, loaded_len)
loaded_len += field.length
setattr(self.packet, field_name, field_data)
return byte_len
class Packet(object, metaclass=PacketMeta):
'''define field order
'''
fields=[]
def __init__(self):
for field_name, field in self._fields:
if isinstance(field, Packet):
setattr(self, field_name, field.__class__())
def dump(self):
'''Serialize self to bytes
'''
data = b''
bit_dumper = BitDumper()
for field_name, field in self._fields:
field_value = getattr(self, field_name)
if field_value is None:
raise NettestError(_("%s is None and haven't default value")%(field_name))
if isinstance(field, BitField):
bit_dumper.push(field_value, field.length)
continue
else:
if bit_dumper.data_len_sum > 0:
data += bit_dumper.dump()
bit_dumper.clear()
if isinstance(field, Packet):
data += field_value.dump()
continue
data += field.to_netbytes(field_value)
if bit_dumper.data_len_sum > 0:
data += bit_dumper.dump()
return data
# def __dump_list_data(self, fields):
# data = b''
# for field in fields:
# if isinstance(field, Packet):
# data += field.dump()
# continue
# if isinstance(field, list):
# data += self.__dump_list_data()
# continue
# if isinstance(field, Field):
# data += field.to_netbytes(field_value)
# continue
def load(self, data):
'''Deserialize bytes to a self.
if success, return the total data length used
else return None
'''
loaded_len = 0
bit_loader = BitLoader(self)
for field_name, field in self._fields:
if isinstance(field, BitField):
bit_loader.push(field_name, field)
continue
else:
if bit_loader.bit_len_sum > 0:
loaded_len += bit_loader.load(data[loaded_len:])
bit_loader.clear()
if isinstance(field, Packet):
field_value = getattr(self, field_name)
length = field_value.load(data[loaded_len:])
if length is None:
return None
loaded_len += length
continue
field_data = field.from_netbytes(data[loaded_len:])
if field_data is None:
return None
loaded_len += field.length
setattr(self, field_name, field_data)
if bit_loader.bit_len_sum > 0:
loaded_len += bit_loader.load(data[loaded_len:])
return loaded_len
def to_printable(self):
string = ''
string += '-'*20+str(self.__class__.__name__)+'-'*20+'\n'
for field_name, field in self._fields:
field_value = getattr(self, field_name)
if field_value is None:
string += '%s\tNone\n'%(field_name)
elif isinstance(field, Packet):
string += '%s\t%s\n'%(field_name, field_value.to_printable())
else:
string += '%s\t%s\n'%(field_name, field.to_printable(field_value))
string += '-'*(40+len(self.__class__.__name__))+'\n'
return string
d | ef __eq__(self, other):
for field_name in self.fields:
field_value1 = getattr(self, field_name)
field_value2 = getattr(other, field_name)
if field_value1 | != field_value2:
return False
return True
@property
def length(self):
total_len = 0
bit_len = 0
for field_name, field in self._fields:
if isinstance(field, BitField):
bit_len += field.length
elif field.length > 0:
total_len += field.length
else:
field_value = getattr(self, field_name)
total_len += len(field_value)
total_len += int(bit_len/8)
return total_len
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
utils
=====
Utility functions for matching.py.
"""
import datetime
import json
import os
#testme
def parse_timestamp(t):
"""Parse MediaWiki-style timestamps and return a datetime."""
if t == '0000-00-00T00:00:00Z':
return None
else:
return datetime.datetime.strptime(t, '%Y-%m-%dT%H:%M:%SZ')
def load_config(filepath):
"""Given the path to the config file, opens and returns the dict."""
configfile = os.path.jo | in(filepath, 'config.json')
with open(configfile, 'rb') as configf:
config = json.loads(configf.read())
| return config
#testme
def make_category_string(categories):
"""Given a list of categories, return the |-separated string."""
return '|'.join(categories)
def timelog(run_time, filepath):
"""Get the timestamp from the last run, then log the current time
(UTC).
"""
timelogfile = os.path.join(filepath, 'time.log') # fixme this currently only works because filepath is in the enclosing scope (main)
try:
with open(timelogfile, 'r+b') as timelog:
prevruntimestamp = timelog.read()
timelog.seek(0)
timelog.write(datetime.datetime.strftime(run_time,
'%Y-%m-%dT%H:%M:%SZ'))
timelog.truncate()
except IOError:
with open(timelogfile, 'wb') as timelog:
prevruntimestamp = ''
timelog.write(datetime.datetime.strftime(run_time,
'%Y-%m-%dT%H:%M:%SZ'))
return prevruntimestamp
#testme
def buildgreeting(greeting, username, ideas):
"""Create a customized greeting string to be posted to a talk page
to present the IdeaLab member with a list of interesting ideas.
Return the wikitext-formatted greeting string.
"""
idea_string = ''
for idea in ideas:
title = idea['profile_title']
idea_string = u'{}* [[{}]]\n'.format(idea_string, title)
full_greeting = greeting.format(username, idea_string)
return full_greeting
|
"""
Filename: mc_tools.py
Authors: John Stachurski and Thomas J. Sargent
"""
import numpy as np
from discrete_rv import DiscreteRV
def mc_compute_stationary(P):
"""
Computes the stationary distribution of Markov matrix P.
Parameters
===========
P : a square 2D NumPy array
Returns: A flat array giving the stationary distribution
"""
n = len(P) # P is n x n
I = np.identity(n) # Identity matrix
B, b = np.ones((n, n)), np.ones((n, 1)) # Matrix and vector of ones
A = np.transpose(I - P + B)
solution = np.linalg.solve(A, b)
return solution.flatten() # Return a flat array
def mc_sample_path( | P, init=0, sample_size=1000):
"""
Generates one sa | mple path from a finite Markov chain with (n x n) Markov
matrix P on state space S = {0,...,n-1}.
Parameters
==========
P : A nonnegative 2D NumPy array with rows that sum to 1
init : Either an integer in S or a nonnegative array of length n
with elements that sum to 1
sample_size : int
If init is an integer, the integer is treated as the determinstic initial
condition. If init is a distribution on S, then X_0 is drawn from this
distribution.
Returns
========
A NumPy array containing the sample path
"""
# === set up array to store output === #
X = np.empty(sample_size, dtype=int)
if isinstance(init, int):
X[0] = init
else:
X[0] = DiscreteRV(init).draw()
# === turn each row into a distribution === #
# In particular, let P_dist[i] be the distribution corresponding to the
# i-th row P[i,:]
n = len(P)
P_dist = [DiscreteRV(P[i,:]) for i in range(n)]
# === generate the sample path === #
for t in range(sample_size - 1):
X[t+1] = P_dist[X[t]].draw()
return X
|
nce(j, slice):
obj.times = self.times.__getitem__(j)
elif isinstance(j, np.ndarray):
raise NotImplementedError("Arrays not yet supported")
else:
raise TypeError("%s not supported" % type(j))
if isinstance(k, int):
obj = obj.reshape(-1, 1)
elif isinstance(i, slice):
obj.times = self.times.__getitem__(i)
else:
raise IndexError("index should be an integer, tuple or slice")
return obj
@property
def duration(self):
'''
Signal duration.
(:attr:`times`[-1] - :attr:`times`[0])
'''
return self.times[-1] - self.times[0]
@property
def t_start(self):
'''
Time when signal begins.
(:attr:`times`[0])
'''
return self.times[0]
@property
def t_stop(self):
'''
Time when signal ends.
(:attr:`times`[-1])
'''
return self.times[-1]
def __eq__(self, other):
'''
Equality test (==)
'''
return (super(IrregularlySampledSignal, self).__eq__(other).all() and
(self.times == other.times).all())
def __ne__(self, other):
'''
Non-equality test (!=)
'''
return not self.__eq__(other)
def _apply_operator(self, other, op, *args):
'''
Handle copying metadata to the new :class:`IrregularlySampledSignal`
after a mathematical operation.
'''
self._check_consistency(other)
f = getattr(super(IrregularlySampledSignal, self), op)
new_signal = f(other, *args)
new_signal._copy_data_complement(self)
return new_signal
def _check_consistency(self, other):
'''
Check if the attributes of another :class:`IrregularlySampledSignal`
are compatible with this one.
'''
# if not an array, then allow the calculation
if not hasattr(other, 'ndim'):
return
# if a scalar array, then allow the calculation
if not other.ndim:
return
# dimensionality should match
if self.ndim != other.ndim:
raise ValueError('Dimensionality does not match: %s vs %s' %
(self.ndim, other.ndim))
# if if the other array does not have a times property,
# then it should be okay to add it directly
if not hasattr(other, 'times'):
return
# if there is a times property, the times | need to be the same
if not (self.times == other.times).all():
raise ValueError('Times do not match: %s vs %s' %
(self.times, other.times))
def _copy_data_complement(self, other):
'''
Copy the metadata from another :class:`IrregularlySampledSignal`.
| '''
for attr in ("times", "name", "file_origin",
"description", "annotations"):
setattr(self, attr, getattr(other, attr, None))
def __add__(self, other, *args):
'''
Addition (+)
'''
return self._apply_operator(other, "__add__", *args)
def __sub__(self, other, *args):
'''
Subtraction (-)
'''
return self._apply_operator(other, "__sub__", *args)
def __mul__(self, other, *args):
'''
Multiplication (*)
'''
return self._apply_operator(other, "__mul__", *args)
def __truediv__(self, other, *args):
'''
Float division (/)
'''
return self._apply_operator(other, "__truediv__", *args)
def __div__(self, other, *args):
'''
Integer division (//)
'''
return self._apply_operator(other, "__div__", *args)
__radd__ = __add__
__rmul__ = __sub__
def __rsub__(self, other, *args):
'''
Backwards subtraction (other-self)
'''
return self.__mul__(-1) + other
def _repr_pretty_(self, pp, cycle):
'''
Handle pretty-printing the :class:`IrregularlySampledSignal`.
'''
pp.text("{cls} with {channels} channels of length {length}; "
"units {units}; datatype {dtype} ".format(
cls=self.__class__.__name__,
channels=self.shape[1],
length=self.shape[0],
units=self.units.dimensionality.string,
dtype=self.dtype))
if self._has_repr_pretty_attrs_():
pp.breakable()
self._repr_pretty_attrs_(pp, cycle)
def _pp(line):
pp.breakable()
with pp.group(indent=1):
pp.text(line)
for line in ["sample times: {0}".format(self.times)]:
_pp(line)
@property
def sampling_intervals(self):
'''
Interval between each adjacent pair of samples.
(:attr:`times[1:]` - :attr:`times`[:-1])
'''
return self.times[1:] - self.times[:-1]
def mean(self, interpolation=None):
'''
Calculates the mean, optionally using interpolation between sampling
times.
If :attr:`interpolation` is None, we assume that values change
stepwise at sampling times.
'''
if interpolation is None:
return (self[:-1]*self.sampling_intervals.reshape(-1, 1)).sum()/self.duration
else:
raise NotImplementedError
def resample(self, at=None, interpolation=None):
'''
Resample the signal, returning either an :class:`AnalogSignal` object
or another :class:`IrregularlySampledSignal` object.
Arguments:
:at: either a :class:`Quantity` array containing the times at
which samples should be created (times must be within the
signal duration, there is no extrapolation), a sampling rate
with dimensions (1/Time) or a sampling interval
with dimensions (Time).
:interpolation: one of: None, 'linear'
'''
# further interpolation methods could be added
raise NotImplementedError
def rescale(self, units):
'''
Return a copy of the :class:`IrregularlySampledSignal` converted to the
specified units
'''
to_dims = pq.quantity.validate_dimensionality(units)
if self.dimensionality == to_dims:
to_u = self.units
signal = np.array(self)
else:
to_u = pq.Quantity(1.0, to_dims)
from_u = pq.Quantity(1.0, self.dimensionality)
try:
cf = pq.quantity.get_conversion_factor(from_u, to_u)
except AssertionError:
raise ValueError('Unable to convert between units of "%s" \
and "%s"' % (from_u._dimensionality,
to_u._dimensionality))
signal = cf * self.magnitude
new = self.__class__(times=self.times, signal=signal, units=to_u)
new._copy_data_complement(self)
new.annotations.update(self.annotations)
return new
def merge(self, other):
'''
Merge another :class:`IrregularlySampledSignal` with this one, and return the
merged signal.
The :class:`IrregularlySampledSignal` objects are concatenated horizontally
(column-wise, :func:`np.hstack`).
If the attributes of the two :class:`IrregularlySampledSignal` are not
compatible, a :class:`MergeError` is raised.
'''
if not np.array_equal(self.times, other.times):
raise MergeError("Cannot merge these two signals as the sample times differ.")
if self.segment != other.segment:
raise MergeError("Cannot merge these two signals as they belong to different segments.")
if hasattr(self, "lazy_shape"):
if hasattr(other, "lazy_shape"):
if self.lazy_shape[0] != other.lazy_shape[0]:
raise MergeError("Cannot merge signals of different le |
from __future__ import unicode_literals
from datetime import datetime, date
import os
import time
from django.utils.dateformat import format
from django.utils import dateformat, translation, unittest
from django.utils.timezone import utc
from django.utils.tzinfo import FixedOffset, LocalTimezone
class DateFormatTests(unittest.TestCase):
def setUp(self):
self.old_TZ = os.environ.get('TZ')
os.environ['TZ'] = 'Europe/Copenhagen'
translation.activate('en-us')
try:
# Check if a timezone has been set
time.tzset()
self.tz_tests = True
except AttributeError:
# No timezone available. Don't run the tests that require a TZ
self.tz_tests = False
def tearDown(self):
if self.old_TZ is None:
del os.environ['TZ']
else:
os.environ['TZ'] = self.old_TZ
# Cleanup - force re-evaluation of TZ environment variable.
if self.tz_tests:
time.tzset()
def test_date(self):
d = date(2009, 5, 16)
self.assertEqual(date.fromtimestamp(int(format(d, 'U'))), d)
def test_naive_datetime(self):
dt = datetime(2009, 5, 16, 5, 30, 30)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt)
def test_datetime_with_local_tzinfo(self):
ltz = LocalTimezone(datetime.now())
dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=ltz)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt.replace(tzinfo=None))
def test_datetime_with_tzinfo(self):
tz = FixedOffset(-510)
ltz = LocalTimezone(datetime.now())
dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=tz)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), tz), dt)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt.astimezone(ltz).replace(tzinfo=None))
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), tz).utctimetuple(), dt.utctimetuple())
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz).utctimetuple(), dt.utctimetuple())
def test_epoch(self):
udt = datetime(1970, 1, 1, tzinfo=utc)
self.assertEqual(format(udt, 'U'), '0')
def test_empty_format(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEqual(dateformat.format(my_birthday, ''), '')
def test_am_pm(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEqual(dateformat.format(my_birthday, 'a'), 'p.m.')
def test_microsecond(self):
# Regression test for #18951
dt = datetime(2009, 5, 16, microsecond=123)
self.assertEqual(dateformat.format(dt, 'u'), '000123')
def test_date_formats(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)
| self.assertEqual(dateformat.format(my_birthday, 'A'), 'PM')
self.assertEqual(dateformat.format(timestamp, 'c'), '2008-05-19T11:45:23.123456')
self.assertEqual(dateformat.format(my_birthday, 'd'), '08')
self.assertEqual(dateformat.format(my_birthday, 'j'), '8')
self.assertEqual(dateformat.format(my_birthday, 'l'), 'Sunday')
self.a | ssertEqual(dateformat.format(my_birthday, 'L'), 'False')
self.assertEqual(dateformat.format(my_birthday, 'm'), '07')
self.assertEqual(dateformat.format(my_birthday, 'M'), 'Jul')
self.assertEqual(dateformat.format(my_birthday, 'b'), 'jul')
self.assertEqual(dateformat.format(my_birthday, 'n'), '7')
self.assertEqual(dateformat.format(my_birthday, 'N'), 'July')
def test_time_formats(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEqual(dateformat.format(my_birthday, 'P'), '10 p.m.')
self.assertEqual(dateformat.format(my_birthday, 's'), '00')
self.assertEqual(dateformat.format(my_birthday, 'S'), 'th')
self.assertEqual(dateformat.format(my_birthday, 't'), '31')
self.assertEqual(dateformat.format(my_birthday, 'w'), '0')
self.assertEqual(dateformat.format(my_birthday, 'W'), '27')
self.assertEqual(dateformat.format(my_birthday, 'y'), '79')
self.assertEqual(dateformat.format(my_birthday, 'Y'), '1979')
self.assertEqual(dateformat.format(my_birthday, 'z'), '189')
def test_dateformat(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEqual(dateformat.format(my_birthday, r'Y z \C\E\T'), '1979 189 CET')
self.assertEqual(dateformat.format(my_birthday, r'jS \o\f F'), '8th of July')
def test_futuredates(self):
the_future = datetime(2100, 10, 25, 0, 00)
self.assertEqual(dateformat.format(the_future, r'Y'), '2100')
def test_timezones(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
summertime = datetime(2005, 10, 30, 1, 00)
wintertime = datetime(2005, 10, 30, 4, 00)
timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)
if self.tz_tests:
self.assertEqual(dateformat.format(my_birthday, 'O'), '+0100')
self.assertEqual(dateformat.format(my_birthday, 'r'), 'Sun, 8 Jul 1979 22:00:00 +0100')
self.assertEqual(dateformat.format(my_birthday, 'T'), 'CET')
self.assertEqual(dateformat.format(my_birthday, 'U'), '300315600')
self.assertEqual(dateformat.format(timestamp, 'u'), '123456')
self.assertEqual(dateformat.format(my_birthday, 'Z'), '3600')
self.assertEqual(dateformat.format(summertime, 'I'), '1')
self.assertEqual(dateformat.format(summertime, 'O'), '+0200')
self.assertEqual(dateformat.format(wintertime, 'I'), '0')
self.assertEqual(dateformat.format(wintertime, 'O'), '+0100')
# Ticket #16924 -- We don't need timezone support to test this
# 3h30m to the west of UTC
tz = FixedOffset(-3*60 - 30)
dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=tz)
self.assertEqual(dateformat.format(dt, 'O'), '-0330')
|
realm=self._realm, scheme=self._scheme, host=self._host,
port=self._port, **self._context)
return self._cred_manager
def _filter_stanza(self, stanza):
for k in self.reserved_keys:
if k in stanza:
del stanza[k]
return stanza
def _encrypt_stanza(self, stanza_name, stanza, encrypt_keys):
if not encrypt_keys:
return stanza
encrypt_stanza_keys = [ k for k in encrypt_keys if k in stanza ]
encrypt_fields = {key: stanza[key] for key in encrypt_stanza_keys}
if not encrypt_fields:
return stanza
self._cred_mgr.set_password(stanza_name, json.dumps(encrypt_fields))
for key in encrypt_stanza_keys:
stanza[key] = self.ENCRYPTED_TOKEN
return stanza
def _decrypt_stanza(self, stanza_name, encrypted_stanza):
encrypted_keys = [key for key in encrypted_stanza if
encrypted_stanza[key] == self.ENCRYPTED_TOKEN]
if encrypted_keys:
encrypted_fields = json.loads(
self._cred_mgr.get_password(stanza_name))
for key in encrypted_keys:
encrypted_stanza[key] = encrypted_fields[key]
return encrypted_stanza
def _delete_stanza_creds(self, stanza_name):
self._cred_mgr.delete_password(stanza_name)
@retry(exceptions=[binding.HTTPError])
def stanza_exist(self, stanza_name):
'''Check whether stanza exists.
:param stanza_name: Stanza name.
:type stanza_name: ``string``
:returns: True if stanza exists else False.
:rtype: ``bool``
Usage::
>>> from solnlib import conf_manager
>>> cfm = conf_manager.ConfManager(session_key,
'Splunk_TA_test')
>>> conf = cfm.get_conf('test')
>>> conf.stanza_exist('test_stanza')
'''
try:
self._conf.list(name=stanza_name)[0]
except binding.HTTPError as e:
if e.status != 404:
| raise
return False
return True
@retry(exceptions=[binding.HTTPError])
def get(self, stanza_name, only_current_app=False):
'''Get stanza from configuration file.
:param stanza_name: Stanza name.
:type stanza_name: ``string``
:returns: Stanza, like: {
'disabled': '0',
| 'eai:appName': 'solnlib_demo',
'eai:userName': 'nobody',
'k1': '1',
'k2': '2'}
:rtype: ``dict``
:raises ConfStanzaNotExistException: If stanza does not exist.
Usage::
>>> from solnlib import conf_manager
>>> cfm = conf_manager.ConfManager(session_key,
'Splunk_TA_test')
>>> conf = cfm.get_conf('test')
>>> conf.get('test_stanza')
'''
try:
if only_current_app:
stanza_mgrs = self._conf.list(
search='eai:acl.app={} name={}'.format(
self._app, stanza_name.replace('=', r'\=')))
else:
stanza_mgrs = self._conf.list(name=stanza_name)
except binding.HTTPError as e:
if e.status != 404:
raise
raise ConfStanzaNotExistException(
'Stanza: %s does not exist in %s.conf' %
(stanza_name, self._name))
if len(stanza_mgrs) == 0:
raise ConfStanzaNotExistException(
'Stanza: %s does not exist in %s.conf' %
(stanza_name, self._name))
stanza = self._decrypt_stanza(stanza_mgrs[0].name, stanza_mgrs[0].content)
stanza['eai:access'] = stanza_mgrs[0].access
stanza['eai:appName'] = stanza_mgrs[0].access.app
return stanza
@retry(exceptions=[binding.HTTPError])
def get_all(self, only_current_app=False):
'''Get all stanzas from configuration file.
:returns: All stanzas, like: {'test': {
'disabled': '0',
'eai:appName': 'solnlib_demo',
'eai:userName': 'nobody',
'k1': '1',
'k2': '2'}}
:rtype: ``dict``
Usage::
>>> from solnlib import conf_manager
>>> cfm = conf_manager.ConfManager(session_key,
'Splunk_TA_test')
>>> conf = cfm.get_conf('test')
>>> conf.get_all()
'''
if only_current_app:
stanza_mgrs = self._conf.list(search='eai:acl.app={}'.format(self._app))
else:
stanza_mgrs = self._conf.list()
res = {}
for stanza_mgr in stanza_mgrs:
name = stanza_mgr.name
key_values = self._decrypt_stanza(name, stanza_mgr.content)
key_values['eai:access'] = stanza_mgr.access
key_values['eai:appName'] = stanza_mgr.access.app
res[name] = key_values
return res
@retry(exceptions=[binding.HTTPError])
def update(self, stanza_name, stanza, encrypt_keys=None):
'''Update stanza.
It will try to encrypt the credential automatically fist if
encrypt_keys are not None else keep stanza untouched.
:param stanza_name: Stanza name.
:type stanza_name: ``string``
:param stanza: Stanza to update, like: {
'k1': 1,
'k2': 2}.
:type stanza: ``dict``
:param encrypt_keys: Fields name to encrypt.
:type encrypt_keys: ``list``
Usage::
>>> from solnlib import conf_manager
>>> cfm = conf_manager.ConfManager(session_key,
'Splunk_TA_test')
>>> conf = cfm.get_conf('test')
>>> conf.update('test_stanza', {'k1': 1, 'k2': 2}, ['k1'])
'''
stanza = self._filter_stanza(stanza)
encrypted_stanza = self._encrypt_stanza(stanza_name,
stanza,
encrypt_keys)
try:
stanza_mgr = self._conf.list(name=stanza_name)[0]
except binding.HTTPError as e:
if e.status != 404:
raise
stanza_mgr = self._conf.create(stanza_name)
stanza_mgr.submit(encrypted_stanza)
@retry(exceptions=[binding.HTTPError])
def delete(self, stanza_name):
'''Delete stanza.
:param stanza_name: Stanza name to delete.
:type stanza_name: ``string``
:raises ConfStanzaNotExistException: If stanza does not exist.
Usage::
>>> from solnlib import conf_manager
>>> cfm = conf_manager.ConfManager(session_key,
'Splunk_TA_test')
>>> conf = cfm.get_conf('test')
>>> conf.delete('test_stanza')
'''
try:
self._cred_mgr.delete_password(stanza_name)
except CredentialNotExistException:
pass
try:
self._conf.delete(stanza_name)
except KeyError as e:
logging.error('Delete stanza: %s error: %s.',
stanza_name, traceback.format_exc())
raise ConfStanzaNotExistException(
'Stanza: %s does not exist in %s.conf' %
(stanza_name, self._name))
@retry(exceptions=[binding.HTTPError])
def reload(self):
'''Reload configuration file.
Usage::
>>> from solnlib import conf_manager
>>> cfm = conf_manager.ConfManager(session_key,
'Splunk_TA_test')
>>> conf = cfm.get_conf('test')
>>> conf.reload()
'''
self._conf.get('_reload')
class ConfManagerException(Exception):
pass
class ConfManager(object):
'''Configuration file manager.
:param session_key: Splunk access token.
:type session_key: ``string``
:param app: App name of namespace.
:type app: ``string``
:param owner: (optional) Owner of |
settings
from django.core.files.storage import default_storage as storage
from django.test.client import RequestFactory
from mock import patch
from olympia import amo, core
from olympia.addons import forms
from olympia.addons.models import Addon, Category
from olympia.amo.tests import TestCase, addon_factory, req_factory_factory
from olympia.amo.tests.test_helpers import get_image_path
from olympia.amo.utils import rm_local_tmp_dir
from olympia.tags.models import AddonTag, Tag
from olympia.users.models import UserProfile
class TestAddonFormSupport(TestCase):
def test_bogus_support_url(self):
form = forms.AddonFormSupport(
{'support_url': 'javascript://something.com'}, request=None)
assert not form.is_valid()
assert form.errors['support_url'][0][1] == u'Enter a valid URL.'
def test_ftp_support_url(self):
form = forms.AddonFormSupport(
{'support_url': 'ftp://foo.com'}, request=None)
assert not form.is_valid()
assert form.errors['support_url'][0][1] == u'Enter a valid URL.'
def test_http_support_url(self):
form = forms.AddonFormSupport(
{'support_url': 'http://foo.com'}, request=None)
assert form.is_valid()
class FormsTest(TestCase):
fixtures = ('base/addon_3615', 'base/addon_3615_categories',
'addons/denied')
def setUp(self):
super(FormsTest, self).setUp()
self.existing_name = 'Delicious Bookmarks'
self.non_existing_name = 'Does Not Exist'
self.error_msg = 'This name is already in use. Please choose another.'
self.request = req_factory_factory('/')
def test_locales(self):
form = forms.AddonFormDetails(request=self.request)
assert form.fields['default_locale'].choices[0][0] == 'af'
def test_slug_deny(self):
delicious = Addon.objects.get()
form = forms.AddonFormBasic({'slug': 'submit'}, re | quest=self.request,
instance=delicious)
assert not form.is_valid()
assert form.errors['slug'] == (
[u'The slug cannot be "submit". Please choose another.'])
def test_name_trademark_mozilla(self):
delicious = Addon.objects.get()
form = forms.AddonFormBasic(
{'name': 'Delicious Mozilla', 'summary': 'foo', 'slug': 'bar'},
request=self.request,
instance=delicious)
assert not f | orm.is_valid()
assert dict(form.errors['name'])['en-us'].startswith(
u'Add-on names cannot contain the Mozilla or Firefox trademarks.')
def test_name_trademark_firefox(self):
delicious = Addon.objects.get()
form = forms.AddonFormBasic(
{'name': 'Delicious Firefox', 'summary': 'foo', 'slug': 'bar'},
request=self.request,
instance=delicious)
assert not form.is_valid()
assert dict(form.errors['name'])['en-us'].startswith(
u'Add-on names cannot contain the Mozilla or Firefox trademarks.')
def test_name_trademark_allowed_for_prefix(self):
delicious = Addon.objects.get()
form = forms.AddonFormBasic(
{'name': 'Delicious for Mozilla', 'summary': 'foo', 'slug': 'bar'},
request=self.request,
instance=delicious)
assert form.is_valid()
def test_name_no_trademark(self):
delicious = Addon.objects.get()
form = forms.AddonFormBasic(
{'name': 'Delicious Dumdidum', 'summary': 'foo', 'slug': 'bar'},
request=self.request,
instance=delicious)
assert form.is_valid()
def test_bogus_homepage(self):
form = forms.AddonFormDetails(
{'homepage': 'javascript://something.com'}, request=self.request)
assert not form.is_valid()
assert form.errors['homepage'][0][1] == u'Enter a valid URL.'
def test_ftp_homepage(self):
form = forms.AddonFormDetails(
{'homepage': 'ftp://foo.com'}, request=self.request)
assert not form.is_valid()
assert form.errors['homepage'][0][1] == u'Enter a valid URL.'
def test_homepage_is_not_required(self):
delicious = Addon.objects.get()
form = forms.AddonFormDetails(
{'default_locale': 'en-US'},
request=self.request, instance=delicious)
assert form.is_valid()
def test_slug_isdigit(self):
delicious = Addon.objects.get()
form = forms.AddonFormBasic({'slug': '123'}, request=self.request,
instance=delicious)
assert not form.is_valid()
assert form.errors['slug'] == (
[u'The slug cannot be "123". Please choose another.'])
class TestTagsForm(TestCase):
fixtures = ['base/addon_3615', 'base/users']
def setUp(self):
super(TestTagsForm, self).setUp()
self.addon = Addon.objects.get(pk=3615)
category = Category.objects.get(pk=22)
category.db_name = 'test'
category.save()
self.data = {
'summary': str(self.addon.summary),
'name': str(self.addon.name),
'slug': self.addon.slug,
}
self.user = self.addon.authors.all()[0]
core.set_user(self.user)
self.request = req_factory_factory('/')
def add_tags(self, tags):
data = self.data.copy()
data.update({'tags': tags})
form = forms.AddonFormBasic(data=data, request=self.request,
instance=self.addon)
assert form.is_valid()
form.save(self.addon)
return form
def get_tag_text(self):
return [t.tag_text for t in self.addon.tags.all()]
def test_tags(self):
self.add_tags('foo, bar')
assert self.get_tag_text() == ['bar', 'foo']
def test_tags_xss(self):
self.add_tags('<script>alert("foo")</script>, bar')
assert self.get_tag_text() == ['bar', 'scriptalertfooscript']
def test_tags_case_spaces(self):
self.add_tags('foo, bar')
self.add_tags('foo, bar , Bar, BAR, b a r ')
assert self.get_tag_text() == ['b a r', 'bar', 'foo']
def test_tags_spaces(self):
self.add_tags('foo, bar beer')
assert self.get_tag_text() == ['bar beer', 'foo']
def test_tags_unicode(self):
self.add_tags(u'Österreich')
assert self.get_tag_text() == [u'Österreich'.lower()]
def add_restricted(self, *args):
if not args:
args = ['i_am_a_restricted_tag']
for arg in args:
tag = Tag.objects.create(tag_text=arg, restricted=True)
AddonTag.objects.create(tag=tag, addon=self.addon)
def test_tags_restricted(self):
self.add_restricted()
self.add_tags('foo, bar')
form = forms.AddonFormBasic(data=self.data, request=self.request,
instance=self.addon)
assert form.fields['tags'].initial == 'bar, foo'
assert self.get_tag_text() == ['bar', 'foo', 'i_am_a_restricted_tag']
self.add_tags('')
assert self.get_tag_text() == ['i_am_a_restricted_tag']
def test_tags_error(self):
self.add_restricted('i_am_a_restricted_tag', 'sdk')
data = self.data.copy()
data.update({'tags': 'i_am_a_restricted_tag'})
form = forms.AddonFormBasic(data=data, request=self.request,
instance=self.addon)
assert form.errors['tags'][0] == (
'"i_am_a_restricted_tag" is a reserved tag and cannot be used.')
data.update({'tags': 'i_am_a_restricted_tag, sdk'})
form = forms.AddonFormBasic(data=data, request=self.request,
instance=self.addon)
assert form.errors['tags'][0] == (
'"i_am_a_restricted_tag", "sdk" are reserved tags and'
' cannot be used.')
@patch('olympia.access.acl.action_allowed')
def test_tags_admin_restricted(self, action_allowed):
action_allowed.return_value = True
self.add_restricted('i_am_a_restricted_tag')
self.add_tags('foo, bar')
assert self |
from collections import namedtuple
import select
StreamEvent = namedtuple( 'StreamEvent', [ 'fd', 'stream', 'data', 'direction', 'num_bytes', 'eof' ] )
class StreamWatcher(object):
def __init__( self ):
if _best_backend is None:
raise Exception( "No poll/queue backend could be found for your OS." )
self.backend = _best_backend( )
self.fd_map = {}
self.stream_map = {}
def watch( self, fd, data=None, read=True, write=False ):
# allow python file-like objects that have a backing fd
if hasattr(fd, 'fileno') and callable(fd.fileno):
stream = fd
fd = stream.fileno()
self.stream_map[fd] = stream
else:
self.stream_map[fd] = None
# associate user data with the fd
self.fd_map[fd] = data
# prepare any event filter additions
if read:
self.backend.watch_read( fd )
if write:
self.backend.watch_write( fd )
def wait( self, timeout=None, max_events=4 ):
return self.backend.wait(
timeout=timeout,
max_events=max_events,
fd_data_map=self.fd_map,
fd_stream_map=self.stream_map )
_best_backend = None
try:
from select import kqueue, kevent
except ImportError:
pass
else:
class KQueueBackend(object):
def __init__( self ):
self.kq = kqueue( )
def watch_read( self, fd ):
event = kevent( fd, filter=select.KQ_FILTER_READ, flags=select.KQ_EV_ADD )
self._add_events( [event] )
def watch_write( self, fd ):
event = kevent( fd, filter=select.KQ_FILTER_WRITE, flags=select.KQ_EV_ADD )
self._add_events( [event] )
def _add_events( self, new_events ):
e = self.kq.control( new_events, 0, 0 )
assert len(e) == 0, "Not expecting to receive any events while adding filters."
def wait( self, timeout=None, max_event | s=4, fd_data_map={}, fd_stream_map={} ):
r_events = self.kq.control( None, max_events, timeout )
e = []
for event in r_events:
fd = event.ident
if fd in fd_data_map:
stream = fd_stream_map.get( fd, None )
data = fd_data_map.get( fd, None )
|
direction = 'read' if event.filter == select.KQ_FILTER_READ else 'write'
num_bytes = event.data
eof = ( event.flags & select.KQ_EV_EOF != 0 )
e.append( StreamEvent( fd, stream, data, direction, num_bytes, eof ) )
return e
if _best_backend is None:
_best_backend = KQueueBackend
try:
from select import epoll
from fcntl import ioctl
import array
import termios
except ImportError:
pass
else:
class EPollBackend(object):
def __init__( self ):
self.ep = epoll( )
def watch_read( self, fd ):
self.ep.register( fd, select.EPOLLIN )
def watch_write( self, fd ):
self.ep.register( fd, select.EPOLLOUT )
def wait( self, timeout=None, max_events=None, fd_data_map={}, fd_stream_map={} ):
if max_events is None:
max_events = -1
if timeout is None:
timeout = -1
r_events = self.ep.poll( timeout, max_events )
e = []
for fd, event in r_events:
if fd in fd_data_map:
buf = array.array( 'i', [0] )
ioctl( fd, termios.FIONREAD, buf, 1 )
stream = fd_stream_map.get( fd, None )
data = fd_data_map.get( fd, None )
num_bytes = buf[0]
eof = ( event & (select.EPOLLHUP | select.EPOLLERR) != 0 )
if event & select.EPOLLIN != 0:
e.append( StreamEvent( fd, stream, data, 'read', num_bytes, eof ) )
if event & select.EPOLLOUT != 0:
e.append( StreamEvent( fd, stream, data, 'write', num_bytes, eof ) )
return e
if _best_backend is None:
_best_backend = EPollBackend
|
from django.conf.urls import include, url
from django.urls import path
from login import views
from django.contrib.auth.views import PasswordResetCompleteView, PasswordResetConfirmView, PasswordResetDoneView
urlpatterns = [
path('password_reset/', views.PasswordResetView.as_view(
html_email_template_name="registration/password_reset_email.html",
email_template_name="registration/password_reset_email.txt",
template_name='registration/custom_password_reset_form.html'), name='password_reset'),
path('password_reset/done/', PasswordResetDoneView.as_view(template_name = 'registration/custom_password_reset_done.html'), name='password_reset_done'),
path('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(template_name = 'registration/custom_password_reset_confirm.html'), name='password_reset_confirm'),
path('reset/done/', PasswordResetCompleteView.as_view(template_name='registration/custom_password_reset_complete.html'), name='password_reset_complete'),
url("^", include("django.contrib.auth.urls")),
url(r"^profile/(?P<user_id>[\d]+)$", views.ProfileView.as_view(), name="input"),
url(
r"^profile/password_change$",
views.OEPPasswordChangeView.as_view(),
name="input",
),
url(
r"^profile/(?P<user_id>[\d]+)/edit$", views.EditUserView.as_view(), name="input"
),
url(r"^groups/$", views.GroupManagement.as_view(), name="input"),
url(
r"^groups/new/$",
views.GroupCreate.as_view(),
name="input",
),
url(
r"^groups/(?P<group_id>[\w\d_\s]+)/edit$",
| views.GroupCreate.as_view(),
name="input",
),
url(
r"^groups/(?P<group_id>[\w\d_\s]+)/$",
views.GroupView | .as_view(),
),
url(
r"^groups/(?P<group_id>[\w\d_\s]+)/members$",
views.GroupEdit.as_view(),
name="input",
),
url(r"^groups/new/$", views.GroupCreate.as_view(), name="input"),
url(r"^register$", views.CreateUserView.as_view()),
url(r"^detach$", views.DetachView.as_view()),
url(r"^activate/(?P<token>[\w\d\-\s]+)$", views.activate),
url(r"^activate/$", views.ActivationNoteView.as_view(), name="activate"),
]
|
# Copyright 2020, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li | cense.
# 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 Licen | se 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.
"""Libraries for interacting with a computation."""
|
# coding=utf-8
from abc import ABCMeta, abstractmethod
from typing import Optional
from weakref import ref
from logging import getLogger
from ultros.core.networks.base.connectors import base as base_connector
from ultros.core.networks.base.networks import base as base_network
__author__ = "Gareth Coles"
class BaseServer(metaclass=ABCMeta):
def __init__(self, name: str, network: "base_network.BaseNetwork"):
self.name = name
| self._network = ref(network)
self.logger = getLogger(self.name) # TODO: Logging
@property
def network(self) -> "base_network.BaseNetwork":
return self._network()
@abstractmethod
async def connector_connected(self, connector: "base_connector.BaseConnector"):
| pass
@abstractmethod
async def connector_disconnected(self, connector: "base_connector.BaseConnector",
exc: Optional[Exception]):
pass
|
from emburse.resource import (
EmburseObject,
Account,
Allowance,
Card,
Category,
Company,
Department,
Label,
Location,
Member,
SharedLink,
Statement,
Transaction
)
class Client(EmburseObject):
"""
Emburse API Client
API enables for the creation of expense cards at scale for custom business solutions as well as for
third-party app integrations. Cards can be created with set spending limits and assigned with just an email.
Some use cases include vendor payments, employee expense control, and fleet card management.
API Version:
v1
API Docs:
https://www.emburse.com/api/v1/docs#getting-started
Authors:
Marc Ford <marc.ford@gmail.com>
"""
@property
def Account(self):
"""
Emburse Account Object,
configured with the auth token from the client
:return: A configured emburse.resource.Account
:rtype: Account
"""
return Account(auth_token=self.auth_token)
@property
def Allowance(self):
"""
Emburse Allowance Object,
configured with the auth token from the client
:return: A configured emburse.resource.Allowance
:rtype: Allowance
"""
return Allowance(auth_token=self.auth_token)
@property
def Card(self):
"""
Emburse Card Object,
configured with the auth token from the client
:return: A configured emburse.resource.Card
:rtype: Card
"""
return Card(auth_token=self.auth_token)
@property
def Category(self):
"""
Emburse Category Object,
configured with the auth token from the client
:return: A configured emburse.resource.Category
:rtype: Category
"""
return Category(auth_token=self.auth_token)
@property
def Company(self):
"""
Emburse Company Object,
configured with the auth token from the client
:return: A configured emburse.resource.Company
:rtype: Company
"""
return Company(auth_token=self.auth_token)
@property
def Department(self):
"""
Emburse Department Object,
configured with the auth to | ken from the client
:return: A configured emburse.resource.Department
:rtype: Department
"""
return Department(auth_token=self.auth_token)
@property
def Label(self):
"""
Emburse Label Object,
configured with the auth token from the client
:return: A configured emburse.resource.Label
| :rtype: Label
"""
return Label(auth_token=self.auth_token)
@property
def Location(self):
"""
Emburse Location Object,
configured with the auth token from the client
:return: A configured emburse.resource.Location
:rtype: Location
"""
return Location(auth_token=self.auth_token)
@property
def Member(self):
"""
Emburse Member Object,
configured with the auth token from the client
:return: A configured emburse.resource.Member
:rtype: Member
"""
return Member(auth_token=self.auth_token)
@property
def SharedLink(self):
"""
Emburse SharedLink Object,
configured with the auth token from the client
:return: A configured emburse.resource.SharedLink
:rtype: SharedLink
"""
return SharedLink(auth_token=self.auth_token)
@property
def Statement(self):
"""
Emburse Statement Object,
configured with the auth token from the client
:return: A configured emburse.resource.Statement
:rtype: Statement
"""
return Statement(auth_token=self.auth_token)
@property
def Transaction(self):
"""
Emburse Transaction Object,
configured with the auth token from the client
:return: A configured emburse.resource.Transaction
:rtype: Transaction
"""
return Transaction(auth_token=self.auth_token)
|
_offset = "UTC Offset"
self.messages.label_image = "Profile Image"
self.messages.help_utc_offset = "The time difference between UTC and your timezone, specify as +HHMM for eastern or -HHMM for western timezones."
self.messages.help_mobile_phone = "Entering a phone number is optional, but doing so allows you to subscribe to receive SMS messages."
self.messages.help_organisation = "Entering an Organization is optional, but doing so directs you to the appropriate approver & means you automatically get the appropriate permissions."
self.messages.help_image = "You can either use %(gravatar)s or else upload a picture here. The picture will be resized to 50x50."
#self.messages.logged_in = "Signed In"
#self.messages.submit_button = "Signed In"
#self.messages.logged_out = "Signed Out"
self.messages.lock_keys = True
# S3Permission
self.permission = S3Permission(self)
# Set to True to override any authorization
self.override = False
# Site types (for OrgAuth)
T = current.T
if deployment_settings.get_ui_camp():
shelter = T("Camp")
else:
shelter = T("Shelter")
self.org_site_types = Storage(
cr_shelter = shelter,
#org_facility = T("Facility"),
org_facility = T("Site"),
org_office = T("Office"),
hms_hospital = T("Hospital"),
#project_site = T("Project Site"),
#fire_station = T("Fire Station"),
)
# -------------------------------------------------------------------------
def define_tables(self, migrate=True, fake_migrate=False):
"""
to be called unless tables are defined manually
usages::
# defines all needed tables and table files
# UUID + "_auth_user.table", ...
auth.define_tables()
# defines all needed tables and table files
# "myprefix_auth_user.table", ...
auth.define_tables(migrate="myprefix_")
# defines all needed tables without migration/table files
auth.define_tables(migrate=False)
"""
db = current.db
request = current.request
session = current.session
settings = self.settings
messages = self.messages
# User table
if not settings.table_user:
passfield = settings.password_field
if settings.username_field:
# with username (not used by default in Sahana)
settings.table_user = db.define_table(
settings.table_user_name,
Field("first_name", length=128, default="",
label=messages.label_first_name),
Field("last_name", length=128, default="",
label=messages.label_last_name),
Field("username", length=128, default="",
unique=True),
Field(passfield, "password", length=512,
readable=False, label=messages.label_password),
Field("email", length=512, default="",
label=messages.label_email),
Field("language", length=16),
Field("utc_offset", length=16,
readable=False, writable=False),
Field("organisation_id", "integer",
writable=False,
label=messages.label_organisation_id),
Field("site_id", "integer",
writable=False,
label=messages.label_site_id),
Field("registration_key", length=512,
writable=False, readable=False, default="",
label=messages.label_registration_key),
Field("reset_password_key", length=512,
writable=False, readable=False, default="",
label=messages.label_registration_key),
Field("deleted", "boolean", writable=False,
readable=False, default=False),
Field("timestmp", "datetime", writable=False,
readable=False, default=""),
migrate = migrate,
fake_migrate=fake_migrate,
*(s3_uid()+s3_timestamp()))
else:
# with email-address (Sahana default)
settings.table_user = db.define_table(
settings.table_user_name,
Field("first_name", length=128, default="",
label=messages.label_first_name),
Field("last_name", length=128, default="",
label=messages.label_last_name),
Field("email", length=512, default="",
label=messages.label_email,
unique=True),
Field(passfield, "password", length=512,
readable=False, label=messages.label_password),
Field("language", length=16),
Field("utc_offset", length=16,
readable=False,
writable=False,
label=messages.label_utc_offset),
Field("organisation_id", "integer",
writable=False,
label=messages.label_organisation_id),
Field("site_id", "integer",
writable=False,
label=messages.label_site_id),
Field("registration_key", length=512,
writable=False, readable=False, default="",
label=messages.label_registration_key),
Field("reset_password_key", length=512,
writable=False, readable=False, default="",
label=messages.label_registration_key),
Field("deleted", "boolean", writable=False,
readable=False, default=False),
Field("timestmp", "datetime", writable=False,
readable=False, default=""),
migrate = migrate,
fake_migrate=fake_migrate,
*(s3_uid()+s3_timestamp()))
table = settings.table_user
table.first_name.notnull = True
table.first_name.requires = \
IS_NOT_EMPTY(error_message=messages.is_empty)
if current.deployment_settings.get_L10n_mandatory_lastname():
table.last_name.notnull = True
table.last_name.requires = \
IS_NOT_EMPTY(error_message=messages.is_empty)
table.utc_offset.comment = A(SPAN("[Help]"),
_class="tooltip",
_title="%s|%s" % (messages.label_utc_offset,
| messages.help_utc_offset))
try:
from s3validators import IS_UTC_OFFSET
table.utc_offset.requires = IS_EMPTY_OR(IS_UTC_OFFSET())
except:
pass
table[pa | ssfield].requires = [CRYPT(key=settings.hmac_key,
min_length=self.settings.password_min_length,
digest_alg="sha512")]
if settings.username_field:
table.username.requires = IS_NOT_IN_DB(db,
"%s.username" % settings.table_user._tablename)
table.email.requires = \
|
from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='odin',
version='0.4.2',
url='https://github.com/timsavage/odin',
license='LICENSE',
author='Tim Savage',
author_email='tim.savage@poweredbypenguins.org',
descrip | tion='Object Data Mapping for Python',
long_description=long_description,
packages=find_packages(),
install_requires=['six'],
extras_require={
# | Documentation generation
'doc_gen': ["jinja2>=2.7"],
# Pint integration
'pint': ["pint"],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
# -*- coding: utf-8 -*-
#
# Yelandur documentation build configuration file, created by
# sphinx-quickstart on Thu Jan 10 16:10:42 2013.
#
# 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
# 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.
#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.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.mathjax', '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-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Yelandur'
copyright = u'2013, Sébastien Lerique'
# 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 = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# 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 = []
# 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 = 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 = []
# -- 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 = '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 = 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']
# 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 = 'Yelandurdoc'
# -- 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]).
latex_documents = [
('index', 'Yelandur.tex', u'Yelandur Documentation',
u'Sébastien Lerique', '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
# -- Options for manual page output --------------------------------------------
# One entry per manual page. | List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'yelandur', u'Yelandur Documentation',
[u'Sébastien Lerique'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target na | me, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Yelandur', u'Yelandur Documentation',
u'Sébastien Lerique', 'Yelandur', 'One line description of project.',
'Miscellaneous'),
]
# 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'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
|
import logging
try:
create_external('xml2', build_helper = 'xml2-config',
version_query = '--version', version_parser = lambda x: 'invalid')
except Exception:
logging.critical('external version parsing')
try:
tools['c'].std = 'latest'
except Exception:
logging.critical('std setting')
try:
shared_library('x', [])
except Exc | eption:
logging.critical('shared_library: empty input')
try:
static_library('x', [])
except Exception:
| logging.critical('static_library: empty input')
|
import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePat | h = os.path.join(path, 'MODEL8687196544.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
| return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString) |
# encoding: utf-8
from ztq_core import async
import time
@async
def send(body):
print 'START: ', body
time.sle | ep(3)
print 'END: ', body
@async(queue='mail')
def send_failed(body):
pr | int 'FAIL START:', body
raise Exception('connection error...')
@async(queue='mail')
def failed_callback(return_code, return_msg):
print 'FAILED CALLBACK:', return_code, return_msg
@async(queue='index')
def index(data):
print 'INDEX:', data
time.sleep(1)
def do_commit():
print 'COMMITTED'
import ztq_worker
ztq_worker.register_batch_queue('index', 5, do_commit)
|
ty is the abstract base class of all Configuration properties."""
def __init__(self):
abc.ABC.__init__(self)
@abc.abstractmethod
def copy(self) -> 'Property':
raise NotImplementedError
@abc.abstractmethod
def unpack(self, value: 'Any', context: 'Context') -> bool:
raise NotImplementedError
@abc.abstractmethod
def pack(self) -> 'Any':
raise NotImplementedError
class PrimitiveProperty(Property, abc.ABC):
def __init__(self, def | ault: 'Any') -> None:
P | roperty.__init__(self)
self._default = default
self._value = default
def __repr__(self) -> str:
return str(self._value)
def __str__(self) -> str:
return str(self._value)
def __bool__(self) -> bool:
return bool(self._value)
def __int__(self) -> int:
return int(self._value)
def __float__(self) -> float:
return float(self._value)
def __eq__(self, other: 'Any') -> bool:
return self._value == other
def __ne__(self, other: 'Any') -> bool:
return self._value != other
def __lt__(self, other: 'Any') -> bool:
return self._value < other
def __le__(self, other: 'Any') -> bool:
return self._value <= other
def __gt__(self, other: 'Any') -> bool:
return self._value > other
def __ge__(self, other: 'Any') -> bool:
return self._value >= other
def pack(self) -> 'Any':
return self._value
class Boolean(PrimitiveProperty):
"""A boolean property."""
def __init__(self, default: bool = False) -> None:
"""Create a new Boolean property.
:param default: The default value of the property
"""
if type(default) is not bool:
raise PropertyTypeError("Boolean", default)
PrimitiveProperty.__init__(self, default)
@property
def value(self) -> bool:
"""The value of the property."""
return self._value
@value.setter
def value(self, value: bool) -> None:
if type(value) is not bool:
raise PropertyTypeError("Boolean", value)
self._value = value
@property
def default(self) -> bool:
"""The default value of the property."""
return self._default
def copy(self) -> 'Boolean':
"""Create a copy of this Boolean Property.
:returns: A copy of this boolean property
"""
b = Boolean(self._default)
b._value = self._value
return b
def unpack(self, value: 'Any', context: 'Context') -> bool:
"""Unpack a YAML value into this Boolean property.
:param value: The value to unpack
:param context: The context of this unpack operation
:returns: If the unpack operation succeeded
"""
if type(value) is not bool:
context.invalid_type(bool, value)
return False
self._value = value
return True
class Integer(PrimitiveProperty):
"""An integer property."""
def __init__(self, default: int = 0) -> None:
"""Create a new Integer property.
:param default: The default value of the property
"""
if type(default) is not int:
raise PropertyTypeError("Integer", default)
PrimitiveProperty.__init__(self, default)
@property
def value(self) -> int:
"""The value of the property."""
return self._value
@value.setter
def value(self, value: int) -> None:
if type(value) is not int:
raise PropertyTypeError("Integer", value)
self._value = value
@property
def default(self) -> int:
"""The default value of the property (read-only)."""
return self._default
def copy(self) -> 'Integer':
"""Create a copy of this Integer Property.
:returns: A copy of this Integer
"""
i = Integer(self._default)
i._value = self._value
return i
def unpack(self, value: 'Any', context: 'Context') -> bool:
"""Unpack a YAML value into this Integer Property.
The value being unpacked must be an int, otherwise an error is written
to the context and False is returned.
:param value: The value to unpack
:param context: The context of this unpack operation
:returns: If the unpack operation succeeded
"""
if type(value) is not int:
context.invalid_type(int, value)
return False
self._value = value
return True
class Float(PrimitiveProperty):
"""A Float property."""
def __init__(self, default: float = 0.0) -> None:
"""Create a new Float property.
:param default: The default value of the property
"""
if type(default) is not float:
raise PropertyTypeError("Float", default)
PrimitiveProperty.__init__(self, default)
@property
def value(self) -> float:
"""The value of the property."""
return self._value
@value.setter
def value(self, value: float) -> None:
if type(value) is not float:
raise PropertyTypeError("Float", value)
self._value = value
@property
def default(self) -> int:
"""The default value of the property (read-only)."""
return self._default
def copy(self) -> 'Float':
"""Create a copy of this Float Property.
:returns: A copy of this Float
"""
f = Float(self._default)
f._value = self._value
return f
def unpack(self, value: 'Any', context: 'Context') -> bool:
"""Unpack a YAML value into this Float Property.
The value being unpacked must be either a float or an int, otherwise
an error is written to the context and False is returned.
:param value: The value to unpack
:param context: The context of this unpack operation
:returns: If the unpack operation succeeded
"""
if type(value) is int or type(value) is float:
self._value = float(value)
return True
context.invalid_type(float, value)
return False
class String(PrimitiveProperty):
def __init__(self, default: str = "", allow_empty: bool = True,
strip: bool = False) -> None:
if type(default) is not str:
raise PropertyTypeError("String", default)
if strip:
default = default.strip()
if not allow_empty and default == "":
raise ValueError("may not be empty")
PrimitiveProperty.__init__(self, default)
self._allow_empty = allow_empty
self._strip = strip
@property
def value(self) -> str:
return self._value
@value.setter
def value(self, value: str) -> None:
if type(value) is not str:
raise PropertyTypeError("String", value)
if self._strip:
value = value.strip()
if not self._allow_empty and value == "":
raise ValueError("may not be empty")
self._value = value
@property
def default(self) -> str:
return self._default
def copy(self) -> 'String':
"""Create a copy of this String Property.
:returns: A copy of this String
"""
s = String(self._default, self._allow_empty, self._strip)
s._value = self._value
return s
def unpack(self, value: 'Any', context: 'Context') -> bool:
"""Unpack a YAML value into this String Property.
The value being unpacked must be a str, otherwise an error is written
to the context and False is returned.
:param value: The value to unpack
:param context: The context of this unpack operation
:returns: If the unpack operation succeeded
"""
if type(value) is not str:
context.invalid_type(str, value)
return False
if self._strip:
value = value.strip()
if value == "" and not self._allow_empty:
context.error("may not be empty")
return False
self._value = value
return True
class EnumValueErro |
from __future__ import unicode_literals
from django.test import TestCase
from wtl.wtlib.models import Library, LibraryVersion
from wtl.wtlib.tests.factories import (LibraryFactory, LibraryVersionFactory,
ProjectFactory)
class LibraryTestCase(TestCase):
def test_str(self):
x = LibraryFactory()
self.assertEqual(str(x), x.name)
class LibraryVersionTestCase(TestCase):
def test_str(self):
x = LibraryVersionFactory()
self.assertEqual(str(x), x.library.name + ' ' + x.version)
def test_update_totals(self):
l1 = LibraryFactory(name='l1')
l1v1 = LibraryVersionFactory(library=l1, version="1")
l1v2 = LibraryVersionFactory(library=l1, version="2")
l2 = LibraryFactory(name='l2')
l2v1 = LibraryVersionFactory(library=l2, version="1")
l2v2 = LibraryVersionFactory(library=l2, version="2")
p = ProjectFactory()
p.libraries.add(l1v1)
p.libraries.add(l1v2)
p.libraries.add(l2v1)
LibraryVersion.update_totals(project=p)
self.assertEqual(Library.objects.get(id=l1.id).total_users, 2)
self.assertEqual(Library.objects.get(id=l2.id).total_users, 1)
self.assertEqual(LibraryVersion.objects.get(id=l1v1.id).total_users, 1)
self.assertEqual(LibraryVersion.objects.get(id=l1v2.id).total_users, 1)
self.assertEqual(LibraryVersion.objects.get(id | =l2v1.id).total_users, 1)
self.assertEqual(LibraryVersion.objects.get(id=l2v2.id).total_users, 0)
def test_often_used_with(self):
lib1 = LibraryFactory()
lib2 = LibraryFactory()
lib3 = LibraryFactory()
lib4 = LibraryFactory()
ver1 = LibraryVersionFactory(library=lib1)
project_1_2 = ProjectFactory()
project_1_2.libraries.add(ver1)
project_1_2.libraries.add(LibraryVersionFactory(library=lib2))
project_1 | _2__2 = ProjectFactory()
project_1_2__2.libraries.add(ver1)
project_1_2__2.libraries.add(LibraryVersionFactory(library=lib2))
project_1_3 = ProjectFactory()
project_1_3.libraries.add(LibraryVersionFactory(library=lib1))
project_1_3.libraries.add(LibraryVersionFactory(library=lib3))
project_2_3_4 = ProjectFactory()
project_2_3_4.libraries.add(LibraryVersionFactory(library=lib2))
project_2_3_4.libraries.add(LibraryVersionFactory(library=lib3))
project_2_3_4.libraries.add(LibraryVersionFactory(library=lib4))
lib1_result = lib1.often_used_with()
self.assertEqual(lib2.name, lib1_result[0].name)
self.assertEqual(2, lib1_result[0].usage_count)
self.assertEqual(lib3.name, lib1_result[1].name)
self.assertEqual(1, lib1_result[1].usage_count)
class ProjectTestCase(TestCase):
def test_str(self):
x = ProjectFactory()
self.assertEqual(str(x), x.name)
|
import os
from configurations.wsgi import get_wsgi_application
from whitenoise.django import Dj | angoWhiteNoise
os.environ.setdefa | ult("DJANGO_SETTINGS_MODULE", "morgoth.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Production")
application = DjangoWhiteNoise(get_wsgi_application())
|
#----------------------------------------------------------------------------
#
# Copyright (c) 2014, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in /LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
#
#----------------------------------------------------------------------------
from __future__ import unicode_literals
import ast
import traceback
import sys
import inspect
from _ast import ClassDef, Assign
from sphinx.ext.autodoc import ClassLevelDocumenter
from traits.has_traits import MetaHasTraits
from traits.trait_handlers import TraitType
def is_class_trait(name, cls):
""" Check if the name is in the list of class defined traits of ``cls``.
"""
return isinstance(cls, MetaHasTraits) and name in cls.__class_traits__
class TraitDocumenter(ClassLevelDocumenter):
""" Specialized Documenter subclass for trait attributes.
The class defines a new documenter that recovers the trait definition
signature of module level and class level traits.
To use the documenter, append the module path in the extension
attribute of the `conf.py`.
.. warning::
Using the TraitDocumenter in conjunction with TraitsDoc is not
advised.
"""
objtype = 'traitattribute'
directivetype = 'attribute'
member_order = 60
# must be higher than other attribute documenters
priority = 12
@classmethod
def can_document_member(cls, member, membername, isattr, parent):
""" Check that the documented member is a trait instance.
"""
return (
isattr and
issubclass(type(member), TraitType) or
is_class_trait(membername, parent.object))
def document_members(self, all_members=False):
# Trait attributes have no members """
pass
def add_content(self, more_content, no_docstring=False):
# Never try to get a docstring from the trait object.
ClassLevelDocumenter.add_content(
self, more_content, no_docstring=True)
def import_object(self):
""" Get the Trait object.
Notes
-----
Code adapted from autodoc.Documenter.import_object.
"""
try:
__import__(self.modname)
cur | rent = self.module = sys.modules[self.modname]
for part in self.objpath[:-1]:
current = self.get_attr(current, part)
name = self.objpath[-1]
self.object_name = name
self.object = None
self.parent = current
return True
# this used to only catch SyntaxError, ImportError and
# AttributeError, but importing m | odules with side effects can raise
# all kinds of errors.
except Exception as err:
if self.env.app and not self.env.app.quiet:
self.env.app.info(traceback.format_exc().rstrip())
msg = (
'autodoc can\'t import/find {0} {r1}, it reported error: '
'"{2}", please check your spelling and sys.path')
self.directive.warn(msg.format(
self.objtype, str(self.fullname), err))
self.env.note_reread()
return False
def add_directive_header(self, sig):
""" Add the sphinx directives.
Add the 'attribute' directive with the annotation option
set to the trait definition.
"""
ClassLevelDocumenter.add_directive_header(self, sig)
definition = self.get_trait_definition()
self.add_line(
' :annotation: = {0}'.format(definition), '<autodoc>')
def get_trait_definition(self):
""" Retrieve the Trait attribute definition
"""
# Get the class source and tokenize it.
source = inspect.getsource(self.parent)
nodes = ast.parse(source)
for node in ast.iter_child_nodes(nodes):
if isinstance(node, ClassDef):
parent_node = node
break
else:
return ''
for node in ast.iter_child_nodes(parent_node):
if isinstance(node, Assign):
name = node.targets[0]
if name.id == self.object_name:
break
else:
return ''
endlineno = name.lineno
for item in ast.walk(node):
if hasattr(item, 'lineno'):
endlineno = max(endlineno, item.lineno)
definition_lines = [
line.strip()
for line in source.splitlines()[name.lineno-1:endlineno]]
definition = ''.join(definition_lines)
equal = definition.index('=')
return definition[equal + 1:].lstrip()
|
from scipy.spatial.distance i | mport cdist
import numpy as np
class KNNC1(object):
def fit(self, X, Y):
self.X = X
self.Y = Y
def predict(self, Z):
dists = cdist(self.X, Z, 'correlation')
indices = dists.argmin(axis = 0)
return self.Y[indices]
def predict_proba(self, Z):
predictions = self.predict(Z)
result = np.zeros((Z.shape[0], np.unique(self.Y).size))
result[:,predictions-1] = | 1
return result
|
elf, exploration_id, prerequisite_skills, acquired_skills):
self.exploration_id = exploration_id
self.prerequisite_skills = prerequisite_skills
self.acquired_skills = acquired_skills
def to_dict(self):
return {
'exploration_id': self.exploration_id,
'prerequisite_skills': self.prerequisite_skills,
'acquired_skills': self.acquired_skills
}
@classmethod
def from_dict(cls, node_dict):
return cls(
copy.deepcopy(node_dict['exploration_id']),
copy.deepcopy(node_dict['prerequisite_skills']),
copy.deepcopy(node_dict['acquired_skills']))
@property
def skills(self):
"""Returns a set of skills where each prerequisite and acquired skill
in this collection node is represented at most once.
"""
return set(self.prerequisite_skills) | set(self.acquired_skills)
def update_prerequisite_skills(self, prerequisite_skills):
self.prerequisite_skills = copy.deepcopy(prerequisite_skills)
def update_acquired_skills(self, acquired_skills):
self.acquired_skills = copy.deepcopy(acquired_skills)
def validate(self):
"""Validates various properties of the collection node."""
if not isinstance(self.exploration_id, basestring):
raise utils.ValidationError(
'Expected exploration ID to be a string, received %s' %
self.exploration_id)
if not isinstance(self.prerequisite_skills, list):
raise utils.ValidationError(
'Expected prerequisite_skills to be a list, received %s' %
self.prerequisite_skills)
if len(set(self.prerequisite_skills)) != len(self.prerequisite_skills):
raise utils.ValidationError(
'The prerequisite_skills list has duplicate entries: %s' %
self.prerequisite_skills)
for prerequisite_skill in self.prerequisite_skills:
if not isinstance(prerequisite_skill, basestring):
raise utils.ValidationError(
'Expected all prerequisite skills to be strings, '
'received %s' % prerequisite_skill)
if not isinstance(self.acquired_skills, list):
raise utils.ValidationError(
'Expected acquired_skills to be a list, received %s' %
self.acquired_skills)
if len(set(self.acquired_skills)) != len(self.acquired_skills):
raise utils.ValidationError(
'The acquired_skills list has duplicate entries: %s' %
self.acquired_skills)
for acquired_skill in self.acquired_skills:
if not isinstance(acquired_skill, basestring):
raise utils.ValidationError(
'Expected all acquired skills to be strings, received %s' %
acquired_skill)
redundant_skills = (
set(self.prerequisite_skills) & set(self.acquired_skills))
if redundant_skills:
raise utils.ValidationError(
'There are some skills which are both required for '
'exploration %s and acquired after playing it: %s' %
(self.exploration_id, redundant_skills))
@classmethod
def create_default_node(cls, exploration_id):
return cls(exploration_id, [], [])
class Collection(object):
"""Domain object for an Oppia collection."""
"""Constructs a new collection given all the information necessary to
represent a collection.
Note: The schema_version represents the version of any underlying
dictionary or list structures stored within the collection. In particular,
the schema for CollectionNodes is represented by this version. If the
schema for CollectionNode changes, then a migration function will need to
be added to this class to convert from the current schema version to the
new one. This function should be called in both from_yaml in this class and
collection_services._migrate_collection_to_latest_schema.
feconf.CURRENT_COLLECTION_SCHEMA_VERSION should be incremented and the new
value should be saved in the collection after the migration process,
ensuring it represents the latest schema version.
"""
def __init__(self, collection_id, title, category, objective,
schema_version, nodes, version, created_on=None,
last_updated=None):
self.id = collection_id
self.title = title
self.category = category
self.objective = objective
self.schema_version = schema_version
self.nodes = nodes
self.version = version
self.created_on = created_on
self.last_updated = last_updated
def to_dict(self):
return {
'id': self.id,
'title': self.title,
| 'category': self.category,
'objective': self.objective,
'schema_version': self.schema_version,
'nodes': [
node.to_dict() for node in self.nodes
]
}
@classmethod
def create_default_collection(
cls, collection_id, title, category, objective):
return cls(
collection_id, title, category, objective,
feconf.CURRENT_COLLECTI | ON_SCHEMA_VERSION, [], 0)
@classmethod
def from_dict(
cls, collection_dict, collection_version=0,
collection_created_on=None, collection_last_updated=None):
collection = cls(
collection_dict['id'], collection_dict['title'],
collection_dict['category'], collection_dict['objective'],
collection_dict['schema_version'], [], collection_version,
collection_created_on, collection_last_updated)
for node_dict in collection_dict['nodes']:
collection.nodes.append(
CollectionNode.from_dict(node_dict))
return collection
def to_yaml(self):
collection_dict = self.to_dict()
# The ID is the only property which should not be stored within the
# YAML representation.
del collection_dict['id']
return utils.yaml_from_dict(collection_dict)
@classmethod
def from_yaml(cls, collection_id, yaml_content):
try:
collection_dict = utils.dict_from_yaml(yaml_content)
except Exception as e:
raise Exception(
'Please ensure that you are uploading a YAML text file, not '
'a zip file. The YAML parser returned the following error: %s'
% e)
collection_dict['id'] = collection_id
return Collection.from_dict(collection_dict)
@property
def skills(self):
"""The skills of a collection are made up of all prerequisite and
acquired skills of each exploration that is part of this collection.
This returns a sorted list of all the skills of the collection.
"""
unique_skills = set()
for node in self.nodes:
unique_skills.update(node.skills)
return sorted(unique_skills)
@property
def exploration_ids(self):
"""Returns a list of all the exploration IDs that are part of this
collection.
"""
return [
node.exploration_id for node in self.nodes]
@property
def init_exploration_ids(self):
"""Returns a list of exploration IDs that are starting points for this
collection (ie, they require no prior skills to complete). The order
of these IDs is given by the order each respective exploration was
added to the collection.
"""
init_exp_ids = []
for node in self.nodes:
if not node.prerequisite_skills:
init_exp_ids.append(node.exploration_id)
return init_exp_ids
def get_next_exploration_ids(self, completed_exploration_ids):
"""Returns a list of exploration IDs for which the prerequisite skills
are satisfied. These are the next explorations to complete for a user.
If the list returned is em |
__author__ = 'aakilomar'
import requests, json, time
requests.packages.urllib3.disable_warnings()
host = "https://localhost:8443"
#from rest_requests import add_user
def add_user(phone):
post_url = host + "/api/user/add/" + str(phone)
return requests.post(post_url,None, verify=False).json()
def add_group(userid,pho | nenumbers):
post_url = host + "/api/group/add/" + str(userid) + "/" + phonenumbers
return requests.post(post_url,None, verify=False).json()
#/add/{userId}/{groupId}/{issue}
def add_vote(userid,groupid,issue):
post_url = host + "/api/vote/add/" + str(userid) + "/" + str(groupid) + "/" + issue
return requests.post(post_url,None, verify=False).json()
def vote_l | ist():
list_url = host + "/api/vote/listallfuture"
r = requests.get(list_url)
print r.json
print r.text
def set_event_time(eventid,time):
post_url = host + "/api/event/settime/" + str(eventid) + "/" + time
return requests.post(post_url,None, verify=False).json()
def rsvp(eventid,userid,message):
post_url = host + "/api/event/rsvp/" + str(eventid) + "/" + str(userid) + "/" + str(message)
return requests.post(post_url,None, verify=False).json()
def add_user_to_group(userid,groupid):
post_url = host + "/api/group/add/usertogroup/" + str(userid) + "/" + str(groupid)
return requests.post(post_url,None, verify=False).json()
def manualreminder(eventid,message):
post_url = host + "/api/event/manualreminder/" + str(eventid) + "/" + str(message)
return requests.post(post_url,None, verify=False).json()
user = add_user("0826607134")
group = add_group(user['id'],"0821111111")
user2 = add_user("0821111112")
group = add_user_to_group(user2['id'],group['id'])
print user
print group
issue = add_vote(user['id'], group['id'],"test vote")
print issue
#future_votes = vote_list()
#print future_votes
issue = set_event_time(issue['id'],"30th 7pm")
r = rsvp(issue['id'],user['id'],"yes")
r2 = rsvp(issue['id'],user2['id'],"no")
r = rsvp(issue['id'],user['id'],"yes")
ok = manualreminder(issue['id'],"|") # should use reminder mesage
ok = manualreminder(issue['id'],"my manual messsage")
|
if key in self.headers:
value = self.headers[key]
else:
value = fallback or []
return value
def add(self, key, value):
"""add header value"""
if key not in self.headers:
self.headers[key] = []
self.headers[key].append(value)
if self.sent_time:
self.modified_since_sent = True
def attach(self, attachment, filename=None, ctype=None):
"""
attach a file
:param attachment: File to attach, given as
:class:`~alot.db.attachment.Attachment` object or path to a file.
:type attachment: :class:`~alot.db.attachment.Attachment` or str
:param filename: filename to use in content-disposition.
Will be ignored if `path` matches multiple files
:param ctype: force content-type to be used for this attachment
:type ctype: str
"""
if isinstance(attachment, Attachment):
self.attachments.append(attachment)
elif isinstance(attachment, str):
path = os.path.expanduser(attachment)
part = helper.mimewrap(path, filename, ctype)
self.attachments.append(At | tachment(part))
else:
raise TypeError('attach accepts an Attachment or str')
if self.sent_time:
self.modified_since_sent = True
def construct_mail(self):
"""
compiles the information contained in this envelope into a
:class:`email.Message`.
"""
# Build body text part. To properly sign/encrypt messages later on, we |
# convert the text to its canonical format (as per RFC 2015).
canonical_format = self.body.encode('utf-8')
textpart = MIMEText(canonical_format, 'plain', 'utf-8')
# wrap it in a multipart container if necessary
if self.attachments:
inner_msg = MIMEMultipart()
inner_msg.attach(textpart)
# add attachments
for a in self.attachments:
inner_msg.attach(a.get_mime_representation())
else:
inner_msg = textpart
if self.sign:
plaintext = inner_msg.as_bytes(policy=email.policy.SMTP)
logging.debug('signing plaintext: %s', plaintext)
try:
signatures, signature_str = crypto.detached_signature_for(
plaintext, [self.sign_key])
if len(signatures) != 1:
raise GPGProblem("Could not sign message (GPGME "
"did not return a signature)",
code=GPGCode.KEY_CANNOT_SIGN)
except gpg.errors.GPGMEError as e:
if e.getcode() == gpg.errors.BAD_PASSPHRASE:
# If GPG_AGENT_INFO is unset or empty, the user just does
# not have gpg-agent running (properly).
if os.environ.get('GPG_AGENT_INFO', '').strip() == '':
msg = "Got invalid passphrase and GPG_AGENT_INFO\
not set. Please set up gpg-agent."
raise GPGProblem(msg, code=GPGCode.BAD_PASSPHRASE)
else:
raise GPGProblem("Bad passphrase. Is gpg-agent "
"running?",
code=GPGCode.BAD_PASSPHRASE)
raise GPGProblem(str(e), code=GPGCode.KEY_CANNOT_SIGN)
micalg = crypto.RFC3156_micalg_from_algo(signatures[0].hash_algo)
unencrypted_msg = MIMEMultipart(
'signed', micalg=micalg, protocol='application/pgp-signature')
# wrap signature in MIMEcontainter
stype = 'pgp-signature; name="signature.asc"'
signature_mime = MIMEApplication(
_data=signature_str.decode('ascii'),
_subtype=stype,
_encoder=encode_7or8bit)
signature_mime['Content-Description'] = 'signature'
signature_mime.set_charset('us-ascii')
# add signed message and signature to outer message
unencrypted_msg.attach(inner_msg)
unencrypted_msg.attach(signature_mime)
unencrypted_msg['Content-Disposition'] = 'inline'
else:
unencrypted_msg = inner_msg
if self.encrypt:
plaintext = unencrypted_msg.as_bytes(policy=email.policy.SMTP)
logging.debug('encrypting plaintext: %s', plaintext)
try:
encrypted_str = crypto.encrypt(
plaintext, list(self.encrypt_keys.values()))
except gpg.errors.GPGMEError as e:
raise GPGProblem(str(e), code=GPGCode.KEY_CANNOT_ENCRYPT)
outer_msg = MIMEMultipart('encrypted',
protocol='application/pgp-encrypted')
version_str = 'Version: 1'
encryption_mime = MIMEApplication(_data=version_str,
_subtype='pgp-encrypted',
_encoder=encode_7or8bit)
encryption_mime.set_charset('us-ascii')
encrypted_mime = MIMEApplication(
_data=encrypted_str.decode('ascii'),
_subtype='octet-stream',
_encoder=encode_7or8bit)
encrypted_mime.set_charset('us-ascii')
outer_msg.attach(encryption_mime)
outer_msg.attach(encrypted_mime)
else:
outer_msg = unencrypted_msg
headers = self.headers.copy()
# add Message-ID
if 'Message-ID' not in headers:
headers['Message-ID'] = [email.utils.make_msgid()]
if 'User-Agent' in headers:
uastring_format = headers['User-Agent'][0]
else:
uastring_format = settings.get('user_agent').strip()
uastring = uastring_format.format(version=__version__)
if uastring:
headers['User-Agent'] = [uastring]
# copy headers from envelope to mail
for k, vlist in headers.items():
for v in vlist:
outer_msg.add_header(k, v)
return outer_msg
def parse_template(self, tmp, reset=False, only_body=False):
"""parses a template or user edited string to fills this envelope.
:param tmp: the string to parse.
:type tmp: str
:param reset: remove previous envelope content
:type reset: bool
"""
logging.debug('GoT: """\n%s\n"""', tmp)
if self.sent_time:
self.modified_since_sent = True
if only_body:
self.body = tmp
else:
m = re.match(r'(?P<h>([a-zA-Z0-9_-]+:.+\n)*)\n?(?P<b>(\s*.*)*)',
tmp)
assert m
d = m.groupdict()
headertext = d['h']
self.body = d['b']
# remove existing content
if reset:
self.headers = {}
# go through multiline, utf-8 encoded headers
# we decode the edited text ourselves here as
# email.message_from_file can't deal with raw utf8 header values
key = value = None
for line in headertext.splitlines():
if re.match('[a-zA-Z0-9_-]+:', line): # new k/v pair
if key and value: # save old one from stack
self.add(key, value) # save
key, value = line.strip().split(':', 1) # parse new pair
# strip spaces, otherwise we end up having " foo" as value
# of "Subject: foo"
value = value.strip()
elif key and value: # append new line without key prefix
value += line
if key and value: # save last one if present
self.add(key, value)
# interpret 'Attach' pseudo header
if 'Attach' in self:
to_attach = []
for line in self.get_all('Attach'):
gpath = os.path.expanduser(line.s |
# Copyright 2017 QuantRocket - 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.
import os
import getpass
from quantrocket.houston import houston
from quantrocket.cli.utils.output import json_to_cli
def get_credentials(gateway):
"""
Returns username and trading mode (paper/live) for IB Gateway.
Parameters
----------
gateway : str, required
name of IB Gateway service to get credentials for (for example, 'ibg1')
Returns
-------
dict
credentials
"""
statuses = list_gateway_statuses(gateways=[gateway])
if not statuses:
raise ValueError("no such IB Gateway: {0}".format(gateway))
response = houston.get("/{0}/credentials".format(gateway))
houston.raise_for_status_with_json(response)
# It's possible to get a 204 empty response
if not response.content:
return {}
return response.json()
def set_credentials(gateway, username=None, password=None, trading_mode=None):
"""
Set username/password and trading mode (paper/live) for IB Gateway.
Can be used to set new credentials or switch between paper and live trading
(must have previously entered live credentials). Setting new credentials will
restart IB Gateway and takes a moment to complete.
Credentials are encrypted at rest and never leave your deployment.
Parameters
----------
gateway : str, required
name of IB Gateway service to set credentials for (for example, 'ibg1')
username : str, optional
IBKR username (optional if only modifying trading environment)
password : str, optional
IBKR password (if omitted and username is provided, will be prompted
for password)
trading_mode : str, optional
the trading mode to use ('paper' or 'live')
Returns
-------
dict
status message
"""
statuses = list_gateway_statuses(gateways=[gateway])
if not statuses:
raise ValueError("no such IB Gateway: {0}".format(gateway))
if username and not password:
password = getpass.getpass(prompt="Enter IBKR Password: ")
data = {}
if username:
data["username"] = username
if password:
data["password"] = password
if trading_mode:
data["trading_mode"] = trading_mode
response = houston.put("/{0}/credentials".format(gateway), data=data, timeout=180)
houston.raise_for_status_with_json(response)
return response.json()
def _cli_get_or_set_credentials(*args, **kwargs):
if kwargs.get("username", None) or kwargs.get("password", None) or kwargs.get("trading_mode", None):
return json_to_cli(set_credentials, *args, **kwargs)
else:
return json_to_cli(get_credentials, gateway=kwargs.get("gateway", None))
def list_gateway_statuses(status=None, gateways=None):
"""
Query statuses of IB Gateways.
Parameters
----------
status : str, optional
limit to IB Gateways in this status. Possible choices: running, stopped, error
gateways : list of str, optional
limit to these IB Gateways
Returns
-------
dict of gateway:status (if status arg not provided), or list of gateways (if status arg provided)
"""
params = {}
if gateways:
params["gateways"] = gateways
if status:
params["status"] = status
response = houston.get("/ibgrouter/gateways", params=params)
houston.raise_for_status_with_json(response)
return response.json()
def _cli_list_gateway_statuses(*args, **kwargs):
return json_to_cli(list_gateway_statuses, *args, **kwargs)
def start_gateways(gateways=None, wait=False):
"""
Start one or more IB Gateways.
Parameters
----------
gateways : list of str, optional
limit to these IB Gateways
wait: bool
wait for the IB Gateway to start before returning (default is to start
the gateways asynchronously)
Returns
-------
dict
status message
"""
params = {"wait": wait}
if gateways:
params["gateways"] = gateways
response = houston.post("/ibgrouter/gateways", params=params, timeout=120)
houston.raise_for_status_with_json(response)
return response.json()
def _cli_start_gateways(*args, **kwargs):
return json_to_cli(start_gateways, *args, **kwargs)
def stop_gateways(gateways=None, wait=False):
"""
Stop one or more IB Gateways.
Parameters
----------
gateways : list of str, optional
limit to these IB Gateways
wait: bool
wait for the IB Gateway to stop before returning (default is to stop
the gateways asynchronously)
Returns
-------
dict
status message
"""
params = {"wait": wait}
if gateways:
params["gateways"] = gateways
response = houston.delete("/ibgrouter/gateways", params=params, timeout=60)
houston.raise_for_status_with_json(response)
return response.json()
def _cli_stop_gateways(*args, **kwargs):
return json_to_cli(stop_gateways, *args, **kwargs)
def load_ibg_config(filename):
"""
Upload a new IB Gateway permissions config.
Permission configs are only necessary when running multiple IB Gateways with
differing market data permissions.
Parameters
----------
filename : str, required
the config file to upload
Returns
-------
dict
status message
"""
with open(filename) as file:
response = houston.put("/ibgrouter/config", data=file.read())
houston.raise_for_status_with_json(response)
return response.json()
def get_ibg_config():
"""
Returns the current IB Gateway permissions config.
Returns
-------
dict
the confi | g as a dict
"""
response = houston.get("/ibgrouter/config")
houston.raise_for_status_with_json(response)
# It's possible to get a 204 empty response
if not response.content:
return {}
return response.json()
def _cli_loa | d_or_show_config(filename=None):
if filename:
return json_to_cli(load_ibg_config, filename)
else:
return json_to_cli(get_ibg_config)
|
# coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.github.io
#
# 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 print_function, unicode_literals
from sickbeard import helpers, logger
meta_session = helpers.make_session()
def getShowImage(url, imgNum=None):
if url is None:
return None
# if they provided a fanart number try to use it instead
if imgNum is | not None:
tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg"
else:
tempURL = url
logger.log("Fetching image from " + tempURL, logger.DEBUG)
image_data = helpers.getURL(tempURL, session=meta_session, ret | urns='content')
if image_data is None:
logger.log("There was an error trying to retrieve the image, aborting", logger.WARNING)
return
return image_data
|
# 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)
class PyAzureMgmtDeploymentmanager(PythonPackage):
"""Microsoft Azure Deployment Manager Client Library for Python."""
homepage = "https://github.com/Azure/azure-sdk-for-python"
py | pi = "azure-mgmt-deploymentmanager/azure-mgmt-deploymentmanager-0.2.0.zip"
version('0.2.0', sha256='46e342227993fc9acab1dda42f2eb566b522a8c945ab9d0eea56276b46f6d730')
depends_on('py-setuptools', type='build')
depends_on('py-msrest@0.5.0:', type=('build', 'run'))
depends_on('py-msrestazure@0.4.32:1', type=('build', 'run'))
depends_on('py-azure-common@1.1:1 | ', type=('build', 'run'))
depends_on('py-azure-mgmt-nspkg', when='^python@:2', type=('build', 'run'))
|
for item in string.split(','):
key = item.split(':')[0]
var_offset = weechat.hdata_get_var_offset(ptr_hdata, key)
var_array_size = \
weechat.hdata_get_var_array_size_string(ptr_hdata, '',
key)
if var_array_size:
var_array_size = \
', array_size: "{0}"'.format(var_array_size)
var_hdata = weechat.hdata_get_var_hdata(ptr_hdata, key)
if var_hdata:
var_hdata = ', hdata: "{0}"'.format(var_hdata)
type_string = weechat.hdata_get_var_type_string(ptr_hdata,
key)
hdata2.append({
'offset': var_offset,
'text': '\'{0}\' ({1})'.format(key, type_string),
'textlong': '\'{0}\' ({1}{2}{3})'.format(
key, type_string, var_array_size, var_hdata),
'update': weechat.hdata_update(
ptr_hdata, '', {'__update_allowed': key}),
})
hdata2 = sorted(hdata2, key=itemgetter('offset'))
for item in hdata2:
variables += '*** {0}\n'.format(item['textlong'])
if item['update']:
variables_update += '*** {0}\n'.format(item['text'])
if weechat.hdata_update(ptr_hdata, '',
{'__create_allowed': ''}):
variables_update += '*** \'__create\'\n'
if weechat.hdata_update(ptr_hdata, '',
{'__delete_allowed': ''}):
variables_update += '*** \'__delete\'\n'
hdata[plugin][hdata_name]['vars'] = variables
hdata[plugin][hdata_name]['vars_update'] = variables_update
string = weechat.hdata_get_string(ptr_hdata, 'list_keys')
if string:
for item in sorted(string.split(',')):
lists += '*** \'{0}\'\n'.format(item)
hdata[plugin][hdata_name]['lists'] = lists
weechat.infolist_free(infolist)
return hdata
def get_completions():
"""
Get list of WeeChat/plugins completions as dictionary with 3 indexes:
plugin, item, xxx.
"""
completions = defaultdict(lambda: defaultdict(defaultdict))
infolist = weechat.infolist_get('hook', '', 'completion')
while weechat.infolist_next(infolist):
completion_item = weechat.infolist_string(infolist, 'completion_item')
if not re.search('|'.join(IGNORE_COMPLETIONS_ITEMS), completion_item):
plugin = weechat.infolist_string(infolist, 'plugin_name') or \
'weechat'
completions[plugin][completion_item]['description'] = \
weechat.infolist_string(infolist, 'description')
weechat.infolist_free(infolist)
return completions
def get_url_options():
"""
Get list of URL options as list of dictionaries.
"""
url_options = []
inf | olist = | weechat.infolist_get('url_options', '', '')
while weechat.infolist_next(infolist):
url_options.append({
'name': weechat.infolist_string(infolist, 'name').lower(),
'option': weechat.infolist_integer(infolist, 'option'),
'type': weechat.infolist_string(infolist, 'type'),
'constants': weechat.infolist_string(
infolist, 'constants').lower().replace(',', ', ')
})
weechat.infolist_free(infolist)
return url_options
def get_irc_colors():
"""
Get list of IRC colors as list of dictionaries.
"""
irc_colors = []
infolist = weechat.infolist_get('irc_color_weechat', '', '')
while weechat.infolist_next(infolist):
irc_colors.append({
'color_irc': weechat.infolist_string(infolist, 'color_irc'),
'color_weechat': weechat.infolist_string(infolist,
'color_weechat'),
})
weechat.infolist_free(infolist)
return irc_colors
def get_plugins_priority():
"""
Get priority of default WeeChat plugins as a dictionary.
"""
plugins_priority = {}
infolist = weechat.infolist_get('plugin', '', '')
while weechat.infolist_next(infolist):
name = weechat.infolist_string(infolist, 'name')
priority = weechat.infolist_integer(infolist, 'priority')
if priority in plugins_priority:
plugins_priority[priority].append(name)
else:
plugins_priority[priority] = [name]
weechat.infolist_free(infolist)
return plugins_priority
# pylint: disable=too-many-locals, too-many-branches, too-many-statements
# pylint: disable=too-many-nested-blocks
def docgen_cmd_cb(data, buf, args):
"""Callback for /docgen command."""
if args:
locales = args.split(' ')
else:
locales = LOCALE_LIST
commands = get_commands()
options = get_options()
infos = get_infos()
infos_hashtable = get_infos_hashtable()
infolists = get_infolists()
hdata = get_hdata()
completions = get_completions()
url_options = get_url_options()
irc_colors = get_irc_colors()
plugins_priority = get_plugins_priority()
# get path and replace ~ by home if needed
path = weechat.config_get_plugin('path')
if path.startswith('~'):
path = os.environ['HOME'] + path[1:]
# write to doc files, by locale
num_files = defaultdict(int)
num_files_updated = defaultdict(int)
# pylint: disable=undefined-variable
translate = lambda s: (s and _(s)) or s
escape = lambda s: s.replace('|', '\\|')
for locale in locales:
for key in num_files:
if key != 'total2':
num_files[key] = 0
num_files_updated[key] = 0
trans = gettext.translation('weechat',
weechat.info_get('weechat_localedir', ''),
languages=[locale + '.UTF-8'],
fallback=True)
trans.install()
directory = path + '/' + locale[0:2] + '/autogen'
if not os.path.isdir(directory):
weechat.prnt('',
'{0}docgen error: directory "{1}" does not exist'
''.format(weechat.prefix('error'), directory))
continue
# write commands
for plugin in commands:
doc = AutogenDoc(directory, 'user', plugin + '_commands')
for i, command in enumerate(sorted(commands[plugin])):
if i > 0:
doc.write('\n')
_cmd = commands[plugin][command]
args = translate(_cmd['args'])
args_formats = args.split(' || ')
desc = translate(_cmd['description'])
args_desc = translate(_cmd['args_description'])
doc.write('[[command_{0}_{1}]]\n'.format(plugin, command))
doc.write('[command]*`{0}`* {1}::\n\n'.format(command, desc))
doc.write('----\n')
prefix = '/' + command + ' '
if args_formats != ['']:
for fmt in args_formats:
doc.write(prefix + fmt + '\n')
prefix = ' ' * len(prefix)
if args_desc:
doc.write('\n')
for line in args_desc.split('\n'):
doc.write(line + '\n')
doc.write('----\n')
doc.update('commands', num_files, num_files_updated)
# write config options
for config in options:
doc = AutogenDoc(directory, 'user', config + '_options')
i = 0
for section in sorted(options[config]):
for option in sorted(options[config][section]):
if i > 0:
doc.write('\n' |
from django | .contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from flop.cooking.forms import MealForm, MealContributionFormSet
from flop.decorators import view_decorator
@view_decorator(login_required)
class IndexV | iew(TemplateView):
template_name = 'dashboard/index.html'
|
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE file for details.
"""
import os
import shutil
import grp
import pwd
from cct.module import Module
from cct.lib.file_utils import create_dir
class File(Module):
def copy(self, source, destination):
"""
Copies file.
Args:
source: path to file
destination: path where file should be copied
"""
create_dir(destination)
shutil.copy(source, destination)
def link(self, source, destination):
"""
Creates symbolik link.
Args:
source: path to symbolik link destination
destination: Symbolik link name
"""
create_dir(destination)
os.symlink(source, destination)
def move(self, source, destination):
"""
Moves file.
Args:
source: path to file
destination: path where file should be moved
"""
create_dir(destination)
shutil.move(source, destination)
def remove(self, path):
"""
Removes file.
Args:
source: path to file to be removed
"""
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.unlink(path)
def chown(self, owner, group, path, recursive=False):
"""
Change the ownership of a path.
Args:
owner: the owner (numeric or name) to change ownership to
group: the group (numeric or name) to change groupship to
| path: the path to operate on
recursive: if path is a directory, recursively change ownership for all
paths within
"""
# supplied owner/group might be symbolic (e.g. 'wheel') or numeric.
# Try interpreting symbolically first
try:
gid = grp.getgrnam(group).gr_gid
except KeyError:
gid = int( | group,0)
try:
uid = pwd.getpwnam(owner).pw_uid
except KeyError:
uid = int(owner,0)
# Beware: argument order is different
os.chown(path, uid, gid)
if recursive and os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for f in (dirnames + filenames):
os.chown(os.path.join(dirpath, f), uid, gid)
def chmod(self, mode, path, recursive=False):
"""
Change the permissions of a path.
Args:
path: the path to operate on
mode: the numeric mode to set
recursive: whether to change mode recursively
"""
mode = int(mode,0)
# Beware: argument order swapped
os.chmod(path, mode)
if recursive and os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for f in (dirnames + filenames):
os.chmod(os.path.join(dirpath, f), mode)
|
ref, remote_ip, payload)
else:
return (None, None, None)
def get_url(self):
href, remote_ip, payload = self._get_href()
return href and "%s&key=%s" % (href, gom_stream_key(remote_ip, payload))
def get_proxy_url(self):
href, remote_ip, payload = self._get_href()
return href and proxy.url(href, payload)
class GOMtv(object):
VODLIST_ORDER_MOST_RECENT = 1
VODLIST_ORDER_MOST_VIEWED = 2
VODLIST_ORDER_MOST_COMMENTED = 3
VODLIST_TYPE_ALL = 0
VODLIST_TYPE_CODE_S = 32
VODLIST_TYPE_CODE_A = 16
VODLIST_TYPE_UP_DOWN = 64
AUTH_GOMTV = 1
AUTH_TWITTER = 2
AUTH_FACEBOOK = 3
LEVEL = {
'EHQ': 65,
'HQ': 60,
'SQ': 6
}
OLDLEVEL = {
'EHQ': 50,
'HQ': 50,
'SQ': 5
}
def __init__(self, cookie_path=None):
self.vod_sets = {}
if cookie_path is None:
cookie_path = "%s%scookies_gomtv.txt" % (tempfile.gettempdir(), os.path.sep)
self.cookie_jar = cookielib.LWPCookieJar(cookie_path)
if not os.path.exists(os.path.dirname(cookie_path)):
os.makedirs(os.path.dirname(cookie_path))
if (os.path.isfile(cookie_path) and os.path.getsize(cookie_path) > 0):
self.cookie_jar.load(cookie_path,True)
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar))
def _request(self, url, data=None, headers={}):
r = request(url, data, headers, opener=self.opener)
# Ugly hack required to fix cookie names.
# Guessing there's some javascript somewhere on that mess of a website
# that uppercases the cookies..?
for cookie in self.cookie_jar:
if cookie.name.startswith("SES_"):
cookie.name = cookie.name.upper()
self.cookie_jar.save(None,True)
return r
def set_cookie(self, name, value):
exp = time.time() + 24 * 60 * 60
cookie = cookielib.Cookie(version=0, name=name, value=value, port=None, port_specified=False,
domain='.gomtv.net', domain_specified=True, domain_initial_dot=True,
path='/', path_specified=True, secure=False, expires=exp,
discard=False, comment=None, comment_url=None, rest={})
self.cookie_jar.set_cookie(cookie)
def login(self, username, password, auth_type=AUTH_GOMTV):
self.cookie_jar.clear()
if auth_type == self.AUTH_GOMTV:
form = {
"mb_username": username,
"mb_password": password,
"cmd": "login",
"rememberme": "1"
}
ret = self._request("https://ssl.gomtv.net/userinfo/loginProcess.gom", form, {'Referer': 'http://www.gomtv.net/'})
cookies = [cookie.name for cookie in self.cookie_jar if cookie.domain == '.gomtv.net']
return 'SES_MEMBERNO' in cookies
elif auth_type == self.AUTH_TWITTER:
data = self._request("http://www.gomtv.net/twitter/redirect.gom?burl=/index.gom")
location = re.search("document.location.replace\(\"(.*)\"\)", data).group(1)
oauth_token = re.search("setCookie\('oauth_token', \"(.*)\"", data).group(1)
oauth_token_secret = re.search("setCookie\('oauth_token_secret', \"(.*)\"", data).group(1)
self.set_cookie("oauth_token", oauth_token)
self.set_cookie("oauth_token_secret", oauth_token_secret)
data = self._request(location)
soup = BeautifulSoup(data)
oauth_token = soup.find("input", {"id": "oauth_token"})["value"]
auth_token = soup.find("input", {"name": "authenticity_token"})["value"]
url = soup.find("form")["action"]
data = self._request(url, {"oauth_token": oauth_token,
"session[username_or_email]": username,
"session[password]": password,
"submit": "Sign in",
"authenticity_token": auth_token})
refresh = re.search('<meta http-equiv="refresh" content="0;url=(.*)">', data)
if refresh is None:
return False
else:
location = refresh.group(1)
data = self._request(location)
return True
elif auth_type == self.AUTH_FACEBOOK:
data = self._request("http://www.gomtv.net/facebook/index.gom?burl=/index.gom")
soup = BeautifulSoup(data)
# already logged in
if data.startswith("<script>"):
return False
url = soup.find("form")["action"]
payload = {}
for field in soup.findAll("input"):
if not field["name"] == "charset_test":
payload[field["name"]] = field["value"]
payload["email"] = username
payload["pass"] = password
data = self._request(url, payload)
if re.search("<title>Logga in", data) is None:
return True
else:
return False
def get_league_list(self):
soup = BeautifulSoup(self._request("http://www.gomtv.net/view/channelDetails.gom?gameid=0"))
leagues = soup.findAll("dl", "league_list")
result = []
for league in leagues:
result.append({"id": league.find("a")["href"].replace("/", ""),
"logo": league.find("img")["src"],
"name": league.find("strong").find(text=True)})
return result
def get_most_recent_list(self, page=1):
return self.get_vod_list(league=None, page=page)
def get_vod_list(self, order=1, page=1, league=None, type=VODLIST_TYPE_ALL):
if league is None:
url = "http://www.gomtv.net/videos/index.gom?page=%d" % (page)
else:
url = "http://www.gomtv.net/%s/vod/?page=%d&order=%d<ype=%d" % (league, page, order, type)
soup = BeautifulSoup(self._request(url))
thumb_links = soup.findAll("td", {"class": ["vod_info", "listOff"]})
nums = soup.findAll("a", "num", href=re.compile("page=[0-9]+"))
if len(nums) > 0:
last = int(re.search("page=([0-9]+)",
num | s[-1]["href"]).group(1))
else:
last = page
vods = []
result = {"order": order,
"page": page,
"vods": vods,
"has_previous": page is not 1,
"has_next": page is not last}
if page > last or page < 1:
return result
| for thumb_link in thumb_links:
href = thumb_link.find("a", {'class': ["vod_link", "vodlink"]})["href"].replace("/./", "/")
thumb = thumb_link.find("img", {'class': ["v_thumb", "vodthumb"]})
vods.append({"url": "http://www.gomtv.net%s" % href, "preview": thumb["src"], "title": thumb["alt"]})
return result
def _get_set_params(self, body):
flashvars = re.search('flashvars\s+=\s+([^;]+);', body).group(1)
return json.loads(flashvars)
def extract_jsonData(self, body):
jsondata = re.search('var\s+jsonData\s+=\s+eval\s+\(([^)]*)\)', body).group(1)
return json.loads(jsondata)
def get_vod_set(self, vod_url, quality="EHQ"):
self.set_cookie('SES_VODLEVEL', str(self.LEVEL[quality]))
self.set_cookie('SES_VODOLDLEVEL', str(self.OLDLEVEL[quality]))
r = self._request(vod_url)
flashvars = self._get_set_params(r)
if flashvars['uno'] == '0':
raise NotLoggedInException
# 0 english, 1 korean
jsondata = self.extract_jsonData(r)[0]
soup = BeautifulSoup(r)
vodlist = soup.find('ul', id='vodList')
sets = vodlist.findAll("a")
for (i, s) in enumerate(sets):
params = dict(flashvars, **jsondata[i])
yield {"params": params,
|
. | ./../../../share/pyshared/jockey/xorg_driver. | py |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a co | py of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#--------------------- | ----------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .. import Rule
from ....lib.familyreltype import FamilyRelType
#-------------------------------------------------------------------------
#
# HasRelationship
#
#-------------------------------------------------------------------------
class HasRelationship(Rule):
"""Rule that checks for a person who has a particular relationship"""
labels = [ _('Number of relationships:'),
_('Relationship type:'),
_('Number of children:') ]
name = _('People with the <relationships>')
description = _("Matches people with a particular relationship")
category = _('Family filters')
def apply(self,db,person):
rel_type = 0
cnt = 0
num_rel = len(person.get_family_handle_list())
if self.list[1]:
specified_type = FamilyRelType()
specified_type.set_from_xml_str(self.list[1])
# count children and look for a relationship type match
for f_id in person.get_family_handle_list():
f = db.get_family_from_handle(f_id)
if f:
cnt = cnt + len(f.get_child_ref_list())
if self.list[1] and specified_type == f.get_relationship():
rel_type = 1
# if number of relations specified
if self.list[0]:
try:
v = int(self.list[0])
except:
return False
if v != num_rel:
return False
# number of childred
if self.list[2]:
try:
v = int(self.list[2])
except:
return False
if v != cnt:
return False
# relation
if self.list[1]:
return rel_type == 1
else:
return True
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys, re, json, requests
from oxapi import *
def get_a_task(ox):
folder = ox.get_standard_folder('tasks')
task = list(ox.get_tasks(folder.id))[0]
return task
def upload(bean, args=[{'content':None,'file':None, 'mimetype':'text/plain','name':'attachment.txt'}]):
from requests.packages.urllib3.fields import RequestField
from requests.packages.urllib3.filepost import encode_multipart_formdata
ox = bean._ox
url = ox._url('attachmen | t', 'attach')
params = ox._params()
meta = {'module': bean.module_type,
#'attached': bean.id,
'folder': bean.folder_id}
counter = 0; fields = []
for data in args:
# json metadata
rf = RequestField(name='json_' + str(counter) ,data=json. | dumps(meta))
rf.make_multipart(content_disposition='form-data')
fields.append(rf)
# content: data or file to read
filename = 'attachment.txt'
mimetype = 'text/plain'
content = None
if 'content' in data:
content = data['content']
else:
if 'file' in data:
filename = data['file']
if os.path.isfile(filename):
with open(filename, 'rb') as fh:
content = fh.read()
if content is None:
#TODO: process error
return None
if 'name' in data:
filename = data['name']
mimetype = 'text/plain'
if 'mimetype' in data:
mimetype = data['mimetype']
rf = RequestField(name='file_' + str(counter), data=content, filename=filename)
rf.make_multipart(content_disposition='form-data',content_type=mimetype)
fields.append(rf)
post_body, content_type = encode_multipart_formdata(fields)
content_type = ''.join(('multipart/mixed',) + content_type.partition(';')[1:])
headers = {'Content-Type': content_type}
response = requests.post(url, cookies=ox._cookies, params=params, headers=headers, data=post_body)
if response and response.status_code == 200:
regex='\((\{.*\})\)'
match = re.search(regex, response.content)
if match:
return json.loads(match.group(1))
return None
def create_attachment(ox, task):
from requests.packages.urllib3.fields import RequestField
from requests.packages.urllib3.filepost import encode_multipart_formdata
url = ox._url('attachment', 'attach')
params = ox._params()
json_0 = {'module': task.module_type,
'attached': task.id,
'folder': task.folder_id}
fields = []
rf = RequestField(name='json_0',data=json.dumps(json_0))
rf.make_multipart(content_disposition='form-data')
fields.append(rf)
rf = RequestField(name='file_0', data="TEXT", filename='attachment.txt')
rf.make_multipart(content_disposition='form-data',content_type='text/plain')
fields.append(rf)
post_body, content_type = encode_multipart_formdata(fields)
content_type = ''.join(('multipart/mixed',) + content_type.partition(';')[1:])
headers = {'Content-Type': content_type}
response = requests.post(url, cookies=ox._cookies, params=params, headers=headers, data=post_body)
if response and response.status_code == 200:
regex='\((\{.*\})\)'
match = re.search(regex, response.content)
if match:
return json.loads(match.group(1))
return None
if __name__ == '__main__':
with OxHttpAPI.get_session() as ox:
task = get_a_task(ox)
# args = [{ 'file':'attachments_module.py' }]
# upload(task, args)
#create_attachment(ox,task)
#attachments = list(ox.get_attachments(task))
attachments = ox.get_attachments(task)
pass
|
he unique versions for an objext can be retrieved."""
with reversion.revision:
self.test.save()
versions = Version.objects.get_unique_for_object(self.test)
# Check correct version data.
self.assertEqual(versions[0].field_dict["name"], "test1.0")
self.assertEqual(versions[1].field_dict["name"], "test1.1")
self.assertEqual(versions[2].field_dict["name"], "test1.2")
# Check correct number of versions.
self.assertEqual(len(versions), 3)
def testCanGetForDate(self):
"""Tests that the latest version for a particular date can be loaded."""
with self.settings(USE_TZ=True):
self.assertEqual(Version.objects.get_for_date(self.test, datetime.datetime.now(UTC())).field_dict["name"], "test1.2")
def testCanRevert(self):
"""Tests that an object can be reverted to a previous revision."""
oldest = Version.objects.get_for_object(self.test)[0]
self.assertEqual(oldest.field_dict["name"], "test1.0")
oldest.revert()
self.assertEqual(self.model.objects.get().name, "test1.0")
def testCanGetDeleted(self):
"""Tests that deleted objects can be retrieved."""
self.assertEqual(len(Version.objects.get_deleted(self.model)), 0)
# Create and delete another model.
with reversion.revision:
test2 = self.model.objects.create(name="test2.0")
test2.delete()
# Delete the test model.
self.test.delete()
# Ensure that there are now two deleted models.
deleted = Version.objects.get_deleted(self.model)
self.assertEqual(len(deleted), 2)
self.assertEqual(deleted[0].field_dict["name"], "test1.2")
self.assertEqual(deleted[1].field_dict["name"], "test2.0")
self.assertEqual(len(deleted), 2)
def testCanRecoverDeleted(self):
"""Tests that a deleted object can be recovered."""
self.test.delete()
# Ensure deleted.
self.assertEqual(self.model.objects.count(), 0)
# Recover.
Version.objects.get_deleted(self.model)[0].revert()
# Ensure recovered.
self.assertEqual(self.model.objects.get().name, "test1.2")
def testCanGenerateStatistics(self):
"""Tests that the stats are accurate for Version models."""
self.assertEqual(Version.objects.filter(type=VERSION_ADD).count(), 1)
self.assertEqual(Version.objects.filter(type=VERSION_CHANGE).count(), 2)
self.assertEqual(Version.objects.filter(type=VERSION_DELETE).count(), 0)
with reversion.revision:
self.test.delete()
self.assertEqual(Version.objects.filter(type=VERSION_DELETE).count(), 1)
def tearDown(self):
"""Tears down the tests."""
# Unregister the model.
reversion.unregister(self.model)
# Clear the database.
Revision.objects.all().delete()
self.model.objects.all().delete()
# Clear references.
del self.test
class ReversionQueryStrPrimaryTest(ReversionQueryTest):
model = ReversionTestModelStrPrimary
class ReversionCustomRegistrationTest(TestCase):
"""Tests the custom model registration options."""
def setUp(self):
"""Sets up the ReversionTestModel."""
# Clear the database.
Revision.objects.all().delete()
ReversionTestModel.objects.all().delete()
# Register the model.
reversion.register(ReversionTestModel, fields=("id",), format="xml")
# Create some initial revisions.
with reversion.revision:
self.test = ReversionTestModel.objects.create(n | ame="test1.0")
with reversion.revision:
self.test.name = "test1.1"
self.test | .save()
with reversion.revision:
self.test.name = "test1.2"
self.test.save()
def testCustomRegistrationHonored(self):
"""Ensures that the custom settings were honored."""
self.assertEqual(tuple(reversion.revision.get_adapter(ReversionTestModel).get_fields_to_serialize()), ("id",))
self.assertEqual(reversion.revision.get_adapter(ReversionTestModel).get_serialization_format(), "xml")
def testCanRevertOnlySpecifiedFields(self):
""""Ensures that only the restricted set of fields are loaded."""
Version.objects.get_for_object(self.test)[0].revert()
self.assertEqual(ReversionTestModel.objects.get().name, "")
def testCustomSerializationFormat(self):
"""Ensures that the custom serialization format is used."""
self.assertEquals(Version.objects.get_for_object(self.test)[0].serialized_data[0], "<");
def testIgnoreDuplicates(self):
"""Ensures that duplicate revisions can be ignores."""
self.assertEqual(len(Version.objects.get_for_object(self.test)), 3)
with reversion.revision:
self.test.save()
self.assertEqual(len(Version.objects.get_for_object(self.test)), 4)
with reversion.revision:
reversion.revision.ignore_duplicates = True
self.assertTrue(reversion.revision.ignore_duplicates)
self.test.save()
self.assertEqual(len(Version.objects.get_for_object(self.test)), 4)
def tearDown(self):
"""Tears down the tests."""
# Unregister the model.
reversion.unregister(ReversionTestModel)
# Clear the database.
Revision.objects.all().delete()
ReversionTestModel.objects.all().delete()
# Clear references.
del self.test
class TestRelatedModel(models.Model):
"""A model used to test Reversion relation following."""
name = models.CharField(max_length=100)
relation = models.ForeignKey(ReversionTestModel)
class Meta:
app_label = "auth" # Hack: Cannot use an app_label that is under South control, due to http://south.aeracode.org/ticket/520
class ReversionRelatedTest(TestCase):
"""Tests the ForeignKey and OneToMany support."""
def setUp(self):
"""Sets up the ReversionTestModel."""
# Clear the database.
Revision.objects.all().delete()
ReversionTestModel.objects.all().delete()
TestRelatedModel.objects.all().delete()
# Register the models.
reversion.register(ReversionTestModel, follow=("testrelatedmodel_set",))
reversion.register(TestRelatedModel, follow=("relation",))
def testCanCreateRevisionForiegnKey(self):
"""Tests that a revision containing both models is created."""
with reversion.revision:
test = ReversionTestModel.objects.create(name="test1.0")
related = TestRelatedModel.objects.create(name="related1.0", relation=test)
self.assertEqual(Version.objects.get_for_object(test).count(), 1)
self.assertEqual(Version.objects.get_for_object(related).count(), 1)
self.assertEqual(Revision.objects.count(), 1)
self.assertEqual(Version.objects.get_for_object(test)[0].revision.version_set.all().count(), 2)
def testCanCreateRevisionOneToMany(self):
"""Tests that a revision containing both models is created."""
with reversion.revision:
test = ReversionTestModel.objects.create(name="test1.0")
related = TestRelatedModel.objects.create(name="related1.0", relation=test)
with reversion.revision:
test.save()
self.assertEqual(Version.objects.get_for_object(test).count(), 2)
self.assertEqual(Version.objects.get_for_object(related).count(), 2)
self.assertEqual(Revision.objects.count(), 2)
self.assertEqual(Version.objects.get_for_object(test)[1].revision.version_set.all().count(), 2)
def testCanRevertRevision(self):
"""Tests that an entire revision can be reverted."""
with reversion.revision:
test = ReversionTestModel.objects.create(name="test1.0")
related = TestRelatedModel.objects.create(name="related1.0", relation=test)
|
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2011 Vauxoo - http://www.vauxoo.com/
# All Rights Reserved.
# info Vauxoo (info@vauxoo.com)
############################################################################
# Coded by: Juan Carlos Hernandez Funes (info@vaux | oo.com)
# Planned by: Moises Augusto Lopez Calderon (info@vauxoo.com)
############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but | WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import osv, fields
class account_analytic_account(osv.Model):
_inherit = 'account.analytic.account'
_order = "parent_left"
_parent_order = "code"
_parent_store = True
_columns = {
'parent_right': fields.integer('Parent Right', select=1),
'parent_left': fields.integer('Parent Left', select=1),
}
|
"""
FEniCS tutorial demo program: Poisson equation with Dirichlet,
Neumann and Robin conditions.
The solution is checked to coincide with the exact solution at all nodes.
The file is a modification of dn2_p2D.py. Note that the boundary is now also
split into two distinct parts (separate objects and integrations)
and we have a Robin condition instead of a Neumann condition at y=0.
"""
from dolfin import *
import numpy
#-------------- Preprocessing step -----------------
# Create mesh and define function space
mesh = UnitSquareMesh(3, 2)
V = FunctionSpace(mesh, 'Lagrange', 1)
# Define boundary segments for Neumann, Robin and Dirichlet conditions
# Create mesh function over cell facets
boundary_parts = MeshFunction("size_t", mesh, mesh.topology().dim()-1)
# Mark lower boundary facets as subdomain 0
class LowerRobinBoundary(SubDomain):
def inside(self, x, on_boundary):
tol = 1E-14 # tolerance for coordinate comparisons
return on_boundary and abs(x[1]) < tol
Gamma_R = LowerRobinBoundary()
Gamma_R.mark(boundary_parts, 0)
q = Expression('1 + x[0]*x[0] + 2*x[1]*x[1]')
p = Constant(100) # arbitrary function can go here
# Mark upper boundary facets as subdomain 1
class UpperNeumannBoundary(SubDomain):
def inside(self, x, on_boundary):
tol = 1E-14 # tolerance for coordinate comparisons
return on_boundary and abs(x[1] - 1) < tol
Gamma_N = UpperNeumannBoundary()
Gamma_N.mark(boundary_parts, 1)
g = Expression('-4*x[1]')
# Mark left boundary as subdomain 2
class LeftBoundary(SubDomain):
def inside(self, x, on_boundary):
tol = 1E-14 # tolerance for coordinate comparisons
return on_boundary and abs(x[0]) < tol
Gamma_0 = LeftBoundary()
Gamma_0.mark(boundary_parts, 2)
# Mark right boundary as subdomain 3
class RightBoundary(SubDomain):
def inside(self, x, on_boundary):
tol = 1E-14 # tolerance for coordinate comparisons
return on_boundary and abs(x[0] - 1) < tol
Gamma_1 = RightBoundary()
Gamma_1.mark(boundary_parts, 3)
#-------------- Solution and problem definition step -----------------
# given mesh and boundary_parts
u_L = Expression('1 + 2*x[1]*x[1]')
u_R = Expression('2 + 2*x[1]*x[1]')
bcs = [DirichletBC(V, u_L, boundary_parts, 2),
DirichletBC(V, u_R, boundary_parts, 3)]
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(-6.0)
a = inner(nabla_grad(u), nabla_grad(v))*dx + p*u*v*ds(0)
L = f*v*dx - g*v*ds(1) + p*q*v*ds(0)
# Compute solution
A = assemble(a, exterior_facet_domains=boundary_parts)
b = assemble(L, exterior_facet_domains=boundary_parts)
for condition in bcs: condition.apply(A, b)
# Altern | ative is not yet supported
#A, b = assemble_system(a, L, bc, exterior_facet_domains=boundary_parts)
u = Function(V)
solve(A, u.vector(), b, 'lu')
print mesh
# Verification
u_exact = Expression('1 + x[0]*x[0] + 2*x[1]*x[1]')
u_e = interpolate(u_exact, V)
print 'Max error:', abs(u_e.vector().array() - u.vector().array( | )).max()
#interactive()
|
from . | basic import ProcFile
from collections import namedtuple
class Consoles(ProcFile):
filename = '/proc/consoles'
Console = namedtuple('Console', ['operations', 'flags', 'major', 'minor'])
de | f names(self):
return [line.split()[0] for line in self._readfile()]
def get(self, name, default=None):
for line in self._readfile():
console_info = line.replace('(', '').replace(')', '').split()
if name == console_info[0]:
major, minor = console_info[-1].split(':')
return [console_info[1],
''.join(console_info[2:-1]), major, minor
]
else:
return default
def __getattr__(self, name):
if name in self.names():
return self.Console(*tuple(self.get(name)))
else:
raise AttributeError
if __name__ == '__main__':
CONSOLES = Consoles()
print(CONSOLES.names())
print(CONSOLES.get('tty0'))
print(CONSOLES.tty0.operations)
print(CONSOLES.tty0.flags)
print(CONSOLES.tty0.major)
print(CONSOLES.tty0.minor)
|
'''@file cross_enthropytrainer_rec.py
contains the CrossEnthropyTrainerRec for reconstruction of the audio samples'''
import tensorflow as tf
import trainer
from nabu.neuralnetworks import ops
class CostFeaturesRec(trainer.Trainer):
'''A trainer that minimises the cross-enthropy loss, the output sequences
must be of the same length as the input sequences'''
def compute_loss(self, targets, logits, logit_seq_length,
target_seq_length):
'''
Compute the loss
Creates the operation to compute the cross-entropy loss for every input
frame (if y | ou want to have a different loss function, overwrite this
method)
Args:
targets: a tupple of targets, the first one being a
[batch_size x max_target_length] tensor containing the real
targets, the second one being a [batch_size x max_audioseq_length x dim]
| tensor containing the audio samples or other extra information.
logits: a tuple of [batch_size, max_logit_length, dim] tensors
containing the logits for the text and the audio samples
logit_seq_length: the length of all the logit sequences as a tuple of
[batch_size] vectors
target_seq_length: the length of all the target sequences as a
tupple of two [batch_size] vectors, both for one of the elements
in the targets tupple
Returns:
a scalar value containing the loss
'''
with tf.name_scope('cross_entropy_loss'):
total_loss = ops.mse(targets[1], logits[1], target_seq_length[1])
return total_loss
|
#!/usr/bin/env python
#
# 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. See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.
# query.py: Perform a few varieties of queries
from __future__ import print_function
import time
import bugzilla
# public test instance of bugzilla.redhat.com. It's okay to make changes
URL = "partner-bugzilla.redhat.com"
bzapi = bugzilla.Bugzilla(URL)
# build_query is a helper function that handles some bugzilla version
# incompatibility issues. All it does is return a properly formatted
# dict(), and provide friendly parameter names. The param names map
# to those accepted by XMLRPC Bug.search:
# https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#s | earch-bugs
query = bzapi.build_query(
product="Fedora",
component="python-bugzilla")
# Since 'query' is just a dict, you could set your own parameters too, like
# if your bugzilla had a custom field. This will set 'status' for example,
# but for common opts | it's better to use build_query
query["status"] = "CLOSED"
# query() is what actually performs the query. it's a wrapper around Bug.search
t1 = time.time()
bugs = bzapi.query(query)
t2 = time.time()
print("Found %d bugs with our query" % len(bugs))
print("Query processing time: %s" % (t2 - t1))
# Depending on the size of your query, you can massively speed things up
# by telling bugzilla to only return the fields you care about, since a
# large chunk of the return time is transmitting the extra bug data. You
# tweak this with include_fields:
# https://wiki.mozilla.org/Bugzilla:BzAPI#Field_Control
# Bugzilla will only return those fields listed in include_fields.
query = bzapi.build_query(
product="Fedora",
component="python-bugzilla",
include_fields=["id", "summary"])
t1 = time.time()
bugs = bzapi.query(query)
t2 = time.time()
print("Quicker query processing time: %s" % (t2 - t1))
# bugzilla.redhat.com, and bugzilla >= 5.0 support queries using the same
# format as is used for 'advanced' search URLs via the Web UI. For example,
# I go to partner-bugzilla.redhat.com -> Search -> Advanced Search, select
# Classification=Fedora
# Product=Fedora
# Component=python-bugzilla
# Unselect all bug statuses (so, all status values)
# Under Custom Search
# Creation date -- is less than or equal to -- 2010-01-01
#
# Run that, copy the URL and bring it here, pass it to url_to_query to
# convert it to a dict(), and query as usual
query = bzapi.url_to_query("https://partner-bugzilla.redhat.com/"
"buglist.cgi?classification=Fedora&component=python-bugzilla&"
"f1=creation_ts&o1=lessthaneq&order=Importance&product=Fedora&"
"query_format=advanced&v1=2010-01-01")
query["include_fields"] = ["id", "summary"]
bugs = bzapi.query(query)
print("The URL query returned 22 bugs... "
"I know that without even checking because it shouldn't change!... "
"(count is %d)" % len(bugs))
# One note about querying... you can get subtley different results if
# you are not logged in. Depending on your bugzilla setup it may not matter,
# but if you are dealing with private bugs, check bzapi.logged_in setting
# to ensure your cached credentials are up to date. See update.py for
# an example usage
|
"""Methods to set media related (resolution, length) scene properties"""
import bpy
def setup(animated, width, height, lengt | h):
"""
Sets up the type, resolution and length of the currently open scene
The render resolution of the scene is set, and additionally ...
... for stills, sets the length of the scene to exact | ly 1 frame.
... for animations, enables animated seed for cycles, sets the fps to
24 and the fps_base to 1.
"""
bpy.context.scene.render.resolution_percentage = 100
bpy.context.scene.render.resolution_x = int(width)
bpy.context.scene.render.resolution_y = int(height)
if not animated:
bpy.context.scene.frame_end = 1
else:
bpy.context.scene.cycles.use_animated_seed = True
bpy.context.scene.frame_end = length * 24
bpy.context.scene.render.fps = 24
# different for weird framerates (23.9243924 stuffies you know)
bpy.context.scene.render.fps_base = 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.