text stringlengths 4 1.02M | meta dict |
|---|---|
import json
import logging
import re
from django.utils.translation import ugettext_lazy as _ # noqa
from django.views.decorators.debug import sensitive_variables # noqa
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
LOG = logging.getLogger(__name__)
def exception_to_validation_msg(e):
"""Extracts a validation message to display to the user."""
try:
error = json.loads(str(e))
# NOTE(jianingy): if no message exists, we just return 'None'
# and let the caller to deciede what to show
return error['error'].get('message', None)
except Exception:
# NOTE(jianingy): fallback to legacy message parsing approach
# either if error message isn't a json nor the json isn't in
# valid format.
validation_patterns = [
"Remote error: \w* {'Error': '(.*?)'}",
'Remote error: \w* (.*?) \[',
'400 Bad Request\n\nThe server could not comply with the request '
'since it is either malformed or otherwise incorrect.\n\n (.*)',
'(ParserError: .*)'
]
for pattern in validation_patterns:
match = re.search(pattern, str(e))
if match:
return match.group(1)
class TemplateForm(forms.SelfHandlingForm):
class Meta:
name = _('Select Template')
help_text = _('From here you can select a template to launch '
'a stack.')
template_source = forms.ChoiceField(label=_('Template Source'),
choices=[('url', _('URL')),
('file', _('File')),
('raw', _('Direct Input'))],
widget=forms.Select(attrs={
'class': 'switchable',
'data-slug': 'source'}))
template_upload = forms.FileField(
label=_('Template File'),
help_text=_('A local template to upload.'),
widget=forms.FileInput(attrs={'class': 'switched',
'data-switch-on': 'source',
'data-source-file': _('Template File')}),
required=False)
template_url = forms.URLField(
label=_('Template URL'),
help_text=_('An external (HTTP) URL to load the template from.'),
widget=forms.TextInput(attrs={'class': 'switched',
'data-switch-on': 'source',
'data-source-url': _('Template URL')}),
required=False)
template_data = forms.CharField(
label=_('Template Data'),
help_text=_('The raw contents of the template.'),
widget=forms.widgets.Textarea(attrs={
'class': 'switched',
'data-switch-on': 'source',
'data-source-raw': _('Template Data')}),
required=False)
def __init__(self, *args, **kwargs):
self.next_view = kwargs.pop('next_view')
super(TemplateForm, self).__init__(*args, **kwargs)
def clean(self):
cleaned = super(TemplateForm, self).clean()
template_url = cleaned.get('template_url')
template_data = cleaned.get('template_data')
files = self.request.FILES
has_upload = 'template_upload' in files
# Uploaded file handler
if has_upload and not template_url:
log_template_name = self.request.FILES['template_upload'].name
LOG.info('got upload %s' % log_template_name)
tpl = self.request.FILES['template_upload'].read()
if tpl.startswith('{'):
try:
json.loads(tpl)
except Exception as e:
msg = _('There was a problem parsing the template: %s') % e
raise forms.ValidationError(msg)
cleaned['template_data'] = tpl
# URL handler
elif template_url and (has_upload or template_data):
msg = _('Please specify a template using only one source method.')
raise forms.ValidationError(msg)
# Check for raw template input
elif not template_url and not template_data:
msg = _('You must specify a template via one of the '
'available sources.')
raise forms.ValidationError(msg)
# Validate the template and get back the params.
kwargs = {}
if cleaned['template_data']:
kwargs['template'] = cleaned['template_data']
else:
kwargs['template_url'] = cleaned['template_url']
try:
validated = api.heat.template_validate(self.request, **kwargs)
cleaned['template_validate'] = validated
except Exception as e:
msg = exception_to_validation_msg(e)
if not msg:
msg = _('An unknown problem occurred validating the template.')
LOG.exception(msg)
raise forms.ValidationError(msg)
return cleaned
def handle(self, request, data):
kwargs = {'parameters': data['template_validate'],
'template_data': data['template_data'],
'template_url': data['template_url']}
# NOTE (gabriel): This is a bit of a hack, essentially rewriting this
# request so that we can chain it as an input to the next view...
# but hey, it totally works.
request.method = 'GET'
return self.next_view.as_view()(request, **kwargs)
class StackCreateForm(forms.SelfHandlingForm):
param_prefix = '__param_'
class Meta:
name = _('Create Stack')
template_data = forms.CharField(
widget=forms.widgets.HiddenInput,
required=False)
template_url = forms.CharField(
widget=forms.widgets.HiddenInput,
required=False)
parameters = forms.CharField(
widget=forms.widgets.HiddenInput,
required=True)
stack_name = forms.RegexField(
max_length='255',
label=_('Stack Name'),
help_text=_('Name of the stack to create.'),
regex=r"^[a-zA-Z][a-zA-Z0-9_.-]*$",
error_messages={'invalid': _('Name must start with a letter and may '
'only contain letters, numbers, underscores, '
'periods and hyphens.')},
required=True)
timeout_mins = forms.IntegerField(
initial=60,
label=_('Creation Timeout (minutes)'),
help_text=_('Stack creation timeout in minutes.'),
required=True)
enable_rollback = forms.BooleanField(
label=_('Rollback On Failure'),
help_text=_('Enable rollback on create/update failure.'),
required=False)
def __init__(self, *args, **kwargs):
parameters = kwargs.pop('parameters')
super(StackCreateForm, self).__init__(*args, **kwargs)
self._build_parameter_fields(parameters)
def _build_parameter_fields(self, template_validate):
self.fields['password'] = forms.CharField(
label=_('Password for user "%s"') % self.request.user.username,
help_text=_('This is required for operations to be performed '
'throughout the lifecycle of the stack'),
required=True,
widget=forms.PasswordInput())
self.help_text = template_validate['Description']
params = template_validate.get('Parameters', {})
for param_key, param in params.items():
field_key = self.param_prefix + param_key
field_args = {
'initial': param.get('Default', None),
'label': param_key,
'help_text': param.get('Description', ''),
'required': param.get('Default', None) is None
}
param_type = param.get('Type', None)
if 'AllowedValues' in param:
choices = map(lambda x: (x, x), param['AllowedValues'])
field_args['choices'] = choices
field = forms.ChoiceField(**field_args)
elif param_type in ('CommaDelimitedList', 'String'):
if 'MinLength' in param:
field_args['min_length'] = int(param['MinLength'])
field_args['required'] = param.get('MinLength', 0) > 0
if 'MaxLength' in param:
field_args['max_length'] = int(param['MaxLength'])
field = forms.CharField(**field_args)
elif param_type == 'Number':
if 'MinValue' in param:
field_args['min_value'] = int(param['MinValue'])
if 'MaxValue' in param:
field_args['max_value'] = int(param['MaxValue'])
field = forms.IntegerField(**field_args)
self.fields[field_key] = field
@sensitive_variables('password')
def handle(self, request, data):
prefix_length = len(self.param_prefix)
params_list = [(k[prefix_length:], v) for (k, v) in data.iteritems()
if k.startswith(self.param_prefix)]
fields = {
'stack_name': data.get('stack_name'),
'timeout_mins': data.get('timeout_mins'),
'disable_rollback': not(data.get('enable_rollback')),
'parameters': dict(params_list),
'password': data.get('password')
}
if data.get('template_data'):
fields['template'] = data.get('template_data')
else:
fields['template_url'] = data.get('template_url')
try:
api.heat.stack_create(self.request, **fields)
messages.success(request, _("Stack creation started."))
return True
except Exception as e:
msg = exception_to_validation_msg(e)
exceptions.handle(request, msg or _('Stack creation failed.'))
| {
"content_hash": "1c3756056f242bf2441b89cf3e99d0d3",
"timestamp": "",
"source": "github",
"line_count": 255,
"max_line_length": 79,
"avg_line_length": 39.68627450980392,
"alnum_prop": 0.5425889328063241,
"repo_name": "ikargis/horizon_fod",
"id": "23cc7cda77ce9b2fedf1555aa4d59c910094baac",
"size": "10710",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "openstack_dashboard/dashboards/project/stacks/forms.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "167455"
},
{
"name": "JavaScript",
"bytes": "1099746"
},
{
"name": "Python",
"bytes": "3023860"
},
{
"name": "Shell",
"bytes": "13740"
}
],
"symlink_target": ""
} |
""" Skill definition from a YAML config. """
# pylint: disable=too-few-public-methods
class SkillDef:
""" Skill definition from a YAML config. """
# pylint: disable=too-many-arguments
def __init__(self, name, package_name, class_name, url, params, intent_defs, dialogue_events_defs, notification_defs, requires_tts, addons):
""" Initialisation.
:param name: skill name.
:param package_name: the name of the Python module.
:param class_name: the name of the Python class.
:param url: the url package (name or url).
:param params: the parameters to pass to the skills constructor.
:param intent_defs: a list of intent definitions.
:param dialogue_events_defs: a list of notification definitions.
:param notification_defs: a list of notification definitions.
:param requires_tts: whether the skill requires TTS.
:param addons: addon modules.
"""
self.name = name
self.package_name = package_name
self.class_name = class_name
self.url = url
self.params = params
self.intent_defs = intent_defs
self.dialogue_events_defs = dialogue_events_defs
self.notification_defs = notification_defs
self.requires_tts = requires_tts
self.addons = addons
def find(self, intent):
""" Find an intent definition in the list of intents that the skill
declares.
:param intent: the intent object to look for.
:return: an intent definition, from the skill definition, if found,
or None.
"""
if intent is None:
return None
for intent_def in self.intent_defs:
if intent_def.name == intent.intentName:
return intent_def
return None
def find_wildcard(self):
""" Find a wildcard intent definition, i.e. one with name "*".
:return: an wildcard intent definition, from the skill definition,
if found, or None.
"""
for intent_def in self.intent_defs:
if intent_def.name == "*":
return intent_def
return None
def find_notification(self, name):
""" Find a notification definition in the list of notifications
that the skill declares.
:param name: the name of the notification object to look for.
:return: a notification definition, from the skill definition,
if found, or None.
"""
for notification_def in self.notification_defs:
if notification_def.name == name:
return notification_def
return None
def find_dialogue_event(self, name):
""" Find a dialogue event definition in the list of dialogue events
that the skill declares.
:param name: the name of the dialogue event object to look for.
:return: a dialogue event definition, from the skill definition,
if found, or None.
"""
for dialogue_event_def in self.dialogue_events_defs:
if dialogue_event_def.name == name:
return dialogue_event_def
return None
| {
"content_hash": "8b682212fc25ab7e25694cf9f700fcf6",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 144,
"avg_line_length": 38.19047619047619,
"alnum_prop": 0.6119077306733167,
"repo_name": "snipsco/snipsskills",
"id": "ec4e47c4116f3b21e58a18e13035c2d6d5131b57",
"size": "3232",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "snipsmanager/models/skilldef.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "352588"
},
{
"name": "HTML",
"bytes": "15456"
},
{
"name": "Python",
"bytes": "117638"
},
{
"name": "Ruby",
"bytes": "2213"
},
{
"name": "Shell",
"bytes": "11808"
}
],
"symlink_target": ""
} |
import catkin_sphinx
import os
import sys
import subprocess
from xml.etree.ElementTree import ElementTree
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.ifconfig', 'sphinx.ext.todo', 'sphinx.ext.graphviz',
'sphinx.ext.intersphinx',
'catkin_sphinx.ShLexer', 'catkin_sphinx.cmake',
'sphinx.ext.autodoc', 'sphinx.ext.viewcode']
todo_include_todos = True
# include path to python files hidden in cmake folder
sys.path.insert(0, '../cmake')
sys.path.insert(0, '../python')
# 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'
show_sphinx = False
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'catkin'
gitcmd = 'git log -n1 --pretty=format:%cD'.split()
lastmod = subprocess.Popen(gitcmd, stdout=subprocess.PIPE).communicate()[0]
dochash = subprocess.Popen('git log -n1 --pretty=format:%H'.split(),
stdout=subprocess.PIPE).communicate()[0]
print "dochash=", dochash
copyright = u'2010, Willow Garage -- ' + ' Version ' + dochash + ", " + ' '.join(lastmod.split(' ')[:4])
# 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.
try:
root = ElementTree(None, os.path.join('..', 'package.xml'))
version = root.findtext('version')
except Exception as e:
raise RuntimeError('Could not extract version from package.xml:\n%s' % e)
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# 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 = True
# 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 ---------------------------------------------------
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = [os.path.join(os.path.dirname(catkin_sphinx.__file__),
'theme')]
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'ros-theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = { 'rightsidebar' : 'true' }
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = 'catkin'
# 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 = 'ros.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = 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.
#
# tds: We don't use this, we use the git timestamp
#
# 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_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'catkin-cmakedoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'catkin.tex', ur'Catkin',
ur'troy d. straszheim', '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
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
intersphinx_mapping = {
'genmsg': ('http://docs.ros.org/indigo/api/genmsg/html', None),
'vcstools': ('http://docs.ros.org/independent/api/vcstools/html', None),
'rosinstall': ('http://docs.ros.org/independent/api/rosinstall/html', None),
'rospkg': ('http://docs.ros.org/independent/api/rospkg/html', None),
'rosdep': ('http://docs.ros.org/independent/api/rosdep/html', None),
}
rst_epilog="""
"""
| {
"content_hash": "e6c33c81fa3fbcb6035fd7fc062adf38",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 104,
"avg_line_length": 33.18807339449541,
"alnum_prop": 0.6939875604699378,
"repo_name": "shyamalschandra/catkin",
"id": "471d70dd9ddb08f13c4443a0bdc1cf4bc0064694",
"size": "7653",
"binary": false,
"copies": "2",
"ref": "refs/heads/indigo-devel",
"path": "doc/conf.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "2631"
},
{
"name": "EmberScript",
"bytes": "3583"
},
{
"name": "Makefile",
"bytes": "5471"
},
{
"name": "Python",
"bytes": "253244"
},
{
"name": "Shell",
"bytes": "17627"
}
],
"symlink_target": ""
} |
import sys
import os
sys.path.append(
os.path.join(os.path.dirname(__file__), "../")
)
import yaml
import unittest
from pymongo import MongoClient
from bson.json_util import loads as json_loads
from utils import load_test_info
from utils import print_desc
from utils import print_msg
from utils import setup_dataset
from utils import remove_res
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
##############################################################################
class TestFreshRun(unittest.TestCase):
def setUp(self):
os.chdir(CURRENT_DIR)
self.test_name = os.path.basename(CURRENT_DIR)
self.test_info = load_test_info(self.test_name)
self.coll_name = self.test_info['coll_names'][0]
self.conn_src = self.test_info['conn_src']
self.conn_dest = self.test_info['conn_dest']
self.db_src = self.test_info['db_src']
self.db_dest = self.test_info['db_dest']
self.coll_src = self.db_src[self.coll_name]
self.coll_dest = self.db_dest[self.coll_name]
remove_res(self.test_info['temp_res'])
setup_dataset(
coll=self.coll_src,
dataset_file=os.path.join(CURRENT_DIR, 'data.json')
)
def tearDown(self):
print_msg("Dropping {} in source and destination".format(
self.coll_name
))
self.coll_src.drop()
self.coll_dest.drop()
self.conn_src.close()
self.conn_dest.close()
remove_res(self.test_info['temp_res'])
def test_freshrun(self):
self.coll_dest.drop()
print_msg('Running {} test'.format(self.test_name))
os.system(
'../../src/mongob --config config.yaml'
+ ' --progress-file current_progress.yaml'
+ ' --log backup.log'
)
print_msg('Checking result for {}'.format(self.test_name))
with open(self.test_info['dataset_file'], 'r') as input:
data_from_file = json_loads(input.read())
data_from_file.sort(key=lambda x: x['_id'])
data_from_src = list(self.coll_src.find().sort('_id', 1))
data_from_dest = list(self.coll_dest.find().sort('_id', 1))
self.assertEqual(data_from_file, data_from_src)
self.assertEqual(data_from_file, data_from_dest)
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "6a50cadfb5e945da9506142c79c4817f",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 78,
"avg_line_length": 29.365853658536587,
"alnum_prop": 0.5743355481727574,
"repo_name": "cmpitg/mongob",
"id": "8150621765f6879ec7ff8446d20c534585e4d5b5",
"size": "2564",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/fresh/run_test.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "30082"
}
],
"symlink_target": ""
} |
import Renascence
def main():
Renascence.setStreamPath("./")
Renascence.setLibPath("./")
producer = Renascence.init(["func.xml"])
print producer.listAllFunctions()
print producer.listAllTypes()
x0 = producer.load('TrBmp', "input.jpg")
x1 = producer.load('TrBmp', "input_sharp.jpg")
x2 = producer.load('TrBmp', "output.jpg")
filterMatrix = producer.build("FR(x0, x1)").run(producer.merge(x2, x1))
print filterMatrix.dump()
[Trainner, BestValue] = producer.train("S(ADF(Treator,x0,x1))", producer.merge(x0, x1), 5, cacheFile='temp.txt', postFormula='FIT(x0, x1)', postExtraInput=x2)
formula = Trainner.ADF("")
print 'Formula: ', formula
print 'Parameters: ', Trainner.parameters()
print BestValue
predictor = producer.build(formula, Trainner.parameters())
y_p = predictor.run(producer.merge(x0,x1))
y_p.save("output/output_trained.jpg")
main()
| {
"content_hash": "621f399ddd6affd934bdd4f9bfe22b6c",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 162,
"avg_line_length": 36.72,
"alnum_prop": 0.6699346405228758,
"repo_name": "jxt1234/Genetic-Program-Frame",
"id": "06edaedf5460cc384414260e8e396d747e92dbd6",
"size": "936",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "re_python_example.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "48934"
},
{
"name": "C++",
"bytes": "563967"
},
{
"name": "Makefile",
"bytes": "45490"
},
{
"name": "Python",
"bytes": "26735"
},
{
"name": "Shell",
"bytes": "581"
}
],
"symlink_target": ""
} |
import subprocess
ESCAPE_CHARS = {"'", ' ', '(', ')', '&', ',', ';'}
class Shell(object):
def __init__(self, aliases=None):
self.aliases = aliases
def apply_aliases(self, command):
if self.aliases is not None:
for key, val in self.aliases.iteritems():
command = command.replace(key, val)
return command
def cmd(self, command, _shell=True):
command = self.apply_aliases(command)
p = subprocess.Popen(command, shell=_shell,
stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
text, err = p.communicate()
return text
def escape(s):
L = []
for c in s:
if c in ESCAPE_CHARS:
L.append('\\')
L.append(c)
return ''.join(L)
| {
"content_hash": "9e01bf6351724976fc85d901fa54986b",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 78,
"avg_line_length": 27.964285714285715,
"alnum_prop": 0.5389527458492975,
"repo_name": "bluquar/itunes_android_nofluff",
"id": "0d30e890565fbcd72acbec32104535b083d4c9d3",
"size": "783",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "shell.py",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import psutil
from pkg_resources import get_distribution
from django.conf import settings
from django.db import connections
from django.utils.module_loading import import_string
import logging
import os
import six
import socket
import sys
import tempfile
import time
from collections import OrderedDict
from datetime import datetime
from django_sysinfo.compat import get_installed_apps, get_installed_distributions
from django_sysinfo.utils import get_network, humanize_bytes
from .conf import config
logger = logging.getLogger(__name__)
UNKNOWN = "unknown"
def _run_database_statement(conn, stm, offset=0):
if not stm:
return UNKNOWN
c = conn.cursor()
c.execute(stm)
row = c.fetchone()
if row:
return row[offset]
def _get_database_infos(conn):
engine = conn.settings_dict.get("ENGINE")
ret = OrderedDict()
if engine == "django.db.backends.mysql":
ret["version"] = _run_database_statement(conn, "SELECT VERSION();")
ret["user"] = _run_database_statement(conn, "SELECT USER();")
# ret["basedir"] = _run_database_statement(conn, "SHOW VARIABLES LIKE '%BASEDIR%';", 1)
# ret["max_connections"] = _run_database_statement(conn, "SHOW VARIABLES LIKE '%MAX_CONNECTIONS%';", 1)
elif engine == "django.db.backends.postgresql_psycopg2":
import psycopg2.extensions
ret["version"] = _run_database_statement(conn, "SHOW server_version;")
ret["encoding"] = _run_database_statement(conn, "SHOW SERVER_ENCODING;")
ret["collate"] = _run_database_statement(conn, "SHOW LC_COLLATE;")
ret["ctype"] = _run_database_statement(conn, "SHOW LC_CTYPE;")
isolation_level = conn.isolation_level
for attr in ["ISOLATION_LEVEL_AUTOCOMMIT",
"ISOLATION_LEVEL_READ_UNCOMMITTED",
"ISOLATION_LEVEL_READ_COMMITTED",
"ISOLATION_LEVEL_REPEATABLE_READ",
"ISOLATION_LEVEL_SERIALIZABLE"]:
if conn.isolation_level == getattr(psycopg2.extensions, attr, None):
isolation_level = attr
ret["isolation_level"] = isolation_level
ret["timezone"] = conn.connection.get_parameter_status("TimeZone")
ret["info"] = _run_database_statement(conn, "SELECT version();")
elif engine == "django.db.backends.sqlite3":
ret["version"] = _run_database_statement(conn, "select sqlite_version();")
elif engine == "django.db.backends.oracle":
ret["version"] = _run_database_statement(conn, "select * from $version;")
else:
ret["info"] = 'DATABASE NOT SUPPORTED'
return ret
def get_databases(**kwargs):
databases = OrderedDict()
for alias in connections:
db = OrderedDict()
try:
conn = connections[alias]
db["engine"] = conn.settings_dict.get("ENGINE")
db["host"] = "%(HOST)s:%(PORT)s" % conn.settings_dict
db["name"] = conn.settings_dict.get("NAME")
db.update(_get_database_infos(conn))
except Exception as e:
db["error"] = str(e)
finally:
databases[alias] = db
return databases
def get_modules(**kwargs):
modules = OrderedDict()
for i in sorted(get_installed_distributions(),
key=lambda i: i.project_name.lower()):
modules[i.project_name.lower()] = i.version
return modules
def get_host(**kwargs):
mem = psutil.virtual_memory()
host = OrderedDict()
host["hostname"] = socket.gethostname()
host["fqdn"] = socket.getfqdn()
host["cpus"] = psutil.cpu_count()
host["network"] = get_network()
host["memory"] = {"total": humanize_bytes(mem.total),
"available": humanize_bytes(mem.available),
"percent": humanize_bytes(mem.percent),
"used": humanize_bytes(mem.used),
"free": humanize_bytes(mem.free)}
return host
def get_python(**kwargs):
p = OrderedDict()
p["executable"] = sys.executable
p["version"] = "{0.major}.{0.minor}.{0.micro}".format(sys.version_info)
p["platform"] = sys.platform
p["info"] = sys.version
p["maxunicode"] = (sys.maxunicode,
{True: "OK", False: "WARN"}[sys.maxunicode > 0xffff])
return p
def get_mail(**kwargs):
def check():
from django.core.mail import get_connection
try:
conn = get_connection(fail_silently=False)
conn.open()
ret = "OK"
conn.close()
except Exception as e:
ret = str(e)
return ret
p = OrderedDict()
p["backend"] = settings.EMAIL_BACKEND
p["host"] = "{0}:{1}".format(settings.EMAIL_HOST, settings.EMAIL_PORT)
p["tls"] = getattr(settings, "EMAIL_USE_TLS", False)
p["ssl"] = getattr(settings, "EMAIL_USE_SSL", False)
p["status"] = check()
return p
def get_device_info(path):
try:
info = psutil.disk_usage(os.path.realpath(path))
return {"total": humanize_bytes(info.total),
"used": humanize_bytes(info.used),
"free": humanize_bytes(info.free)}
except TypeError:
return {"total": "N/A",
"used": "N/A",
"free": "N/A",
}
except OSError as e:
return {"ERROR": str(e)}
def get_caches_info():
ret = dict(settings.CACHES)
for k, v in ret.items():
backend = settings.CACHES[k]["BACKEND"]
loc = settings.CACHES[k].get("LOCATION", None)
if backend == "django.core.cache.backends.filebased.FileBasedCache":
ret[k]["status"] = get_device_info(loc)
return ret
def get_process(**kwargs):
process = OrderedDict()
p = psutil.Process(None)
from dateutil.relativedelta import relativedelta
end_time = datetime.now()
start_time = datetime.fromtimestamp(p.create_time())
diff = relativedelta(end_time, start_time)
diff_string = ""
for e in ("years", "months", "days", "hours", "minutes", "seconds"):
v = getattr(diff, e)
if v > 0:
if v == 1:
e = e[:-1]
diff_string += f"{v} {e} "
process['Name'] = p.name()
process['Command'] = p.cmdline()
process['Start Time'] = time.strftime("%d %b %Y %H:%M:%S", time.localtime(p.create_time()))
process['Uptime'] = diff_string
return process
def get_project(**kwargs):
project = OrderedDict()
project["current_dir"] = os.path.realpath(os.curdir)
project["tempdir"] = tempfile.gettempdir()
if config.MEDIA_ROOT:
project["MEDIA_ROOT"] = OrderedDict([("path", settings.MEDIA_ROOT),
("disk", get_device_info(settings.MEDIA_ROOT))])
if config.STATIC_ROOT:
project["STATIC_ROOT"] = OrderedDict([("path", settings.STATIC_ROOT),
("disk", get_device_info(settings.STATIC_ROOT))])
if config.DATABASES:
project["DATABASES"] = get_databases()
if config.CACHES:
project["CACHES"] = get_caches_info()
if config.installed_apps:
project["installed_apps"] = get_installed_apps()
if config.mail:
project["mail"] = get_mail(**kwargs)
return project
def get_os(**kwargs):
return {"uname": os.uname(),
"name": os.name}
def run_check(id, request=None, fail_silently=True, fail_status=500):
status = 200
try:
v = config.checks[id]
if isinstance(v, six.string_types):
c = import_string(v)
ret, status = c(request)
elif callable(v):
ret, status = v(request)
else:
ret = v
except Exception as e:
ret = "ERROR"
status = fail_status
logger.exception(e)
if settings.DEBUG:
ret = str(e)
if not fail_silently:
raise
return ret, status
def get_checks(request=None):
checks = {}
if config.checks:
for k, v in config.checks.items():
checks[k] = run_check(k)
return checks
def get_extra(config, request=None):
extras = {}
for k, v in config.extra.items():
try:
if isinstance(v, six.string_types):
c = import_string(v)
extras[k] = c(request)
elif callable(v):
extras[k] = v(request)
else:
extras[k] = v
except Exception as e:
logger.exception(e)
if settings.DEBUG:
extras[k] = str(e)
return extras
def get_environment(config=None, request=None):
ret = {}
if isinstance(config.filter_environment, str):
filter_environment = import_string(config.filter_environment)
elif callable(config.filter_environment):
filter_environment = config.filter_environment
else:
raise ValueError('Invalid value for "sysinfo.filter_environment"')
if isinstance(config.masker, str):
obfuscator = import_string(config.masker)
elif callable(config.masker):
obfuscator = config.masker
else:
raise ValueError('Invalid value for "sysinfo.masker"')
for key, value in os.environ.items():
if not filter_environment(key, config=config, request=request):
ret[key] = obfuscator(key, value, config=config, request=request)
return OrderedDict(sorted(ret.items()))
handlers = OrderedDict([("host", get_host),
("os", get_os),
("environ", get_environment),
("python", get_python),
("modules", get_modules),
("process", get_process),
("project", get_project),
("extra", get_extra),
("checks", get_checks)])
valid_sections = handlers.keys()
def get_sysinfo(request):
data = OrderedDict()
sections = request.GET.get("s", None)
if sections is None:
sections = valid_sections
else:
sections = sections.split(",")
for section in sections:
if section in valid_sections and getattr(config, section):
data[section] = handlers[section](config=config, request=request)
return data
def get_version(name):
try:
version = get_distribution(name).version
except Exception:
version = UNKNOWN
return version
| {
"content_hash": "6f4bfe860f509ab6fd3af075c03b4917",
"timestamp": "",
"source": "github",
"line_count": 334,
"max_line_length": 111,
"avg_line_length": 31.32934131736527,
"alnum_prop": 0.5822821100917431,
"repo_name": "saxix/django-sysinfo",
"id": "1f692943b2855b53422d410e33123d553b5af644",
"size": "10464",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/django_sysinfo/api.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "5702"
},
{
"name": "Makefile",
"bytes": "1615"
},
{
"name": "Python",
"bytes": "50580"
},
{
"name": "SCSS",
"bytes": "346"
}
],
"symlink_target": ""
} |
def test_sdkmanager_can_run_without_problem(host):
assert host.run_expect([0], ". ~/profile.d/android.sh && sdkmanager --list")
def test_cmdline_tools_installed_and_available(host):
cmd = host.run(". ~/profile.d/android.sh && env")
assert "cmdline-tools" in cmd.stdout
def test_installed_sdkmanager_packages(host):
variables = get_variables_from_defaults(host)
for package in variables['sdkmanagerpackages']:
assert host.run_expect([0], '. ~/profile.d/android.sh && ls $ANDROID_HOME/%s' % package['name'].replace(";", "/"))
def get_variables_from_defaults(host):
return host.ansible("include_vars", "file=../../../android/defaults/main.yml")['ansible_facts']
| {
"content_hash": "df3c4fdd28d22ce1c70a017da83f6fcb",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 118,
"avg_line_length": 48.42857142857143,
"alnum_prop": 0.700589970501475,
"repo_name": "bitrise-io/osx-box-bootstrap",
"id": "e1aea0a43c25defe47f745d69f56befdd8054fd2",
"size": "678",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "roles/android/tests/test_android.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "505"
},
{
"name": "Jinja",
"bytes": "4408"
},
{
"name": "Python",
"bytes": "16668"
},
{
"name": "Ruby",
"bytes": "509"
},
{
"name": "Shell",
"bytes": "24197"
}
],
"symlink_target": ""
} |
"""
Django settings for proj project in development.
For more information on this file, see
https://docs.djangoproject.com/en/2.2.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
from libpredweb import myfunc
from libpredweb import webserver_common as webcom
try:
from .shared_settings import *
except ImportError:
pass
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2.7/howto/deployment/checklist/
SECRET_KEY = '5&!cq9#+(_=!ou=mco0=-qrmn6h66o(f)h$ho4+0vo1#d24xdy'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
allowed_host_file = "%s/allowed_host_dev.txt"%(BASE_DIR)
computenodefile = "%s/pred/config/computenode.txt"%(BASE_DIR)
for f in [allowed_host_file, computenodefile]:
if os.path.exists(f):
ALLOWED_HOSTS += myfunc.ReadIDList2(f,col=0)
# add also the host ip address
hostip = webcom.get_external_ip()
ALLOWED_HOSTS.append(hostip)
| {
"content_hash": "374d35da51a6499d90eb75ed16ad8435",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 73,
"avg_line_length": 31.42105263157895,
"alnum_prop": 0.7370184254606366,
"repo_name": "ElofssonLab/web_common_backend",
"id": "21f461f9a8f37c71a8883529a266879f2aebbd80",
"size": "1194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "proj/dev_settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "79046"
},
{
"name": "HTML",
"bytes": "64371"
},
{
"name": "JavaScript",
"bytes": "87235"
},
{
"name": "Makefile",
"bytes": "1097"
},
{
"name": "Perl",
"bytes": "133981"
},
{
"name": "Python",
"bytes": "280192"
},
{
"name": "Shell",
"bytes": "4017"
}
],
"symlink_target": ""
} |
"""scons.Node.FS
File system nodes.
These Nodes represent the canonical external objects that people think
of when they think of building software: files and directories.
This holds a "default_fs" variable that should be initialized with an FS
that can be used by scripts or modules looking for the canonical default.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
__revision__ = "src/engine/SCons/Node/FS.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo"
import fnmatch
import os
import re
import shutil
import stat
import sys
import time
import codecs
import SCons.Action
from SCons.Debug import logInstanceCreation
import SCons.Errors
import SCons.Memoize
import SCons.Node
import SCons.Node.Alias
import SCons.Subst
import SCons.Util
import SCons.Warnings
from SCons.Debug import Trace
do_store_info = True
print_duplicate = 0
class EntryProxyAttributeError(AttributeError):
"""
An AttributeError subclass for recording and displaying the name
of the underlying Entry involved in an AttributeError exception.
"""
def __init__(self, entry_proxy, attribute):
AttributeError.__init__(self)
self.entry_proxy = entry_proxy
self.attribute = attribute
def __str__(self):
entry = self.entry_proxy.get()
fmt = "%s instance %s has no attribute %s"
return fmt % (entry.__class__.__name__,
repr(entry.name),
repr(self.attribute))
# The max_drift value: by default, use a cached signature value for
# any file that's been untouched for more than two days.
default_max_drift = 2*24*60*60
#
# We stringify these file system Nodes a lot. Turning a file system Node
# into a string is non-trivial, because the final string representation
# can depend on a lot of factors: whether it's a derived target or not,
# whether it's linked to a repository or source directory, and whether
# there's duplication going on. The normal technique for optimizing
# calculations like this is to memoize (cache) the string value, so you
# only have to do the calculation once.
#
# A number of the above factors, however, can be set after we've already
# been asked to return a string for a Node, because a Repository() or
# VariantDir() call or the like may not occur until later in SConscript
# files. So this variable controls whether we bother trying to save
# string values for Nodes. The wrapper interface can set this whenever
# they're done mucking with Repository and VariantDir and the other stuff,
# to let this module know it can start returning saved string values
# for Nodes.
#
Save_Strings = None
def save_strings(val):
global Save_Strings
Save_Strings = val
#
# Avoid unnecessary function calls by recording a Boolean value that
# tells us whether or not os.path.splitdrive() actually does anything
# on this system, and therefore whether we need to bother calling it
# when looking up path names in various methods below.
#
do_splitdrive = None
_my_splitdrive =None
def initialize_do_splitdrive():
global do_splitdrive
global has_unc
drive, path = os.path.splitdrive('X:/foo')
has_unc = hasattr(os.path, 'splitunc')
do_splitdrive = not not drive or has_unc
global _my_splitdrive
if has_unc:
def splitdrive(p):
if p[1:2] == ':':
return p[:2], p[2:]
if p[0:2] == '//':
# Note that we leave a leading slash in the path
# because UNC paths are always absolute.
return '//', p[1:]
return '', p
else:
def splitdrive(p):
if p[1:2] == ':':
return p[:2], p[2:]
return '', p
_my_splitdrive = splitdrive
# Keep some commonly used values in global variables to skip to
# module look-up costs.
global OS_SEP
global UNC_PREFIX
global os_sep_is_slash
OS_SEP = os.sep
UNC_PREFIX = OS_SEP + OS_SEP
os_sep_is_slash = OS_SEP == '/'
initialize_do_splitdrive()
# Used to avoid invoking os.path.normpath if not necessary.
needs_normpath_check = re.compile(
r'''
# We need to renormalize the path if it contains any consecutive
# '/' characters.
.*// |
# We need to renormalize the path if it contains a '..' directory.
# Note that we check for all the following cases:
#
# a) The path is a single '..'
# b) The path starts with '..'. E.g. '../' or '../moredirs'
# but we not match '..abc/'.
# c) The path ends with '..'. E.g. '/..' or 'dirs/..'
# d) The path contains a '..' in the middle.
# E.g. dirs/../moredirs
(.*/)?\.\.(?:/|$) |
# We need to renormalize the path if it contains a '.'
# directory, but NOT if it is a single '.' '/' characters. We
# do not want to match a single '.' because this case is checked
# for explicitely since this is common enough case.
#
# Note that we check for all the following cases:
#
# a) We don't match a single '.'
# b) We match if the path starts with '.'. E.g. './' or
# './moredirs' but we not match '.abc/'.
# c) We match if the path ends with '.'. E.g. '/.' or
# 'dirs/.'
# d) We match if the path contains a '.' in the middle.
# E.g. dirs/./moredirs
\./|.*/\.(?:/|$)
''',
re.VERBOSE
)
needs_normpath_match = needs_normpath_check.match
#
# SCons.Action objects for interacting with the outside world.
#
# The Node.FS methods in this module should use these actions to
# create and/or remove files and directories; they should *not* use
# os.{link,symlink,unlink,mkdir}(), etc., directly.
#
# Using these SCons.Action objects ensures that descriptions of these
# external activities are properly displayed, that the displays are
# suppressed when the -s (silent) option is used, and (most importantly)
# the actions are disabled when the the -n option is used, in which case
# there should be *no* changes to the external file system(s)...
#
if hasattr(os, 'link'):
def _hardlink_func(fs, src, dst):
# If the source is a symlink, we can't just hard-link to it
# because a relative symlink may point somewhere completely
# different. We must disambiguate the symlink and then
# hard-link the final destination file.
while fs.islink(src):
link = fs.readlink(src)
if not os.path.isabs(link):
src = link
else:
src = os.path.join(os.path.dirname(src), link)
fs.link(src, dst)
else:
_hardlink_func = None
if hasattr(os, 'symlink'):
def _softlink_func(fs, src, dst):
fs.symlink(src, dst)
else:
_softlink_func = None
def _copy_func(fs, src, dest):
shutil.copy2(src, dest)
st = fs.stat(src)
fs.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
Valid_Duplicates = ['hard-soft-copy', 'soft-hard-copy',
'hard-copy', 'soft-copy', 'copy']
Link_Funcs = [] # contains the callables of the specified duplication style
def set_duplicate(duplicate):
# Fill in the Link_Funcs list according to the argument
# (discarding those not available on the platform).
# Set up the dictionary that maps the argument names to the
# underlying implementations. We do this inside this function,
# not in the top-level module code, so that we can remap os.link
# and os.symlink for testing purposes.
link_dict = {
'hard' : _hardlink_func,
'soft' : _softlink_func,
'copy' : _copy_func
}
if not duplicate in Valid_Duplicates:
raise SCons.Errors.InternalError("The argument of set_duplicate "
"should be in Valid_Duplicates")
global Link_Funcs
Link_Funcs = []
for func in duplicate.split('-'):
if link_dict[func]:
Link_Funcs.append(link_dict[func])
def LinkFunc(target, source, env):
# Relative paths cause problems with symbolic links, so
# we use absolute paths, which may be a problem for people
# who want to move their soft-linked src-trees around. Those
# people should use the 'hard-copy' mode, softlinks cannot be
# used for that; at least I have no idea how ...
src = source[0].abspath
dest = target[0].abspath
dir, file = os.path.split(dest)
if dir and not target[0].fs.isdir(dir):
os.makedirs(dir)
if not Link_Funcs:
# Set a default order of link functions.
set_duplicate('hard-soft-copy')
fs = source[0].fs
# Now link the files with the previously specified order.
for func in Link_Funcs:
try:
func(fs, src, dest)
break
except (IOError, OSError):
# An OSError indicates something happened like a permissions
# problem or an attempt to symlink across file-system
# boundaries. An IOError indicates something like the file
# not existing. In either case, keeping trying additional
# functions in the list and only raise an error if the last
# one failed.
if func == Link_Funcs[-1]:
# exception of the last link method (copy) are fatal
raise
return 0
Link = SCons.Action.Action(LinkFunc, None)
def LocalString(target, source, env):
return 'Local copy of %s from %s' % (target[0], source[0])
LocalCopy = SCons.Action.Action(LinkFunc, LocalString)
def UnlinkFunc(target, source, env):
t = target[0]
t.fs.unlink(t.abspath)
return 0
Unlink = SCons.Action.Action(UnlinkFunc, None)
def MkdirFunc(target, source, env):
t = target[0]
if not t.exists():
t.fs.mkdir(t.abspath)
return 0
Mkdir = SCons.Action.Action(MkdirFunc, None, presub=None)
MkdirBuilder = None
def get_MkdirBuilder():
global MkdirBuilder
if MkdirBuilder is None:
import SCons.Builder
import SCons.Defaults
# "env" will get filled in by Executor.get_build_env()
# calling SCons.Defaults.DefaultEnvironment() when necessary.
MkdirBuilder = SCons.Builder.Builder(action = Mkdir,
env = None,
explain = None,
is_explicit = None,
target_scanner = SCons.Defaults.DirEntryScanner,
name = "MkdirBuilder")
return MkdirBuilder
class _Null(object):
pass
_null = _Null()
DefaultSCCSBuilder = None
DefaultRCSBuilder = None
def get_DefaultSCCSBuilder():
global DefaultSCCSBuilder
if DefaultSCCSBuilder is None:
import SCons.Builder
# "env" will get filled in by Executor.get_build_env()
# calling SCons.Defaults.DefaultEnvironment() when necessary.
act = SCons.Action.Action('$SCCSCOM', '$SCCSCOMSTR')
DefaultSCCSBuilder = SCons.Builder.Builder(action = act,
env = None,
name = "DefaultSCCSBuilder")
return DefaultSCCSBuilder
def get_DefaultRCSBuilder():
global DefaultRCSBuilder
if DefaultRCSBuilder is None:
import SCons.Builder
# "env" will get filled in by Executor.get_build_env()
# calling SCons.Defaults.DefaultEnvironment() when necessary.
act = SCons.Action.Action('$RCS_COCOM', '$RCS_COCOMSTR')
DefaultRCSBuilder = SCons.Builder.Builder(action = act,
env = None,
name = "DefaultRCSBuilder")
return DefaultRCSBuilder
# Cygwin's os.path.normcase pretends it's on a case-sensitive filesystem.
_is_cygwin = sys.platform == "cygwin"
if os.path.normcase("TeSt") == os.path.normpath("TeSt") and not _is_cygwin:
def _my_normcase(x):
return x
else:
def _my_normcase(x):
return x.upper()
class DiskChecker(object):
def __init__(self, type, do, ignore):
self.type = type
self.do = do
self.ignore = ignore
self.func = do
def __call__(self, *args, **kw):
return self.func(*args, **kw)
def set(self, list):
if self.type in list:
self.func = self.do
else:
self.func = self.ignore
def do_diskcheck_match(node, predicate, errorfmt):
result = predicate()
try:
# If calling the predicate() cached a None value from stat(),
# remove it so it doesn't interfere with later attempts to
# build this Node as we walk the DAG. (This isn't a great way
# to do this, we're reaching into an interface that doesn't
# really belong to us, but it's all about performance, so
# for now we'll just document the dependency...)
if node._memo['stat'] is None:
del node._memo['stat']
except (AttributeError, KeyError):
pass
if result:
raise TypeError(errorfmt % node.abspath)
def ignore_diskcheck_match(node, predicate, errorfmt):
pass
def do_diskcheck_rcs(node, name):
try:
rcs_dir = node.rcs_dir
except AttributeError:
if node.entry_exists_on_disk('RCS'):
rcs_dir = node.Dir('RCS')
else:
rcs_dir = None
node.rcs_dir = rcs_dir
if rcs_dir:
return rcs_dir.entry_exists_on_disk(name+',v')
return None
def ignore_diskcheck_rcs(node, name):
return None
def do_diskcheck_sccs(node, name):
try:
sccs_dir = node.sccs_dir
except AttributeError:
if node.entry_exists_on_disk('SCCS'):
sccs_dir = node.Dir('SCCS')
else:
sccs_dir = None
node.sccs_dir = sccs_dir
if sccs_dir:
return sccs_dir.entry_exists_on_disk('s.'+name)
return None
def ignore_diskcheck_sccs(node, name):
return None
diskcheck_match = DiskChecker('match', do_diskcheck_match, ignore_diskcheck_match)
diskcheck_rcs = DiskChecker('rcs', do_diskcheck_rcs, ignore_diskcheck_rcs)
diskcheck_sccs = DiskChecker('sccs', do_diskcheck_sccs, ignore_diskcheck_sccs)
diskcheckers = [
diskcheck_match,
diskcheck_rcs,
diskcheck_sccs,
]
def set_diskcheck(list):
for dc in diskcheckers:
dc.set(list)
def diskcheck_types():
return [dc.type for dc in diskcheckers]
class EntryProxy(SCons.Util.Proxy):
__str__ = SCons.Util.Delegate('__str__')
def __get_abspath(self):
entry = self.get()
return SCons.Subst.SpecialAttrWrapper(entry.get_abspath(),
entry.name + "_abspath")
def __get_filebase(self):
name = self.get().name
return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(name)[0],
name + "_filebase")
def __get_suffix(self):
name = self.get().name
return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(name)[1],
name + "_suffix")
def __get_file(self):
name = self.get().name
return SCons.Subst.SpecialAttrWrapper(name, name + "_file")
def __get_base_path(self):
"""Return the file's directory and file name, with the
suffix stripped."""
entry = self.get()
return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(entry.get_path())[0],
entry.name + "_base")
def __get_posix_path(self):
"""Return the path with / as the path separator,
regardless of platform."""
if os_sep_is_slash:
return self
else:
entry = self.get()
r = entry.get_path().replace(OS_SEP, '/')
return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_posix")
def __get_windows_path(self):
"""Return the path with \ as the path separator,
regardless of platform."""
if OS_SEP == '\\':
return self
else:
entry = self.get()
r = entry.get_path().replace(OS_SEP, '\\')
return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_windows")
def __get_srcnode(self):
return EntryProxy(self.get().srcnode())
def __get_srcdir(self):
"""Returns the directory containing the source node linked to this
node via VariantDir(), or the directory of this node if not linked."""
return EntryProxy(self.get().srcnode().dir)
def __get_rsrcnode(self):
return EntryProxy(self.get().srcnode().rfile())
def __get_rsrcdir(self):
"""Returns the directory containing the source node linked to this
node via VariantDir(), or the directory of this node if not linked."""
return EntryProxy(self.get().srcnode().rfile().dir)
def __get_dir(self):
return EntryProxy(self.get().dir)
dictSpecialAttrs = { "base" : __get_base_path,
"posix" : __get_posix_path,
"windows" : __get_windows_path,
"win32" : __get_windows_path,
"srcpath" : __get_srcnode,
"srcdir" : __get_srcdir,
"dir" : __get_dir,
"abspath" : __get_abspath,
"filebase" : __get_filebase,
"suffix" : __get_suffix,
"file" : __get_file,
"rsrcpath" : __get_rsrcnode,
"rsrcdir" : __get_rsrcdir,
}
def __getattr__(self, name):
# This is how we implement the "special" attributes
# such as base, posix, srcdir, etc.
try:
attr_function = self.dictSpecialAttrs[name]
except KeyError:
try:
attr = SCons.Util.Proxy.__getattr__(self, name)
except AttributeError, e:
# Raise our own AttributeError subclass with an
# overridden __str__() method that identifies the
# name of the entry that caused the exception.
raise EntryProxyAttributeError(self, name)
return attr
else:
return attr_function(self)
class Base(SCons.Node.Node):
"""A generic class for file system entries. This class is for
when we don't know yet whether the entry being looked up is a file
or a directory. Instances of this class can morph into either
Dir or File objects by a later, more precise lookup.
Note: this class does not define __cmp__ and __hash__ for
efficiency reasons. SCons does a lot of comparing of
Node.FS.{Base,Entry,File,Dir} objects, so those operations must be
as fast as possible, which means we want to use Python's built-in
object identity comparisons.
"""
memoizer_counters = []
def __init__(self, name, directory, fs):
"""Initialize a generic Node.FS.Base object.
Call the superclass initialization, take care of setting up
our relative and absolute paths, identify our parent
directory, and indicate that this node should use
signatures."""
if __debug__: logInstanceCreation(self, 'Node.FS.Base')
SCons.Node.Node.__init__(self)
# Filenames and paths are probably reused and are intern'ed to
# save some memory.
#: Filename with extension as it was specified when the object was
#: created; to obtain filesystem path, use Python str() function
self.name = SCons.Util.silent_intern(name)
#: Cached filename extension
self.suffix = SCons.Util.silent_intern(SCons.Util.splitext(name)[1])
self.fs = fs #: Reference to parent Node.FS object
assert directory, "A directory must be provided"
self.abspath = SCons.Util.silent_intern(directory.entry_abspath(name))
self.labspath = SCons.Util.silent_intern(directory.entry_labspath(name))
if directory.path == '.':
self.path = SCons.Util.silent_intern(name)
else:
self.path = SCons.Util.silent_intern(directory.entry_path(name))
if directory.tpath == '.':
self.tpath = SCons.Util.silent_intern(name)
else:
self.tpath = SCons.Util.silent_intern(directory.entry_tpath(name))
self.path_elements = directory.path_elements + [self]
self.dir = directory
self.cwd = None # will hold the SConscript directory for target nodes
self.duplicate = directory.duplicate
def str_for_display(self):
return '"' + self.__str__() + '"'
def must_be_same(self, klass):
"""
This node, which already existed, is being looked up as the
specified klass. Raise an exception if it isn't.
"""
if isinstance(self, klass) or klass is Entry:
return
raise TypeError("Tried to lookup %s '%s' as a %s." %\
(self.__class__.__name__, self.path, klass.__name__))
def get_dir(self):
return self.dir
def get_suffix(self):
return self.suffix
def rfile(self):
return self
def __str__(self):
"""A Node.FS.Base object's string representation is its path
name."""
global Save_Strings
if Save_Strings:
return self._save_str()
return self._get_str()
memoizer_counters.append(SCons.Memoize.CountValue('_save_str'))
def _save_str(self):
try:
return self._memo['_save_str']
except KeyError:
pass
result = sys.intern(self._get_str())
self._memo['_save_str'] = result
return result
def _get_str(self):
global Save_Strings
if self.duplicate or self.is_derived():
return self.get_path()
srcnode = self.srcnode()
if srcnode.stat() is None and self.stat() is not None:
result = self.get_path()
else:
result = srcnode.get_path()
if not Save_Strings:
# We're not at the point where we're saving the string
# representations of FS Nodes (because we haven't finished
# reading the SConscript files and need to have str() return
# things relative to them). That also means we can't yet
# cache values returned (or not returned) by stat(), since
# Python code in the SConscript files might still create
# or otherwise affect the on-disk file. So get rid of the
# values that the underlying stat() method saved.
try: del self._memo['stat']
except KeyError: pass
if self is not srcnode:
try: del srcnode._memo['stat']
except KeyError: pass
return result
rstr = __str__
memoizer_counters.append(SCons.Memoize.CountValue('stat'))
def stat(self):
try: return self._memo['stat']
except KeyError: pass
try: result = self.fs.stat(self.abspath)
except os.error: result = None
self._memo['stat'] = result
return result
def exists(self):
return self.stat() is not None
def rexists(self):
return self.rfile().exists()
def getmtime(self):
st = self.stat()
if st: return st[stat.ST_MTIME]
else: return None
def getsize(self):
st = self.stat()
if st: return st[stat.ST_SIZE]
else: return None
def isdir(self):
st = self.stat()
return st is not None and stat.S_ISDIR(st[stat.ST_MODE])
def isfile(self):
st = self.stat()
return st is not None and stat.S_ISREG(st[stat.ST_MODE])
if hasattr(os, 'symlink'):
def islink(self):
try: st = self.fs.lstat(self.abspath)
except os.error: return 0
return stat.S_ISLNK(st[stat.ST_MODE])
else:
def islink(self):
return 0 # no symlinks
def is_under(self, dir):
if self is dir:
return 1
else:
return self.dir.is_under(dir)
def set_local(self):
self._local = 1
def srcnode(self):
"""If this node is in a build path, return the node
corresponding to its source file. Otherwise, return
ourself.
"""
srcdir_list = self.dir.srcdir_list()
if srcdir_list:
srcnode = srcdir_list[0].Entry(self.name)
srcnode.must_be_same(self.__class__)
return srcnode
return self
def get_path(self, dir=None):
"""Return path relative to the current working directory of the
Node.FS.Base object that owns us."""
if not dir:
dir = self.fs.getcwd()
if self == dir:
return '.'
path_elems = self.path_elements
pathname = ''
try: i = path_elems.index(dir)
except ValueError:
for p in path_elems[:-1]:
pathname += p.dirname
else:
for p in path_elems[i+1:-1]:
pathname += p.dirname
return pathname + path_elems[-1].name
def set_src_builder(self, builder):
"""Set the source code builder for this node."""
self.sbuilder = builder
if not self.has_builder():
self.builder_set(builder)
def src_builder(self):
"""Fetch the source code builder for this node.
If there isn't one, we cache the source code builder specified
for the directory (which in turn will cache the value from its
parent directory, and so on up to the file system root).
"""
try:
scb = self.sbuilder
except AttributeError:
scb = self.dir.src_builder()
self.sbuilder = scb
return scb
def get_abspath(self):
"""Get the absolute path of the file."""
return self.abspath
def for_signature(self):
# Return just our name. Even an absolute path would not work,
# because that can change thanks to symlinks or remapped network
# paths.
return self.name
def get_subst_proxy(self):
try:
return self._proxy
except AttributeError:
ret = EntryProxy(self)
self._proxy = ret
return ret
def target_from_source(self, prefix, suffix, splitext=SCons.Util.splitext):
"""
Generates a target entry that corresponds to this entry (usually
a source file) with the specified prefix and suffix.
Note that this method can be overridden dynamically for generated
files that need different behavior. See Tool/swig.py for
an example.
"""
return self.dir.Entry(prefix + splitext(self.name)[0] + suffix)
def _Rfindalldirs_key(self, pathlist):
return pathlist
memoizer_counters.append(SCons.Memoize.CountDict('Rfindalldirs', _Rfindalldirs_key))
def Rfindalldirs(self, pathlist):
"""
Return all of the directories for a given path list, including
corresponding "backing" directories in any repositories.
The Node lookups are relative to this Node (typically a
directory), so memoizing result saves cycles from looking
up the same path for each target in a given directory.
"""
try:
memo_dict = self._memo['Rfindalldirs']
except KeyError:
memo_dict = {}
self._memo['Rfindalldirs'] = memo_dict
else:
try:
return memo_dict[pathlist]
except KeyError:
pass
create_dir_relative_to_self = self.Dir
result = []
for path in pathlist:
if isinstance(path, SCons.Node.Node):
result.append(path)
else:
dir = create_dir_relative_to_self(path)
result.extend(dir.get_all_rdirs())
memo_dict[pathlist] = result
return result
def RDirs(self, pathlist):
"""Search for a list of directories in the Repository list."""
cwd = self.cwd or self.fs._cwd
return cwd.Rfindalldirs(pathlist)
memoizer_counters.append(SCons.Memoize.CountValue('rentry'))
def rentry(self):
try:
return self._memo['rentry']
except KeyError:
pass
result = self
if not self.exists():
norm_name = _my_normcase(self.name)
for dir in self.dir.get_all_rdirs():
try:
node = dir.entries[norm_name]
except KeyError:
if dir.entry_exists_on_disk(self.name):
result = dir.Entry(self.name)
break
self._memo['rentry'] = result
return result
def _glob1(self, pattern, ondisk=True, source=False, strings=False):
return []
class Entry(Base):
"""This is the class for generic Node.FS entries--that is, things
that could be a File or a Dir, but we're just not sure yet.
Consequently, the methods in this class really exist just to
transform their associated object into the right class when the
time comes, and then call the same-named method in the transformed
class."""
def diskcheck_match(self):
pass
def disambiguate(self, must_exist=None):
"""
"""
if self.isdir():
self.__class__ = Dir
self._morph()
elif self.isfile():
self.__class__ = File
self._morph()
self.clear()
else:
# There was nothing on-disk at this location, so look in
# the src directory.
#
# We can't just use self.srcnode() straight away because
# that would create an actual Node for this file in the src
# directory, and there might not be one. Instead, use the
# dir_on_disk() method to see if there's something on-disk
# with that name, in which case we can go ahead and call
# self.srcnode() to create the right type of entry.
srcdir = self.dir.srcnode()
if srcdir != self.dir and \
srcdir.entry_exists_on_disk(self.name) and \
self.srcnode().isdir():
self.__class__ = Dir
self._morph()
elif must_exist:
msg = "No such file or directory: '%s'" % self.abspath
raise SCons.Errors.UserError(msg)
else:
self.__class__ = File
self._morph()
self.clear()
return self
def rfile(self):
"""We're a generic Entry, but the caller is actually looking for
a File at this point, so morph into one."""
self.__class__ = File
self._morph()
self.clear()
return File.rfile(self)
def scanner_key(self):
return self.get_suffix()
def get_contents(self):
"""Fetch the contents of the entry. Returns the exact binary
contents of the file."""
try:
self = self.disambiguate(must_exist=1)
except SCons.Errors.UserError:
# There was nothing on disk with which to disambiguate
# this entry. Leave it as an Entry, but return a null
# string so calls to get_contents() in emitters and the
# like (e.g. in qt.py) don't have to disambiguate by hand
# or catch the exception.
return ''
else:
return self.get_contents()
def get_text_contents(self):
"""Fetch the decoded text contents of a Unicode encoded Entry.
Since this should return the text contents from the file
system, we check to see into what sort of subclass we should
morph this Entry."""
try:
self = self.disambiguate(must_exist=1)
except SCons.Errors.UserError:
# There was nothing on disk with which to disambiguate
# this entry. Leave it as an Entry, but return a null
# string so calls to get_text_contents() in emitters and
# the like (e.g. in qt.py) don't have to disambiguate by
# hand or catch the exception.
return ''
else:
return self.get_text_contents()
def must_be_same(self, klass):
"""Called to make sure a Node is a Dir. Since we're an
Entry, we can morph into one."""
if self.__class__ is not klass:
self.__class__ = klass
self._morph()
self.clear()
# The following methods can get called before the Taskmaster has
# had a chance to call disambiguate() directly to see if this Entry
# should really be a Dir or a File. We therefore use these to call
# disambiguate() transparently (from our caller's point of view).
#
# Right now, this minimal set of methods has been derived by just
# looking at some of the methods that will obviously be called early
# in any of the various Taskmasters' calling sequences, and then
# empirically figuring out which additional methods are necessary
# to make various tests pass.
def exists(self):
"""Return if the Entry exists. Check the file system to see
what we should turn into first. Assume a file if there's no
directory."""
return self.disambiguate().exists()
def rel_path(self, other):
d = self.disambiguate()
if d.__class__ is Entry:
raise Exception("rel_path() could not disambiguate File/Dir")
return d.rel_path(other)
def new_ninfo(self):
return self.disambiguate().new_ninfo()
def changed_since_last_build(self, target, prev_ni):
return self.disambiguate().changed_since_last_build(target, prev_ni)
def _glob1(self, pattern, ondisk=True, source=False, strings=False):
return self.disambiguate()._glob1(pattern, ondisk, source, strings)
def get_subst_proxy(self):
return self.disambiguate().get_subst_proxy()
# This is for later so we can differentiate between Entry the class and Entry
# the method of the FS class.
_classEntry = Entry
class LocalFS(object):
if SCons.Memoize.use_memoizer:
__metaclass__ = SCons.Memoize.Memoized_Metaclass
# This class implements an abstraction layer for operations involving
# a local file system. Essentially, this wraps any function in
# the os, os.path or shutil modules that we use to actually go do
# anything with or to the local file system.
#
# Note that there's a very good chance we'll refactor this part of
# the architecture in some way as we really implement the interface(s)
# for remote file system Nodes. For example, the right architecture
# might be to have this be a subclass instead of a base class.
# Nevertheless, we're using this as a first step in that direction.
#
# We're not using chdir() yet because the calling subclass method
# needs to use os.chdir() directly to avoid recursion. Will we
# really need this one?
#def chdir(self, path):
# return os.chdir(path)
def chmod(self, path, mode):
return os.chmod(path, mode)
def copy(self, src, dst):
return shutil.copy(src, dst)
def copy2(self, src, dst):
return shutil.copy2(src, dst)
def exists(self, path):
return os.path.exists(path)
def getmtime(self, path):
return os.path.getmtime(path)
def getsize(self, path):
return os.path.getsize(path)
def isdir(self, path):
return os.path.isdir(path)
def isfile(self, path):
return os.path.isfile(path)
def link(self, src, dst):
return os.link(src, dst)
def lstat(self, path):
return os.lstat(path)
def listdir(self, path):
return os.listdir(path)
def makedirs(self, path):
return os.makedirs(path)
def mkdir(self, path):
return os.mkdir(path)
def rename(self, old, new):
return os.rename(old, new)
def stat(self, path):
return os.stat(path)
def symlink(self, src, dst):
return os.symlink(src, dst)
def open(self, path):
return open(path)
def unlink(self, path):
return os.unlink(path)
if hasattr(os, 'symlink'):
def islink(self, path):
return os.path.islink(path)
else:
def islink(self, path):
return 0 # no symlinks
if hasattr(os, 'readlink'):
def readlink(self, file):
return os.readlink(file)
else:
def readlink(self, file):
return ''
#class RemoteFS:
# # Skeleton for the obvious methods we might need from the
# # abstraction layer for a remote filesystem.
# def upload(self, local_src, remote_dst):
# pass
# def download(self, remote_src, local_dst):
# pass
class FS(LocalFS):
memoizer_counters = []
def __init__(self, path = None):
"""Initialize the Node.FS subsystem.
The supplied path is the top of the source tree, where we
expect to find the top-level build file. If no path is
supplied, the current directory is the default.
The path argument must be a valid absolute path.
"""
if __debug__: logInstanceCreation(self, 'Node.FS')
self._memo = {}
self.Root = {}
self.SConstruct_dir = None
self.max_drift = default_max_drift
self.Top = None
if path is None:
self.pathTop = os.getcwd()
else:
self.pathTop = path
self.defaultDrive = _my_normcase(_my_splitdrive(self.pathTop)[0])
self.Top = self.Dir(self.pathTop)
self.Top.path = '.'
self.Top.tpath = '.'
self._cwd = self.Top
DirNodeInfo.fs = self
FileNodeInfo.fs = self
def set_SConstruct_dir(self, dir):
self.SConstruct_dir = dir
def get_max_drift(self):
return self.max_drift
def set_max_drift(self, max_drift):
self.max_drift = max_drift
def getcwd(self):
if hasattr(self, "_cwd"):
return self._cwd
else:
return "<no cwd>"
def chdir(self, dir, change_os_dir=0):
"""Change the current working directory for lookups.
If change_os_dir is true, we will also change the "real" cwd
to match.
"""
curr=self._cwd
try:
if dir is not None:
self._cwd = dir
if change_os_dir:
os.chdir(dir.abspath)
except OSError:
self._cwd = curr
raise
def get_root(self, drive):
"""
Returns the root directory for the specified drive, creating
it if necessary.
"""
drive = _my_normcase(drive)
try:
return self.Root[drive]
except KeyError:
root = RootDir(drive, self)
self.Root[drive] = root
if not drive:
self.Root[self.defaultDrive] = root
elif drive == self.defaultDrive:
self.Root[''] = root
return root
def _lookup(self, p, directory, fsclass, create=1):
"""
The generic entry point for Node lookup with user-supplied data.
This translates arbitrary input into a canonical Node.FS object
of the specified fsclass. The general approach for strings is
to turn it into a fully normalized absolute path and then call
the root directory's lookup_abs() method for the heavy lifting.
If the path name begins with '#', it is unconditionally
interpreted relative to the top-level directory of this FS. '#'
is treated as a synonym for the top-level SConstruct directory,
much like '~' is treated as a synonym for the user's home
directory in a UNIX shell. So both '#foo' and '#/foo' refer
to the 'foo' subdirectory underneath the top-level SConstruct
directory.
If the path name is relative, then the path is looked up relative
to the specified directory, or the current directory (self._cwd,
typically the SConscript directory) if the specified directory
is None.
"""
if isinstance(p, Base):
# It's already a Node.FS object. Make sure it's the right
# class and return.
p.must_be_same(fsclass)
return p
# str(p) in case it's something like a proxy object
p = str(p)
if not os_sep_is_slash:
p = p.replace(OS_SEP, '/')
if p[0:1] == '#':
# There was an initial '#', so we strip it and override
# whatever directory they may have specified with the
# top-level SConstruct directory.
p = p[1:]
directory = self.Top
# There might be a drive letter following the
# '#'. Although it is not described in the SCons man page,
# the regression test suite explicitly tests for that
# syntax. It seems to mean the following thing:
#
# Assuming the the SCons top dir is in C:/xxx/yyy,
# '#X:/toto' means X:/xxx/yyy/toto.
#
# i.e. it assumes that the X: drive has a directory
# structure similar to the one found on drive C:.
if do_splitdrive:
drive, p = _my_splitdrive(p)
if drive:
root = self.get_root(drive)
else:
root = directory.root
else:
root = directory.root
# We can only strip trailing after splitting the drive
# since the drive might the UNC '//' prefix.
p = p.strip('/')
needs_normpath = needs_normpath_match(p)
# The path is relative to the top-level SCons directory.
if p in ('', '.'):
p = directory.labspath
else:
p = directory.labspath + '/' + p
else:
if do_splitdrive:
drive, p = _my_splitdrive(p)
if drive and not p:
# This causes a naked drive letter to be treated
# as a synonym for the root directory on that
# drive.
p = '/'
else:
drive = ''
# We can only strip trailing '/' since the drive might the
# UNC '//' prefix.
if p != '/':
p = p.rstrip('/')
needs_normpath = needs_normpath_match(p)
if p[0:1] == '/':
# Absolute path
root = self.get_root(drive)
else:
# This is a relative lookup or to the current directory
# (the path name is not absolute). Add the string to the
# appropriate directory lookup path, after which the whole
# thing gets normalized.
if directory:
if not isinstance(directory, Dir):
directory = self.Dir(directory)
else:
directory = self._cwd
if p in ('', '.'):
p = directory.labspath
else:
p = directory.labspath + '/' + p
if drive:
root = self.get_root(drive)
else:
root = directory.root
if needs_normpath is not None:
# Normalize a pathname. Will return the same result for
# equivalent paths.
#
# We take advantage of the fact that we have an absolute
# path here for sure. In addition, we know that the
# components of lookup path are separated by slashes at
# this point. Because of this, this code is about 2X
# faster than calling os.path.normpath() followed by
# replacing os.sep with '/' again.
ins = p.split('/')[1:]
outs = []
for d in ins:
if d == '..':
try:
outs.pop()
except IndexError:
pass
elif d not in ('', '.'):
outs.append(d)
p = '/' + '/'.join(outs)
return root._lookup_abs(p, fsclass, create)
def Entry(self, name, directory = None, create = 1):
"""Look up or create a generic Entry node with the specified name.
If the name is a relative path (begins with ./, ../, or a file
name), then it is looked up relative to the supplied directory
node, or to the top level directory of the FS (supplied at
construction time) if no directory is supplied.
"""
return self._lookup(name, directory, Entry, create)
def File(self, name, directory = None, create = 1):
"""Look up or create a File node with the specified name. If
the name is a relative path (begins with ./, ../, or a file name),
then it is looked up relative to the supplied directory node,
or to the top level directory of the FS (supplied at construction
time) if no directory is supplied.
This method will raise TypeError if a directory is found at the
specified path.
"""
return self._lookup(name, directory, File, create)
def Dir(self, name, directory = None, create = True):
"""Look up or create a Dir node with the specified name. If
the name is a relative path (begins with ./, ../, or a file name),
then it is looked up relative to the supplied directory node,
or to the top level directory of the FS (supplied at construction
time) if no directory is supplied.
This method will raise TypeError if a normal file is found at the
specified path.
"""
return self._lookup(name, directory, Dir, create)
def VariantDir(self, variant_dir, src_dir, duplicate=1):
"""Link the supplied variant directory to the source directory
for purposes of building files."""
if not isinstance(src_dir, SCons.Node.Node):
src_dir = self.Dir(src_dir)
if not isinstance(variant_dir, SCons.Node.Node):
variant_dir = self.Dir(variant_dir)
if src_dir.is_under(variant_dir):
raise SCons.Errors.UserError("Source directory cannot be under variant directory.")
if variant_dir.srcdir:
if variant_dir.srcdir == src_dir:
return # We already did this.
raise SCons.Errors.UserError("'%s' already has a source directory: '%s'."%(variant_dir, variant_dir.srcdir))
variant_dir.link(src_dir, duplicate)
def Repository(self, *dirs):
"""Specify Repository directories to search."""
for d in dirs:
if not isinstance(d, SCons.Node.Node):
d = self.Dir(d)
self.Top.addRepository(d)
def variant_dir_target_climb(self, orig, dir, tail):
"""Create targets in corresponding variant directories
Climb the directory tree, and look up path names
relative to any linked variant directories we find.
Even though this loops and walks up the tree, we don't memoize
the return value because this is really only used to process
the command-line targets.
"""
targets = []
message = None
fmt = "building associated VariantDir targets: %s"
start_dir = dir
while dir:
for bd in dir.variant_dirs:
if start_dir.is_under(bd):
# If already in the build-dir location, don't reflect
return [orig], fmt % str(orig)
p = os.path.join(bd.path, *tail)
targets.append(self.Entry(p))
tail = [dir.name] + tail
dir = dir.up()
if targets:
message = fmt % ' '.join(map(str, targets))
return targets, message
def Glob(self, pathname, ondisk=True, source=True, strings=False, cwd=None):
"""
Globs
This is mainly a shim layer
"""
if cwd is None:
cwd = self.getcwd()
return cwd.glob(pathname, ondisk, source, strings)
class DirNodeInfo(SCons.Node.NodeInfoBase):
# This should get reset by the FS initialization.
current_version_id = 1
fs = None
def str_to_node(self, s):
top = self.fs.Top
root = top.root
if do_splitdrive:
drive, s = _my_splitdrive(s)
if drive:
root = self.fs.get_root(drive)
if not os.path.isabs(s):
s = top.labspath + '/' + s
return root._lookup_abs(s, Entry)
class DirBuildInfo(SCons.Node.BuildInfoBase):
current_version_id = 1
glob_magic_check = re.compile('[*?[]')
def has_glob_magic(s):
return glob_magic_check.search(s) is not None
class Dir(Base):
"""A class for directories in a file system.
"""
memoizer_counters = []
NodeInfo = DirNodeInfo
BuildInfo = DirBuildInfo
def __init__(self, name, directory, fs):
if __debug__: logInstanceCreation(self, 'Node.FS.Dir')
Base.__init__(self, name, directory, fs)
self._morph()
def _morph(self):
"""Turn a file system Node (either a freshly initialized directory
object or a separate Entry object) into a proper directory object.
Set up this directory's entries and hook it into the file
system tree. Specify that directories (this Node) don't use
signatures for calculating whether they're current.
"""
self.repositories = []
self.srcdir = None
self.entries = {}
self.entries['.'] = self
self.entries['..'] = self.dir
self.cwd = self
self.searched = 0
self._sconsign = None
self.variant_dirs = []
self.root = self.dir.root
# For directories, we make a difference between the directory
# 'name' and the directory 'dirname'. The 'name' attribute is
# used when we need to print the 'name' of the directory or
# when we it is used as the last part of a path. The 'dirname'
# is used when the directory is not the last element of the
# path. The main reason for making that distinction is that
# for RoorDir's the dirname can not be easily inferred from
# the name. For example, we have to add a '/' after a drive
# letter but not after a UNC path prefix ('//').
self.dirname = self.name + OS_SEP
# Don't just reset the executor, replace its action list,
# because it might have some pre-or post-actions that need to
# be preserved.
#
# But don't reset the executor if there is a non-null executor
# attached already. The existing executor might have other
# targets, in which case replacing the action list with a
# Mkdir action is a big mistake.
if not hasattr(self, 'executor'):
self.builder = get_MkdirBuilder()
self.get_executor().set_action_list(self.builder.action)
else:
# Prepend MkdirBuilder action to existing action list
l = self.get_executor().action_list
a = get_MkdirBuilder().action
l.insert(0, a)
self.get_executor().set_action_list(l)
def diskcheck_match(self):
diskcheck_match(self, self.isfile,
"File %s found where directory expected.")
def __clearRepositoryCache(self, duplicate=None):
"""Called when we change the repository(ies) for a directory.
This clears any cached information that is invalidated by changing
the repository."""
for node in self.entries.values():
if node != self.dir:
if node != self and isinstance(node, Dir):
node.__clearRepositoryCache(duplicate)
else:
node.clear()
try:
del node._srcreps
except AttributeError:
pass
if duplicate is not None:
node.duplicate=duplicate
def __resetDuplicate(self, node):
if node != self:
node.duplicate = node.get_dir().duplicate
def Entry(self, name):
"""
Looks up or creates an entry node named 'name' relative to
this directory.
"""
return self.fs.Entry(name, self)
def Dir(self, name, create=True):
"""
Looks up or creates a directory node named 'name' relative to
this directory.
"""
return self.fs.Dir(name, self, create)
def File(self, name):
"""
Looks up or creates a file node named 'name' relative to
this directory.
"""
return self.fs.File(name, self)
def link(self, srcdir, duplicate):
"""Set this directory as the variant directory for the
supplied source directory."""
self.srcdir = srcdir
self.duplicate = duplicate
self.__clearRepositoryCache(duplicate)
srcdir.variant_dirs.append(self)
def getRepositories(self):
"""Returns a list of repositories for this directory.
"""
if self.srcdir and not self.duplicate:
return self.srcdir.get_all_rdirs() + self.repositories
return self.repositories
memoizer_counters.append(SCons.Memoize.CountValue('get_all_rdirs'))
def get_all_rdirs(self):
try:
return list(self._memo['get_all_rdirs'])
except KeyError:
pass
result = [self]
fname = '.'
dir = self
while dir:
for rep in dir.getRepositories():
result.append(rep.Dir(fname))
if fname == '.':
fname = dir.name
else:
fname = dir.name + OS_SEP + fname
dir = dir.up()
self._memo['get_all_rdirs'] = list(result)
return result
def addRepository(self, dir):
if dir != self and not dir in self.repositories:
self.repositories.append(dir)
dir.tpath = '.'
self.__clearRepositoryCache()
def up(self):
return self.dir
def _rel_path_key(self, other):
return str(other)
memoizer_counters.append(SCons.Memoize.CountDict('rel_path', _rel_path_key))
def rel_path(self, other):
"""Return a path to "other" relative to this directory.
"""
# This complicated and expensive method, which constructs relative
# paths between arbitrary Node.FS objects, is no longer used
# by SCons itself. It was introduced to store dependency paths
# in .sconsign files relative to the target, but that ended up
# being significantly inefficient.
#
# We're continuing to support the method because some SConstruct
# files out there started using it when it was available, and
# we're all about backwards compatibility..
try:
memo_dict = self._memo['rel_path']
except KeyError:
memo_dict = {}
self._memo['rel_path'] = memo_dict
else:
try:
return memo_dict[other]
except KeyError:
pass
if self is other:
result = '.'
elif not other in self.path_elements:
try:
other_dir = other.get_dir()
except AttributeError:
result = str(other)
else:
if other_dir is None:
result = other.name
else:
dir_rel_path = self.rel_path(other_dir)
if dir_rel_path == '.':
result = other.name
else:
result = dir_rel_path + OS_SEP + other.name
else:
i = self.path_elements.index(other) + 1
path_elems = ['..'] * (len(self.path_elements) - i) \
+ [n.name for n in other.path_elements[i:]]
result = OS_SEP.join(path_elems)
memo_dict[other] = result
return result
def get_env_scanner(self, env, kw={}):
import SCons.Defaults
return SCons.Defaults.DirEntryScanner
def get_target_scanner(self):
import SCons.Defaults
return SCons.Defaults.DirEntryScanner
def get_found_includes(self, env, scanner, path):
"""Return this directory's implicit dependencies.
We don't bother caching the results because the scan typically
shouldn't be requested more than once (as opposed to scanning
.h file contents, which can be requested as many times as the
files is #included by other files).
"""
if not scanner:
return []
# Clear cached info for this Dir. If we already visited this
# directory on our walk down the tree (because we didn't know at
# that point it was being used as the source for another Node)
# then we may have calculated build signature before realizing
# we had to scan the disk. Now that we have to, though, we need
# to invalidate the old calculated signature so that any node
# dependent on our directory structure gets one that includes
# info about everything on disk.
self.clear()
return scanner(self, env, path)
#
# Taskmaster interface subsystem
#
def prepare(self):
pass
def build(self, **kw):
"""A null "builder" for directories."""
global MkdirBuilder
if self.builder is not MkdirBuilder:
SCons.Node.Node.build(self, **kw)
#
#
#
def _create(self):
"""Create this directory, silently and without worrying about
whether the builder is the default or not."""
listDirs = []
parent = self
while parent:
if parent.exists():
break
listDirs.append(parent)
p = parent.up()
if p is None:
# Don't use while: - else: for this condition because
# if so, then parent is None and has no .path attribute.
raise SCons.Errors.StopError(parent.path)
parent = p
listDirs.reverse()
for dirnode in listDirs:
try:
# Don't call dirnode.build(), call the base Node method
# directly because we definitely *must* create this
# directory. The dirnode.build() method will suppress
# the build if it's the default builder.
SCons.Node.Node.build(dirnode)
dirnode.get_executor().nullify()
# The build() action may or may not have actually
# created the directory, depending on whether the -n
# option was used or not. Delete the _exists and
# _rexists attributes so they can be reevaluated.
dirnode.clear()
except OSError:
pass
def multiple_side_effect_has_builder(self):
global MkdirBuilder
return self.builder is not MkdirBuilder and self.has_builder()
def alter_targets(self):
"""Return any corresponding targets in a variant directory.
"""
return self.fs.variant_dir_target_climb(self, self, [])
def scanner_key(self):
"""A directory does not get scanned."""
return None
def get_text_contents(self):
"""We already emit things in text, so just return the binary
version."""
return self.get_contents()
def get_contents(self):
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
for node in sorted(self.children(), key=lambda t: t.name):
contents.append('%s %s\n' % (node.get_csig(), node.name))
return ''.join(contents)
def get_csig(self):
"""Compute the content signature for Directory nodes. In
general, this is not needed and the content signature is not
stored in the DirNodeInfo. However, if get_contents on a Dir
node is called which has a child directory, the child
directory should return the hash of its contents."""
contents = self.get_contents()
return SCons.Util.MD5signature(contents)
def do_duplicate(self, src):
pass
changed_since_last_build = SCons.Node.Node.state_has_changed
def is_up_to_date(self):
"""If any child is not up-to-date, then this directory isn't,
either."""
if self.builder is not MkdirBuilder and not self.exists():
return 0
up_to_date = SCons.Node.up_to_date
for kid in self.children():
if kid.get_state() > up_to_date:
return 0
return 1
def rdir(self):
if not self.exists():
norm_name = _my_normcase(self.name)
for dir in self.dir.get_all_rdirs():
try: node = dir.entries[norm_name]
except KeyError: node = dir.dir_on_disk(self.name)
if node and node.exists() and \
(isinstance(dir, Dir) or isinstance(dir, Entry)):
return node
return self
def sconsign(self):
"""Return the .sconsign file info for this directory,
creating it first if necessary."""
if not self._sconsign:
import SCons.SConsign
self._sconsign = SCons.SConsign.ForDirectory(self)
return self._sconsign
def srcnode(self):
"""Dir has a special need for srcnode()...if we
have a srcdir attribute set, then that *is* our srcnode."""
if self.srcdir:
return self.srcdir
return Base.srcnode(self)
def get_timestamp(self):
"""Return the latest timestamp from among our children"""
stamp = 0
for kid in self.children():
if kid.get_timestamp() > stamp:
stamp = kid.get_timestamp()
return stamp
def entry_abspath(self, name):
return self.abspath + OS_SEP + name
def entry_labspath(self, name):
return self.labspath + '/' + name
def entry_path(self, name):
return self.path + OS_SEP + name
def entry_tpath(self, name):
return self.tpath + OS_SEP + name
def entry_exists_on_disk(self, name):
try:
d = self.on_disk_entries
except AttributeError:
d = {}
try:
entries = os.listdir(self.abspath)
except OSError:
pass
else:
for entry in map(_my_normcase, entries):
d[entry] = True
self.on_disk_entries = d
if sys.platform == 'win32':
name = _my_normcase(name)
result = d.get(name)
if result is None:
# Belt-and-suspenders for Windows: check directly for
# 8.3 file names that don't show up in os.listdir().
result = os.path.exists(self.abspath + OS_SEP + name)
d[name] = result
return result
else:
return name in d
memoizer_counters.append(SCons.Memoize.CountValue('srcdir_list'))
def srcdir_list(self):
try:
return self._memo['srcdir_list']
except KeyError:
pass
result = []
dirname = '.'
dir = self
while dir:
if dir.srcdir:
result.append(dir.srcdir.Dir(dirname))
dirname = dir.name + OS_SEP + dirname
dir = dir.up()
self._memo['srcdir_list'] = result
return result
def srcdir_duplicate(self, name):
for dir in self.srcdir_list():
if self.is_under(dir):
# We shouldn't source from something in the build path;
# variant_dir is probably under src_dir, in which case
# we are reflecting.
break
if dir.entry_exists_on_disk(name):
srcnode = dir.Entry(name).disambiguate()
if self.duplicate:
node = self.Entry(name).disambiguate()
node.do_duplicate(srcnode)
return node
else:
return srcnode
return None
def _srcdir_find_file_key(self, filename):
return filename
memoizer_counters.append(SCons.Memoize.CountDict('srcdir_find_file', _srcdir_find_file_key))
def srcdir_find_file(self, filename):
try:
memo_dict = self._memo['srcdir_find_file']
except KeyError:
memo_dict = {}
self._memo['srcdir_find_file'] = memo_dict
else:
try:
return memo_dict[filename]
except KeyError:
pass
def func(node):
if (isinstance(node, File) or isinstance(node, Entry)) and \
(node.is_derived() or node.exists()):
return node
return None
norm_name = _my_normcase(filename)
for rdir in self.get_all_rdirs():
try: node = rdir.entries[norm_name]
except KeyError: node = rdir.file_on_disk(filename)
else: node = func(node)
if node:
result = (node, self)
memo_dict[filename] = result
return result
for srcdir in self.srcdir_list():
for rdir in srcdir.get_all_rdirs():
try: node = rdir.entries[norm_name]
except KeyError: node = rdir.file_on_disk(filename)
else: node = func(node)
if node:
result = (File(filename, self, self.fs), srcdir)
memo_dict[filename] = result
return result
result = (None, None)
memo_dict[filename] = result
return result
def dir_on_disk(self, name):
if self.entry_exists_on_disk(name):
try: return self.Dir(name)
except TypeError: pass
node = self.srcdir_duplicate(name)
if isinstance(node, File):
return None
return node
def file_on_disk(self, name):
if self.entry_exists_on_disk(name) or \
diskcheck_rcs(self, name) or \
diskcheck_sccs(self, name):
try: return self.File(name)
except TypeError: pass
node = self.srcdir_duplicate(name)
if isinstance(node, Dir):
return None
return node
def walk(self, func, arg):
"""
Walk this directory tree by calling the specified function
for each directory in the tree.
This behaves like the os.path.walk() function, but for in-memory
Node.FS.Dir objects. The function takes the same arguments as
the functions passed to os.path.walk():
func(arg, dirname, fnames)
Except that "dirname" will actually be the directory *Node*,
not the string. The '.' and '..' entries are excluded from
fnames. The fnames list may be modified in-place to filter the
subdirectories visited or otherwise impose a specific order.
The "arg" argument is always passed to func() and may be used
in any way (or ignored, passing None is common).
"""
entries = self.entries
names = list(entries.keys())
names.remove('.')
names.remove('..')
func(arg, self, names)
for dirname in [n for n in names if isinstance(entries[n], Dir)]:
entries[dirname].walk(func, arg)
def glob(self, pathname, ondisk=True, source=False, strings=False):
"""
Returns a list of Nodes (or strings) matching a specified
pathname pattern.
Pathname patterns follow UNIX shell semantics: * matches
any-length strings of any characters, ? matches any character,
and [] can enclose lists or ranges of characters. Matches do
not span directory separators.
The matches take into account Repositories, returning local
Nodes if a corresponding entry exists in a Repository (either
an in-memory Node or something on disk).
By defafult, the glob() function matches entries that exist
on-disk, in addition to in-memory Nodes. Setting the "ondisk"
argument to False (or some other non-true value) causes the glob()
function to only match in-memory Nodes. The default behavior is
to return both the on-disk and in-memory Nodes.
The "source" argument, when true, specifies that corresponding
source Nodes must be returned if you're globbing in a build
directory (initialized with VariantDir()). The default behavior
is to return Nodes local to the VariantDir().
The "strings" argument, when true, returns the matches as strings,
not Nodes. The strings are path names relative to this directory.
The underlying algorithm is adapted from the glob.glob() function
in the Python library (but heavily modified), and uses fnmatch()
under the covers.
"""
dirname, basename = os.path.split(pathname)
if not dirname:
return sorted(self._glob1(basename, ondisk, source, strings),
key=lambda t: str(t))
if has_glob_magic(dirname):
list = self.glob(dirname, ondisk, source, strings=False)
else:
list = [self.Dir(dirname, create=True)]
result = []
for dir in list:
r = dir._glob1(basename, ondisk, source, strings)
if strings:
r = [os.path.join(str(dir), x) for x in r]
result.extend(r)
return sorted(result, key=lambda a: str(a))
def _glob1(self, pattern, ondisk=True, source=False, strings=False):
"""
Globs for and returns a list of entry names matching a single
pattern in this directory.
This searches any repositories and source directories for
corresponding entries and returns a Node (or string) relative
to the current directory if an entry is found anywhere.
TODO: handle pattern with no wildcard
"""
search_dir_list = self.get_all_rdirs()
for srcdir in self.srcdir_list():
search_dir_list.extend(srcdir.get_all_rdirs())
selfEntry = self.Entry
names = []
for dir in search_dir_list:
# We use the .name attribute from the Node because the keys of
# the dir.entries dictionary are normalized (that is, all upper
# case) on case-insensitive systems like Windows.
node_names = [ v.name for k, v in dir.entries.items()
if k not in ('.', '..') ]
names.extend(node_names)
if not strings:
# Make sure the working directory (self) actually has
# entries for all Nodes in repositories or variant dirs.
for name in node_names: selfEntry(name)
if ondisk:
try:
disk_names = os.listdir(dir.abspath)
except os.error:
continue
names.extend(disk_names)
if not strings:
# We're going to return corresponding Nodes in
# the local directory, so we need to make sure
# those Nodes exist. We only want to create
# Nodes for the entries that will match the
# specified pattern, though, which means we
# need to filter the list here, even though
# the overall list will also be filtered later,
# after we exit this loop.
if pattern[0] != '.':
#disk_names = [ d for d in disk_names if d[0] != '.' ]
disk_names = [x for x in disk_names if x[0] != '.']
disk_names = fnmatch.filter(disk_names, pattern)
dirEntry = dir.Entry
for name in disk_names:
# Add './' before disk filename so that '#' at
# beginning of filename isn't interpreted.
name = './' + name
node = dirEntry(name).disambiguate()
n = selfEntry(name)
if n.__class__ != node.__class__:
n.__class__ = node.__class__
n._morph()
names = set(names)
if pattern[0] != '.':
#names = [ n for n in names if n[0] != '.' ]
names = [x for x in names if x[0] != '.']
names = fnmatch.filter(names, pattern)
if strings:
return names
#return [ self.entries[_my_normcase(n)] for n in names ]
return [self.entries[_my_normcase(n)] for n in names]
class RootDir(Dir):
"""A class for the root directory of a file system.
This is the same as a Dir class, except that the path separator
('/' or '\\') is actually part of the name, so we don't need to
add a separator when creating the path names of entries within
this directory.
"""
def __init__(self, drive, fs):
if __debug__: logInstanceCreation(self, 'Node.FS.RootDir')
# We're going to be our own parent directory (".." entry and .dir
# attribute) so we have to set up some values so Base.__init__()
# won't gag won't it calls some of our methods.
self.abspath = ''
self.labspath = ''
self.path = ''
self.tpath = ''
self.path_elements = []
self.duplicate = 0
self.root = self
# Handle all the types of drives:
if drive == '':
# No drive, regular UNIX root or Windows default drive.
name = OS_SEP
dirname = OS_SEP
elif drive == '//':
# UNC path
name = UNC_PREFIX
dirname = UNC_PREFIX
else:
# Windows drive letter
name = drive
dirname = drive + OS_SEP
Base.__init__(self, name, self, fs)
# Now set our paths to what we really want them to be. The
# name should already contain any necessary separators, such
# as the initial drive letter (the name) plus the directory
# separator, except for the "lookup abspath," which does not
# have the drive letter.
self.abspath = dirname
self.labspath = ''
self.path = dirname
self.tpath = dirname
self._morph()
# Must be reset after Dir._morph() is invoked...
self.dirname = dirname
self._lookupDict = {}
self._lookupDict[''] = self
self._lookupDict['/'] = self
# The // entry is necessary because os.path.normpath()
# preserves double slashes at the beginning of a path on Posix
# platforms.
if not has_unc:
self._lookupDict['//'] = self
def must_be_same(self, klass):
if klass is Dir:
return
Base.must_be_same(self, klass)
def _lookup_abs(self, p, klass, create=1):
"""
Fast (?) lookup of a *normalized* absolute path.
This method is intended for use by internal lookups with
already-normalized path data. For general-purpose lookups,
use the FS.Entry(), FS.Dir() or FS.File() methods.
The caller is responsible for making sure we're passed a
normalized absolute path; we merely let Python's dictionary look
up and return the One True Node.FS object for the path.
If a Node for the specified "p" doesn't already exist, and
"create" is specified, the Node may be created after recursive
invocation to find or create the parent directory or directories.
"""
k = _my_normcase(p)
try:
result = self._lookupDict[k]
except KeyError:
if not create:
msg = "No such file or directory: '%s' in '%s' (and create is False)" % (p, str(self))
raise SCons.Errors.UserError(msg)
# There is no Node for this path name, and we're allowed
# to create it.
# (note: would like to use p.rsplit('/',1) here but
# that's not in python 2.3)
# e.g.: dir_name, file_name = p.rsplit('/',1)
last_slash = p.rindex('/')
if (last_slash >= 0):
dir_name = p[:last_slash]
file_name = p[last_slash+1:]
else:
dir_name = p # shouldn't happen, just in case
file_name = ''
dir_node = self._lookup_abs(dir_name, Dir)
result = klass(file_name, dir_node, self.fs)
# Double-check on disk (as configured) that the Node we
# created matches whatever is out there in the real world.
result.diskcheck_match()
self._lookupDict[k] = result
dir_node.entries[_my_normcase(file_name)] = result
dir_node.implicit = None
else:
# There is already a Node for this path name. Allow it to
# complain if we were looking for an inappropriate type.
result.must_be_same(klass)
return result
def __str__(self):
return self.abspath
def entry_abspath(self, name):
return self.abspath + name
def entry_labspath(self, name):
return '/' + name
def entry_path(self, name):
return self.path + name
def entry_tpath(self, name):
return self.tpath + name
def is_under(self, dir):
if self is dir:
return 1
else:
return 0
def up(self):
return None
def get_dir(self):
return None
def src_builder(self):
return _null
class FileNodeInfo(SCons.Node.NodeInfoBase):
current_version_id = 1
field_list = ['csig', 'timestamp', 'size']
# This should get reset by the FS initialization.
fs = None
def str_to_node(self, s):
top = self.fs.Top
root = top.root
if do_splitdrive:
drive, s = _my_splitdrive(s)
if drive:
root = self.fs.get_root(drive)
if not os.path.isabs(s):
s = top.labspath + '/' + s
return root._lookup_abs(s, Entry)
class FileBuildInfo(SCons.Node.BuildInfoBase):
current_version_id = 1
def convert_to_sconsign(self):
"""
Converts this FileBuildInfo object for writing to a .sconsign file
This replaces each Node in our various dependency lists with its
usual string representation: relative to the top-level SConstruct
directory, or an absolute path if it's outside.
"""
if os_sep_is_slash:
node_to_str = str
else:
def node_to_str(n):
try:
s = n.path
except AttributeError:
s = str(n)
else:
s = s.replace(OS_SEP, '/')
return s
for attr in ['bsources', 'bdepends', 'bimplicit']:
try:
val = getattr(self, attr)
except AttributeError:
pass
else:
setattr(self, attr, list(map(node_to_str, val)))
def convert_from_sconsign(self, dir, name):
"""
Converts a newly-read FileBuildInfo object for in-SCons use
For normal up-to-date checking, we don't have any conversion to
perform--but we're leaving this method here to make that clear.
"""
pass
def prepare_dependencies(self):
"""
Prepares a FileBuildInfo object for explaining what changed
The bsources, bdepends and bimplicit lists have all been
stored on disk as paths relative to the top-level SConstruct
directory. Convert the strings to actual Nodes (for use by the
--debug=explain code and --implicit-cache).
"""
attrs = [
('bsources', 'bsourcesigs'),
('bdepends', 'bdependsigs'),
('bimplicit', 'bimplicitsigs'),
]
for (nattr, sattr) in attrs:
try:
strings = getattr(self, nattr)
nodeinfos = getattr(self, sattr)
except AttributeError:
continue
nodes = []
for s, ni in zip(strings, nodeinfos):
if not isinstance(s, SCons.Node.Node):
s = ni.str_to_node(s)
nodes.append(s)
setattr(self, nattr, nodes)
def format(self, names=0):
result = []
bkids = self.bsources + self.bdepends + self.bimplicit
bkidsigs = self.bsourcesigs + self.bdependsigs + self.bimplicitsigs
for bkid, bkidsig in zip(bkids, bkidsigs):
result.append(str(bkid) + ': ' +
' '.join(bkidsig.format(names=names)))
result.append('%s [%s]' % (self.bactsig, self.bact))
return '\n'.join(result)
class File(Base):
"""A class for files in a file system.
"""
memoizer_counters = []
NodeInfo = FileNodeInfo
BuildInfo = FileBuildInfo
md5_chunksize = 64
def diskcheck_match(self):
diskcheck_match(self, self.isdir,
"Directory %s found where file expected.")
def __init__(self, name, directory, fs):
if __debug__: logInstanceCreation(self, 'Node.FS.File')
Base.__init__(self, name, directory, fs)
self._morph()
def Entry(self, name):
"""Create an entry node named 'name' relative to
the directory of this file."""
return self.dir.Entry(name)
def Dir(self, name, create=True):
"""Create a directory node named 'name' relative to
the directory of this file."""
return self.dir.Dir(name, create=create)
def Dirs(self, pathlist):
"""Create a list of directories relative to the SConscript
directory of this file."""
return [self.Dir(p) for p in pathlist]
def File(self, name):
"""Create a file node named 'name' relative to
the directory of this file."""
return self.dir.File(name)
#def generate_build_dict(self):
# """Return an appropriate dictionary of values for building
# this File."""
# return {'Dir' : self.Dir,
# 'File' : self.File,
# 'RDirs' : self.RDirs}
def _morph(self):
"""Turn a file system node into a File object."""
self.scanner_paths = {}
if not hasattr(self, '_local'):
self._local = 0
# If there was already a Builder set on this entry, then
# we need to make sure we call the target-decider function,
# not the source-decider. Reaching in and doing this by hand
# is a little bogus. We'd prefer to handle this by adding
# an Entry.builder_set() method that disambiguates like the
# other methods, but that starts running into problems with the
# fragile way we initialize Dir Nodes with their Mkdir builders,
# yet still allow them to be overridden by the user. Since it's
# not clear right now how to fix that, stick with what works
# until it becomes clear...
if self.has_builder():
self.changed_since_last_build = self.decide_target
def scanner_key(self):
return self.get_suffix()
def get_contents(self):
if not self.rexists():
return ''
fname = self.rfile().abspath
try:
contents = open(fname, "rb").read()
except EnvironmentError, e:
if not e.filename:
e.filename = fname
raise
return contents
# This attempts to figure out what the encoding of the text is
# based upon the BOM bytes, and then decodes the contents so that
# it's a valid python string.
def get_text_contents(self):
contents = self.get_contents()
# The behavior of various decode() methods and functions
# w.r.t. the initial BOM bytes is different for different
# encodings and/or Python versions. ('utf-8' does not strip
# them, but has a 'utf-8-sig' which does; 'utf-16' seems to
# strip them; etc.) Just sidestep all the complication by
# explicitly stripping the BOM before we decode().
if contents.startswith(codecs.BOM_UTF8):
return contents[len(codecs.BOM_UTF8):].decode('utf-8')
if contents.startswith(codecs.BOM_UTF16_LE):
return contents[len(codecs.BOM_UTF16_LE):].decode('utf-16-le')
if contents.startswith(codecs.BOM_UTF16_BE):
return contents[len(codecs.BOM_UTF16_BE):].decode('utf-16-be')
return contents
def get_content_hash(self):
"""
Compute and return the MD5 hash for this file.
"""
if not self.rexists():
return SCons.Util.MD5signature('')
fname = self.rfile().abspath
try:
cs = SCons.Util.MD5filesignature(fname,
chunksize=SCons.Node.FS.File.md5_chunksize*1024)
except EnvironmentError, e:
if not e.filename:
e.filename = fname
raise
return cs
memoizer_counters.append(SCons.Memoize.CountValue('get_size'))
def get_size(self):
try:
return self._memo['get_size']
except KeyError:
pass
if self.rexists():
size = self.rfile().getsize()
else:
size = 0
self._memo['get_size'] = size
return size
memoizer_counters.append(SCons.Memoize.CountValue('get_timestamp'))
def get_timestamp(self):
try:
return self._memo['get_timestamp']
except KeyError:
pass
if self.rexists():
timestamp = self.rfile().getmtime()
else:
timestamp = 0
self._memo['get_timestamp'] = timestamp
return timestamp
def store_info(self):
# Merge our build information into the already-stored entry.
# This accomodates "chained builds" where a file that's a target
# in one build (SConstruct file) is a source in a different build.
# See test/chained-build.py for the use case.
if do_store_info:
self.dir.sconsign().store_info(self.name, self)
convert_copy_attrs = [
'bsources',
'bimplicit',
'bdepends',
'bact',
'bactsig',
'ninfo',
]
convert_sig_attrs = [
'bsourcesigs',
'bimplicitsigs',
'bdependsigs',
]
def convert_old_entry(self, old_entry):
# Convert a .sconsign entry from before the Big Signature
# Refactoring, doing what we can to convert its information
# to the new .sconsign entry format.
#
# The old format looked essentially like this:
#
# BuildInfo
# .ninfo (NodeInfo)
# .bsig
# .csig
# .timestamp
# .size
# .bsources
# .bsourcesigs ("signature" list)
# .bdepends
# .bdependsigs ("signature" list)
# .bimplicit
# .bimplicitsigs ("signature" list)
# .bact
# .bactsig
#
# The new format looks like this:
#
# .ninfo (NodeInfo)
# .bsig
# .csig
# .timestamp
# .size
# .binfo (BuildInfo)
# .bsources
# .bsourcesigs (NodeInfo list)
# .bsig
# .csig
# .timestamp
# .size
# .bdepends
# .bdependsigs (NodeInfo list)
# .bsig
# .csig
# .timestamp
# .size
# .bimplicit
# .bimplicitsigs (NodeInfo list)
# .bsig
# .csig
# .timestamp
# .size
# .bact
# .bactsig
#
# The basic idea of the new structure is that a NodeInfo always
# holds all available information about the state of a given Node
# at a certain point in time. The various .b*sigs lists can just
# be a list of pointers to the .ninfo attributes of the different
# dependent nodes, without any copying of information until it's
# time to pickle it for writing out to a .sconsign file.
#
# The complicating issue is that the *old* format only stored one
# "signature" per dependency, based on however the *last* build
# was configured. We don't know from just looking at it whether
# it was a build signature, a content signature, or a timestamp
# "signature". Since we no longer use build signatures, the
# best we can do is look at the length and if it's thirty two,
# assume that it was (or might have been) a content signature.
# If it was actually a build signature, then it will cause a
# rebuild anyway when it doesn't match the new content signature,
# but that's probably the best we can do.
import SCons.SConsign
new_entry = SCons.SConsign.SConsignEntry()
new_entry.binfo = self.new_binfo()
binfo = new_entry.binfo
for attr in self.convert_copy_attrs:
try:
value = getattr(old_entry, attr)
except AttributeError:
continue
setattr(binfo, attr, value)
delattr(old_entry, attr)
for attr in self.convert_sig_attrs:
try:
sig_list = getattr(old_entry, attr)
except AttributeError:
continue
value = []
for sig in sig_list:
ninfo = self.new_ninfo()
if len(sig) == 32:
ninfo.csig = sig
else:
ninfo.timestamp = sig
value.append(ninfo)
setattr(binfo, attr, value)
delattr(old_entry, attr)
return new_entry
memoizer_counters.append(SCons.Memoize.CountValue('get_stored_info'))
def get_stored_info(self):
try:
return self._memo['get_stored_info']
except KeyError:
pass
try:
sconsign_entry = self.dir.sconsign().get_entry(self.name)
except (KeyError, EnvironmentError):
import SCons.SConsign
sconsign_entry = SCons.SConsign.SConsignEntry()
sconsign_entry.binfo = self.new_binfo()
sconsign_entry.ninfo = self.new_ninfo()
else:
if isinstance(sconsign_entry, FileBuildInfo):
# This is a .sconsign file from before the Big Signature
# Refactoring; convert it as best we can.
sconsign_entry = self.convert_old_entry(sconsign_entry)
try:
delattr(sconsign_entry.ninfo, 'bsig')
except AttributeError:
pass
self._memo['get_stored_info'] = sconsign_entry
return sconsign_entry
def get_stored_implicit(self):
binfo = self.get_stored_info().binfo
binfo.prepare_dependencies()
try: return binfo.bimplicit
except AttributeError: return None
def rel_path(self, other):
return self.dir.rel_path(other)
def _get_found_includes_key(self, env, scanner, path):
return (id(env), id(scanner), path)
memoizer_counters.append(SCons.Memoize.CountDict('get_found_includes', _get_found_includes_key))
def get_found_includes(self, env, scanner, path):
"""Return the included implicit dependencies in this file.
Cache results so we only scan the file once per path
regardless of how many times this information is requested.
"""
memo_key = (id(env), id(scanner), path)
try:
memo_dict = self._memo['get_found_includes']
except KeyError:
memo_dict = {}
self._memo['get_found_includes'] = memo_dict
else:
try:
return memo_dict[memo_key]
except KeyError:
pass
if scanner:
# result = [n.disambiguate() for n in scanner(self, env, path)]
result = scanner(self, env, path)
result = [N.disambiguate() for N in result]
else:
result = []
memo_dict[memo_key] = result
return result
def _createDir(self):
# ensure that the directories for this node are
# created.
self.dir._create()
def push_to_cache(self):
"""Try to push the node into a cache
"""
# This should get called before the Nodes' .built() method is
# called, which would clear the build signature if the file has
# a source scanner.
#
# We have to clear the local memoized values *before* we push
# the node to cache so that the memoization of the self.exists()
# return value doesn't interfere.
if self.nocache:
return
self.clear_memoized_values()
if self.exists():
self.get_build_env().get_CacheDir().push(self)
def retrieve_from_cache(self):
"""Try to retrieve the node's content from a cache
This method is called from multiple threads in a parallel build,
so only do thread safe stuff here. Do thread unsafe stuff in
built().
Returns true if the node was successfully retrieved.
"""
if self.nocache:
return None
if not self.is_derived():
return None
return self.get_build_env().get_CacheDir().retrieve(self)
def visited(self):
if self.exists():
self.get_build_env().get_CacheDir().push_if_forced(self)
ninfo = self.get_ninfo()
csig = self.get_max_drift_csig()
if csig:
ninfo.csig = csig
ninfo.timestamp = self.get_timestamp()
ninfo.size = self.get_size()
if not self.has_builder():
# This is a source file, but it might have been a target file
# in another build that included more of the DAG. Copy
# any build information that's stored in the .sconsign file
# into our binfo object so it doesn't get lost.
old = self.get_stored_info()
self.get_binfo().__dict__.update(old.binfo.__dict__)
self.store_info()
def find_src_builder(self):
if self.rexists():
return None
scb = self.dir.src_builder()
if scb is _null:
if diskcheck_sccs(self.dir, self.name):
scb = get_DefaultSCCSBuilder()
elif diskcheck_rcs(self.dir, self.name):
scb = get_DefaultRCSBuilder()
else:
scb = None
if scb is not None:
try:
b = self.builder
except AttributeError:
b = None
if b is None:
self.builder_set(scb)
return scb
def has_src_builder(self):
"""Return whether this Node has a source builder or not.
If this Node doesn't have an explicit source code builder, this
is where we figure out, on the fly, if there's a transparent
source code builder for it.
Note that if we found a source builder, we also set the
self.builder attribute, so that all of the methods that actually
*build* this file don't have to do anything different.
"""
try:
scb = self.sbuilder
except AttributeError:
scb = self.sbuilder = self.find_src_builder()
return scb is not None
def alter_targets(self):
"""Return any corresponding targets in a variant directory.
"""
if self.is_derived():
return [], None
return self.fs.variant_dir_target_climb(self, self.dir, [self.name])
def _rmv_existing(self):
self.clear_memoized_values()
if print_duplicate:
print "dup: removing existing target %s"%self
e = Unlink(self, [], None)
if isinstance(e, SCons.Errors.BuildError):
raise e
#
# Taskmaster interface subsystem
#
def make_ready(self):
self.has_src_builder()
self.get_binfo()
def prepare(self):
"""Prepare for this file to be created."""
SCons.Node.Node.prepare(self)
if self.get_state() != SCons.Node.up_to_date:
if self.exists():
if self.is_derived() and not self.precious:
self._rmv_existing()
else:
try:
self._createDir()
except SCons.Errors.StopError, drive:
desc = "No drive `%s' for target `%s'." % (drive, self)
raise SCons.Errors.StopError(desc)
#
#
#
def remove(self):
"""Remove this file."""
if self.exists() or self.islink():
self.fs.unlink(self.path)
return 1
return None
def do_duplicate(self, src):
self._createDir()
if print_duplicate:
print "dup: relinking variant '%s' from '%s'"%(self, src)
Unlink(self, None, None)
e = Link(self, src, None)
if isinstance(e, SCons.Errors.BuildError):
desc = "Cannot duplicate `%s' in `%s': %s." % (src.path, self.dir.path, e.errstr)
raise SCons.Errors.StopError(desc)
self.linked = 1
# The Link() action may or may not have actually
# created the file, depending on whether the -n
# option was used or not. Delete the _exists and
# _rexists attributes so they can be reevaluated.
self.clear()
memoizer_counters.append(SCons.Memoize.CountValue('exists'))
def exists(self):
try:
return self._memo['exists']
except KeyError:
pass
# Duplicate from source path if we are set up to do this.
if self.duplicate and not self.is_derived() and not self.linked:
src = self.srcnode()
if src is not self:
# At this point, src is meant to be copied in a variant directory.
src = src.rfile()
if src.abspath != self.abspath:
if src.exists():
self.do_duplicate(src)
# Can't return 1 here because the duplication might
# not actually occur if the -n option is being used.
else:
# The source file does not exist. Make sure no old
# copy remains in the variant directory.
if print_duplicate:
print "dup: no src for %s, unlinking old variant copy"%self
if Base.exists(self) or self.islink():
self.fs.unlink(self.path)
# Return None explicitly because the Base.exists() call
# above will have cached its value if the file existed.
self._memo['exists'] = None
return None
result = Base.exists(self)
self._memo['exists'] = result
return result
#
# SIGNATURE SUBSYSTEM
#
def get_max_drift_csig(self):
"""
Returns the content signature currently stored for this node
if it's been unmodified longer than the max_drift value, or the
max_drift value is 0. Returns None otherwise.
"""
old = self.get_stored_info()
mtime = self.get_timestamp()
max_drift = self.fs.max_drift
if max_drift > 0:
if (time.time() - mtime) > max_drift:
try:
n = old.ninfo
if n.timestamp and n.csig and n.timestamp == mtime:
return n.csig
except AttributeError:
pass
elif max_drift == 0:
try:
return old.ninfo.csig
except AttributeError:
pass
return None
def get_csig(self):
"""
Generate a node's content signature, the digested signature
of its content.
node - the node
cache - alternate node to use for the signature cache
returns - the content signature
"""
ninfo = self.get_ninfo()
try:
return ninfo.csig
except AttributeError:
pass
csig = self.get_max_drift_csig()
if csig is None:
try:
if self.get_size() < SCons.Node.FS.File.md5_chunksize:
contents = self.get_contents()
else:
csig = self.get_content_hash()
except IOError:
# This can happen if there's actually a directory on-disk,
# which can be the case if they've disabled disk checks,
# or if an action with a File target actually happens to
# create a same-named directory by mistake.
csig = ''
else:
if not csig:
csig = SCons.Util.MD5signature(contents)
ninfo.csig = csig
return csig
#
# DECISION SUBSYSTEM
#
def builder_set(self, builder):
SCons.Node.Node.builder_set(self, builder)
self.changed_since_last_build = self.decide_target
def changed_content(self, target, prev_ni):
cur_csig = self.get_csig()
try:
return cur_csig != prev_ni.csig
except AttributeError:
return 1
def changed_state(self, target, prev_ni):
return self.state != SCons.Node.up_to_date
def changed_timestamp_then_content(self, target, prev_ni):
if not self.changed_timestamp_match(target, prev_ni):
try:
self.get_ninfo().csig = prev_ni.csig
except AttributeError:
pass
return False
return self.changed_content(target, prev_ni)
def changed_timestamp_newer(self, target, prev_ni):
try:
return self.get_timestamp() > target.get_timestamp()
except AttributeError:
return 1
def changed_timestamp_match(self, target, prev_ni):
try:
return self.get_timestamp() != prev_ni.timestamp
except AttributeError:
return 1
def decide_source(self, target, prev_ni):
return target.get_build_env().decide_source(self, target, prev_ni)
def decide_target(self, target, prev_ni):
return target.get_build_env().decide_target(self, target, prev_ni)
# Initialize this Node's decider function to decide_source() because
# every file is a source file until it has a Builder attached...
changed_since_last_build = decide_source
def is_up_to_date(self):
T = 0
if T: Trace('is_up_to_date(%s):' % self)
if not self.exists():
if T: Trace(' not self.exists():')
# The file doesn't exist locally...
r = self.rfile()
if r != self:
# ...but there is one in a Repository...
if not self.changed(r):
if T: Trace(' changed(%s):' % r)
# ...and it's even up-to-date...
if self._local:
# ...and they'd like a local copy.
e = LocalCopy(self, r, None)
if isinstance(e, SCons.Errors.BuildError):
raise
self.store_info()
if T: Trace(' 1\n')
return 1
self.changed()
if T: Trace(' None\n')
return None
else:
r = self.changed()
if T: Trace(' self.exists(): %s\n' % r)
return not r
memoizer_counters.append(SCons.Memoize.CountValue('rfile'))
def rfile(self):
try:
return self._memo['rfile']
except KeyError:
pass
result = self
if not self.exists():
norm_name = _my_normcase(self.name)
for dir in self.dir.get_all_rdirs():
try: node = dir.entries[norm_name]
except KeyError: node = dir.file_on_disk(self.name)
if node and node.exists() and \
(isinstance(node, File) or isinstance(node, Entry) \
or not node.is_derived()):
result = node
# Copy over our local attributes to the repository
# Node so we identify shared object files in the
# repository and don't assume they're static.
#
# This isn't perfect; the attribute would ideally
# be attached to the object in the repository in
# case it was built statically in the repository
# and we changed it to shared locally, but that's
# rarely the case and would only occur if you
# intentionally used the same suffix for both
# shared and static objects anyway. So this
# should work well in practice.
result.attributes = self.attributes
break
self._memo['rfile'] = result
return result
def rstr(self):
return str(self.rfile())
def get_cachedir_csig(self):
"""
Fetch a Node's content signature for purposes of computing
another Node's cachesig.
This is a wrapper around the normal get_csig() method that handles
the somewhat obscure case of using CacheDir with the -n option.
Any files that don't exist would normally be "built" by fetching
them from the cache, but the normal get_csig() method will try
to open up the local file, which doesn't exist because the -n
option meant we didn't actually pull the file from cachedir.
But since the file *does* actually exist in the cachedir, we
can use its contents for the csig.
"""
try:
return self.cachedir_csig
except AttributeError:
pass
cachedir, cachefile = self.get_build_env().get_CacheDir().cachepath(self)
if not self.exists() and cachefile and os.path.exists(cachefile):
self.cachedir_csig = SCons.Util.MD5filesignature(cachefile, \
SCons.Node.FS.File.md5_chunksize * 1024)
else:
self.cachedir_csig = self.get_csig()
return self.cachedir_csig
def get_cachedir_bsig(self):
try:
return self.cachesig
except AttributeError:
pass
# Add the path to the cache signature, because multiple
# targets built by the same action will all have the same
# build signature, and we have to differentiate them somehow.
children = self.children()
executor = self.get_executor()
# sigs = [n.get_cachedir_csig() for n in children]
sigs = [n.get_cachedir_csig() for n in children]
sigs.append(SCons.Util.MD5signature(executor.get_contents()))
sigs.append(self.path)
result = self.cachesig = SCons.Util.MD5collect(sigs)
return result
default_fs = None
def get_default_fs():
global default_fs
if not default_fs:
default_fs = FS()
return default_fs
class FileFinder(object):
"""
"""
if SCons.Memoize.use_memoizer:
__metaclass__ = SCons.Memoize.Memoized_Metaclass
memoizer_counters = []
def __init__(self):
self._memo = {}
def filedir_lookup(self, p, fd=None):
"""
A helper method for find_file() that looks up a directory for
a file we're trying to find. This only creates the Dir Node if
it exists on-disk, since if the directory doesn't exist we know
we won't find any files in it... :-)
It would be more compact to just use this as a nested function
with a default keyword argument (see the commented-out version
below), but that doesn't work unless you have nested scopes,
so we define it here just so this work under Python 1.5.2.
"""
if fd is None:
fd = self.default_filedir
dir, name = os.path.split(fd)
drive, d = _my_splitdrive(dir)
if not name and d[:1] in ('/', OS_SEP):
#return p.fs.get_root(drive).dir_on_disk(name)
return p.fs.get_root(drive)
if dir:
p = self.filedir_lookup(p, dir)
if not p:
return None
norm_name = _my_normcase(name)
try:
node = p.entries[norm_name]
except KeyError:
return p.dir_on_disk(name)
if isinstance(node, Dir):
return node
if isinstance(node, Entry):
node.must_be_same(Dir)
return node
return None
def _find_file_key(self, filename, paths, verbose=None):
return (filename, paths)
memoizer_counters.append(SCons.Memoize.CountDict('find_file', _find_file_key))
def find_file(self, filename, paths, verbose=None):
"""
find_file(str, [Dir()]) -> [nodes]
filename - a filename to find
paths - a list of directory path *nodes* to search in. Can be
represented as a list, a tuple, or a callable that is
called with no arguments and returns the list or tuple.
returns - the node created from the found file.
Find a node corresponding to either a derived file or a file
that exists already.
Only the first file found is returned, and none is returned
if no file is found.
"""
memo_key = self._find_file_key(filename, paths)
try:
memo_dict = self._memo['find_file']
except KeyError:
memo_dict = {}
self._memo['find_file'] = memo_dict
else:
try:
return memo_dict[memo_key]
except KeyError:
pass
if verbose and not callable(verbose):
if not SCons.Util.is_String(verbose):
verbose = "find_file"
_verbose = u' %s: ' % verbose
verbose = lambda s: sys.stdout.write(_verbose + s)
filedir, filename = os.path.split(filename)
if filedir:
# More compact code that we can't use until we drop
# support for Python 1.5.2:
#
#def filedir_lookup(p, fd=filedir):
# """
# A helper function that looks up a directory for a file
# we're trying to find. This only creates the Dir Node
# if it exists on-disk, since if the directory doesn't
# exist we know we won't find any files in it... :-)
# """
# dir, name = os.path.split(fd)
# if dir:
# p = filedir_lookup(p, dir)
# if not p:
# return None
# norm_name = _my_normcase(name)
# try:
# node = p.entries[norm_name]
# except KeyError:
# return p.dir_on_disk(name)
# if isinstance(node, Dir):
# return node
# if isinstance(node, Entry):
# node.must_be_same(Dir)
# return node
# if isinstance(node, Dir) or isinstance(node, Entry):
# return node
# return None
#paths = [_f for _f in map(filedir_lookup, paths) if _f]
self.default_filedir = filedir
paths = [_f for _f in map(self.filedir_lookup, paths) if _f]
result = None
for dir in paths:
if verbose:
verbose("looking for '%s' in '%s' ...\n" % (filename, dir))
node, d = dir.srcdir_find_file(filename)
if node:
if verbose:
verbose("... FOUND '%s' in '%s'\n" % (filename, d))
result = node
break
memo_dict[memo_key] = result
return result
find_file = FileFinder().find_file
def invalidate_node_memos(targets):
"""
Invalidate the memoized values of all Nodes (files or directories)
that are associated with the given entries. Has been added to
clear the cache of nodes affected by a direct execution of an
action (e.g. Delete/Copy/Chmod). Existing Node caches become
inconsistent if the action is run through Execute(). The argument
`targets` can be a single Node object or filename, or a sequence
of Nodes/filenames.
"""
from traceback import extract_stack
# First check if the cache really needs to be flushed. Only
# actions run in the SConscript with Execute() seem to be
# affected. XXX The way to check if Execute() is in the stacktrace
# is a very dirty hack and should be replaced by a more sensible
# solution.
for f in extract_stack():
if f[2] == 'Execute' and f[0][-14:] == 'Environment.py':
break
else:
# Dont have to invalidate, so return
return
if not SCons.Util.is_List(targets):
targets = [targets]
for entry in targets:
# If the target is a Node object, clear the cache. If it is a
# filename, look up potentially existing Node object first.
try:
entry.clear_memoized_values()
except AttributeError:
# Not a Node object, try to look up Node by filename. XXX
# This creates Node objects even for those filenames which
# do not correspond to an existing Node object.
node = get_default_fs().Entry(entry)
if node:
node.clear_memoized_values()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| {
"content_hash": "ae4d6f7966da80e2224a389d1cd7e11b",
"timestamp": "",
"source": "github",
"line_count": 3302,
"max_line_length": 120,
"avg_line_length": 35.42761962447002,
"alnum_prop": 0.5665999897420116,
"repo_name": "renhaoqi/gem5-stable",
"id": "3f3cf2870c1fcebc94e8728202a1e80b355a474f",
"size": "116982",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "scons-local-2.2.0/SCons/Node/FS.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "239800"
},
{
"name": "Batchfile",
"bytes": "208"
},
{
"name": "C",
"bytes": "1003474"
},
{
"name": "C++",
"bytes": "14592024"
},
{
"name": "CMake",
"bytes": "2202"
},
{
"name": "Emacs Lisp",
"bytes": "1969"
},
{
"name": "Groff",
"bytes": "8777"
},
{
"name": "HTML",
"bytes": "136695"
},
{
"name": "Java",
"bytes": "3096"
},
{
"name": "M4",
"bytes": "49620"
},
{
"name": "Makefile",
"bytes": "27783"
},
{
"name": "Perl",
"bytes": "33602"
},
{
"name": "Protocol Buffer",
"bytes": "7033"
},
{
"name": "Python",
"bytes": "5738537"
},
{
"name": "Shell",
"bytes": "49333"
},
{
"name": "Visual Basic",
"bytes": "2884"
}
],
"symlink_target": ""
} |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class Operations(object):
"""Operations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An objec model deserializer.
:ivar api_version: Version of the API to be used with the client request. The current version is 2015-10-01. Constant value: "2015-10-01".
"""
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2015-10-01"
self.config = config
def list(
self, custom_headers=None, raw=False, **operation_config):
"""Lists all of the available Media Services REST API operations.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: :class:`OperationListResult
<azure.mgmt.media.models.OperationListResult>` or
:class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if
raw=true
:rtype: :class:`OperationListResult
<azure.mgmt.media.models.OperationListResult>` or
:class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = '/providers/Microsoft.Media/operations'
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationListResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
| {
"content_hash": "a7748a6b8b08f0b29cb4022308a3c2e4",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 142,
"avg_line_length": 39.475,
"alnum_prop": 0.6652944901836605,
"repo_name": "AutorestCI/azure-sdk-for-python",
"id": "4103715cdf91f542667cfc5918ed978194b98df6",
"size": "3632",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "azure-mgmt-media/azure/mgmt/media/operations/operations.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "34619070"
}
],
"symlink_target": ""
} |
import cPickle as pickle
import nose
import angr
import ana
import os
import tempfile
internaltest_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
internaltest_files = [ 'argc_decide', 'argc_symbol', 'argv_test', 'counter', 'fauxware', 'fauxware.idb', 'manysum', 'pw', 'strlen', 'test_arrays', 'test_division', 'test_loops' ]
internaltest_arch = [ 'i386', 'armel' ]
def internaltest_vfg(p, cfg):
state = tempfile.TemporaryFile()
vfg = p.analyses.VFG(cfg=cfg)
pickle.dump(vfg, state, -1)
state.seek(0)
vfg2 = pickle.load(state)
nose.tools.assert_equals(vfg.final_states, vfg2.final_states)
nose.tools.assert_equals(set(vfg.graph.nodes()), set(vfg2.graph.nodes()))
def internaltest_cfg(p):
state = tempfile.TemporaryFile()
cfg = p.analyses.CFGAccurate()
pickle.dump(cfg, state, -1)
state.seek(0)
cfg2 = pickle.load(state)
nose.tools.assert_equals(set(cfg.nodes()), set(cfg2.nodes()))
nose.tools.assert_equals(cfg.unresolvables, cfg2.unresolvables)
nose.tools.assert_set_equal(set(cfg.deadends), set(cfg2.deadends))
return cfg
def internaltest_cfgfast(p):
state = tempfile.TemporaryFile()
cfg = p.analyses.CFGFast()
# generate capstone blocks
main_function = cfg.functions.function(name='main')
for b in main_function.blocks:
c = b.capstone # pylint:disable=unused-variable
pickle.dump(cfg, state, -1)
state.seek(0)
cfg2 = pickle.load(state)
nose.tools.assert_equals(set(cfg.nodes()), set(cfg2.nodes()))
def internaltest_project(p):
state = tempfile.TemporaryFile()
pickle.dump(p, state, -1)
state.seek(0)
loaded_p = pickle.load(state)
nose.tools.assert_equals(p.arch, loaded_p.arch)
nose.tools.assert_equals(p.filename, loaded_p.filename)
nose.tools.assert_equals(p.entry, loaded_p.entry)
def setup():
ana.set_dl(ana.DirDataLayer('/tmp/ana'))
def teardown():
ana.set_dl(ana.SimpleDataLayer())
@nose.with_setup(setup, teardown)
def test_serialization():
for d in internaltest_arch:
for f in internaltest_files:
fpath = os.path.join(internaltest_location, d,f)
if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
p = angr.Project(fpath)
internaltest_project(p)
p = angr.Project(os.path.join(internaltest_location, 'i386/fauxware'), load_options={'auto_load_libs': False})
internaltest_cfgfast(p)
cfg = internaltest_cfg(p)
internaltest_vfg(p, cfg)
if __name__ == '__main__':
test_serialization()
| {
"content_hash": "c2d12eb99a6b03fff5092b8e28c34a98",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 178,
"avg_line_length": 30.928571428571427,
"alnum_prop": 0.6678214010777521,
"repo_name": "f-prettyland/angr",
"id": "9db288fbc3585bfd9c2035f66fcb18af550f4aa9",
"size": "2598",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "tests/test_serialization.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "6375"
},
{
"name": "C++",
"bytes": "39375"
},
{
"name": "Makefile",
"bytes": "557"
},
{
"name": "Python",
"bytes": "2934645"
}
],
"symlink_target": ""
} |
from __future__ import print_function
import sys
import os
import netCDF4 as nc
import numpy as np
import shlex
import subprocess as sp
class TestGridGeneration():
def __init__(self):
self.test_dir = os.path.dirname(os.path.realpath(__file__))
self.input_dir = os.path.join(self.test_dir, 'inputs')
self.output_dir = os.path.join(self.test_dir, 'outputs')
def run_script(self, script, args):
"""
Run the given script with args.
"""
cmd = [os.path.join(self.test_dir, '../', script)] + args
ret = sp.call(cmd)
return ret
def make_grids(self):
input_grid = os.path.join(self.input_dir, 'ocean_hgrid.nc')
input_mask = os.path.join(self.input_dir, 'ocean_mask.nc')
um_restart = os.path.join(self.input_dir, 'restart_dump.astart')
args = [input_grid, input_mask, um_restart, '--output_dir',
self.output_dir]
ret = self.run_script('make_grids.py', args)
return ret
def test_make_grids(self):
"""
Test script makes grids.
"""
outputs = ['kmt.nc', 'grid.nc', 'lfrac.nc', 'qrparm.mask.nc',
'restart_dump.astart', 'areas.nc', 'grids.nc', 'masks.nc']
outputs = [os.path.join(self.output_dir, o) for o in outputs]
for f in outputs:
if os.path.exists(f):
os.remove(f)
ret = self.make_grids()
assert(ret == 0)
# Check that outputs exist.
for f in outputs:
assert(os.path.exists(f))
def test_compare_against_old(self):
"""
Compare some generated OASIS fields against pre-made ones.
"""
ret = self.make_grids()
assert(ret == 0)
# Masks
masks = os.path.join(self.output_dir, 'masks.nc')
masks_old = os.path.join(self.input_dir, 'masks_old.nc')
with nc.Dataset(masks) as f_new:
with nc.Dataset(masks_old) as f_old:
for f in ['cice.msk']:
assert(np.array_equal(f_new.variables[f][:],
f_old.variables[f][:]))
for f in ['um1t.msk', 'um1u.msk', 'um1v.msk']:
ratio = (float(np.sum(f_new.variables[f][:])) /
float(np.sum(f_old.variables[f][:])))
assert(abs(1 - ratio) < 0.02)
# Grids
grids = os.path.join(self.output_dir, 'grids.nc')
grids_old = os.path.join(self.input_dir, 'grids_old.nc')
with nc.Dataset(grids) as f_new:
with nc.Dataset(grids_old) as f_old:
for f in ['um1t.lon', 'um1t.lat', 'um1u.lon', 'um1u.lat',
'um1v.lon', 'um1v.lat',
'cice.lon', 'cice.lat', 'cice.clo', 'cice.cla',
'um1t.clo', 'um1t.cla', 'um1u.clo', 'um1u.cla',
'um1v.clo', 'um1v.cla']:
assert(np.array_equal(f_new.variables[f][:],
f_old.variables[f][:]))
# Areas
areas = os.path.join(self.output_dir, 'areas.nc')
areas_old = os.path.join(self.input_dir, 'areas_old.nc')
with nc.Dataset(areas) as f_new:
with nc.Dataset(areas_old) as f_old:
# These variables are significantly different between old and
# new. FIXME: find out why. Perhaps this is related to FIXME
# below. The new ones are closer to the real answers.
# for f in ['um1t.srf', 'um1u.srf', 'um1v.srf']:
for f in ['cice.srf']:
assert(np.array_equal(f_new.variables[f][:],
f_old.variables[f][:]))
def test_same_area(self):
"""
Test that source and destination grids cover the same area.
"""
pass
#src_area = np.copy(src.variables['tarea'])
#dest_area = np.copy(dest.variables['tarea'])
# This is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal)
#assert_almost_equal(np.sum(src_area), np.sum(dest_area[:]), decimal=-1)
def test_overlapping(self):
"""
Test that each destination (ocean) cell is covered by one or more
unmasked source (atm) cells.
We start by doing this with T-cells only. Eventually do it with all.
"""
def find_index_of_bounding_cell(lat, lon, src_clat, src_clon):
"""
Find the index of the box (defined by src_clat, src_clon) that
contains the point (lat, lon).
"""
i = None
j = None
# Do lat.
top_lat = src_clat[3, :, 0]
bot_lat = src_clat[0, :, 0]
for idx, (top, bot) in enumerate(zip(top_lat, bot_lat)):
if lat >= bot and lat <= top:
i = idx
break
# Do lon.
left_lon = src_clon[0, 0, :]
right_lon = src_clon[1, 0, :]
lon = (lon + 360) % 360
for idx, (left, right) in enumerate(zip(left_lon, right_lon)):
if lon >= left and lon <= right:
j = idx
break
else:
# If spot not found then see if it fits in the first cell. This
# is to deal with the periodic domain.
left = (left_lon[0] + 360)
right = (right_lon[0] + 360)
if lon >= left and lon <= right:
j = 0
assert((i is not None) and (j is not None))
return i, j
with nc.Dataset(os.path.join(self.output_dir, 'masks.nc')) as f:
src_mask = np.copy(f.variables['um1t.msk'])
dest_mask = np.copy(f.variables['cice.msk'])
with nc.Dataset(os.path.join(self.output_dir, 'grids.nc')) as f:
dest_lat = np.copy(f.variables['cice.lat'])
dest_lon = np.copy(f.variables['cice.lon'])
src_clat = np.copy(f.variables['um1t.cla'])
src_clon = np.copy(f.variables['um1t.clo'])
# Iterate over all ocean points. Is it unmasked? If yes get it's lat
# lon. Using the atm corners find the atm grid cell that this ocean
# point falls within. Check that the atm cell is unmasked.
unmasked = np.where(dest_mask == 0)
for lat, lon in zip(dest_lat[unmasked], dest_lon[unmasked]):
i, j = find_index_of_bounding_cell(lat, lon, src_clat, src_clon)
assert(src_mask[i, j] == 0)
| {
"content_hash": "4e85cc1afdfee373e2f371021f12784f",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 80,
"avg_line_length": 34.682291666666664,
"alnum_prop": 0.5066826850878511,
"repo_name": "CWSL/access-cm-tools",
"id": "8633424ef77084c8e3921242b73180776bdea489",
"size": "6660",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "grid/tests/test_grids.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2513"
},
{
"name": "Python",
"bytes": "239564"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
import json
import uuid
from StringIO import StringIO
from mock import patch, Mock, call
from tests import TestCase, logged_in
from nose.tools import eq_
from catsnap import Client
from catsnap.table.image import Image, ImageContents
from catsnap.table.album import Album
from catsnap.image_truck import TryHTTPError
from catsnap.worker.tasks import process_image
class TestAdd(TestCase):
def test_adding_requires_login(self):
response = self.app.post('/add', data={})
eq_(response.status_code, 302, response.data)
eq_(response.headers['Location'], 'http://localhost/')
@logged_in
def test_get_the_add_page(self):
response = self.app.get('/add')
eq_(response.status_code, 200)
@logged_in
@patch('catsnap.web.controllers.image.delay')
@patch('catsnap.web.controllers.image.ImageTruck')
def test_upload_an_image(self, ImageTruck, delay):
truck = Mock()
ImageTruck.new_from_stream.return_value = truck
truck.filename = 'CA7'
truck.url.return_value = 'ess three'
truck.contents = b''
truck.content_type = "image/jpeg"
session = Client().session()
album = Album(name='11:11 Eleven Eleven')
session.add(album)
session.flush()
response = self.app.post('/add', data={
'url': '',
'album_id': album.album_id,
'file': (StringIO(str('booya')), 'img.jpg')})
image = session.query(Image).one()
eq_(image.filename, 'CA7')
eq_(image.source_url, '')
eq_(image.album_id, album.album_id)
eq_(response.status_code, 302, response.data)
eq_(response.headers['Location'],
'http://localhost/image/{0}'.format(image.image_id))
contents = session.query(ImageContents).one()
eq_(image.image_id, contents.image_id)
delay.assert_called_with(
[], process_image, contents.image_contents_id)
@logged_in
@patch('catsnap.web.controllers.image.delay')
@patch('catsnap.web.controllers.image.ImageTruck')
def test_upload_an_image_twice(self, ImageTruck, delay):
truck = Mock()
ImageTruck.new_from_stream.return_value = truck
truck.filename = 'CA7'
truck.url.return_value = 'ess three'
truck.contents = b''
truck.content_type = "image/jpeg"
response = self.app.post('/add', data={
'url': '',
'file': (StringIO(str('booya')), 'img.jpg')})
eq_(response.status_code, 302)
response = self.app.post('/add', data={
'url': '',
'file': (StringIO(str('booya')), 'img.jpg')})
eq_(response.status_code, 302)
session = Client().session()
image = session.query(Image).one()
contentses = session.query(ImageContents).all()
for contents in contentses:
eq_(contents.image_id, image.image_id)
contents_calls = [call([], process_image, x.image_contents_id)
for x in contentses]
delay.assert_has_calls(contents_calls)
@logged_in
@patch('catsnap.web.controllers.image.delay')
@patch('catsnap.web.controllers.image.ImageTruck')
def test_upload_an_image_with_json_format(self, ImageTruck, delay):
truck = Mock()
ImageTruck.new_from_url.return_value = truck
truck.filename = 'CA741C'
truck.url.return_value = 'cloudfrunt.nut/CA741C'
truck.contents = b''
truck.content_type = "image/gif"
task_id = str(uuid.uuid4())
delay.return_value = task_id
response = self.app.post('/add.json', data={
'album': '',
'url': 'imgur.com/cool_cat.gif'})
eq_(response.status_code, 200, response.data)
session = Client().session()
image = session.query(Image).one()
body = json.loads(response.data)
eq_(body,
[{
'url': 'cloudfrunt.nut/CA741C',
'image_id': image.image_id,
'task_id': task_id,
}])
contents = session.query(ImageContents).one()
eq_(contents.image_id, image.image_id)
delay.assert_called_with([],
process_image,
contents.image_contents_id)
@logged_in
@patch('catsnap.web.controllers.image.delay')
@patch('catsnap.web.controllers.image.ImageTruck')
def test_upload_several_images_in_one_go(self, ImageTruck, delay):
(truck1, truck2, truck3) = (Mock(), Mock(), Mock())
truck1.filename = 'BAD1DEA'
truck1.url.return_value = 'cloudfrunt.nut/BAD1DEA'
truck1.contents = b'boom'
truck1.content_type = "image/jpeg"
truck2.filename = 'CAFEBABE'
truck2.url.return_value = 'cloudfrunt.nut/CAFEBABE'
truck2.contents = b'shaka'
truck2.content_type = "image/jpeg"
truck3.filename = 'DADD1E'
truck3.url.return_value = 'cloudfrunt.nut/DADD1E'
truck3.contents = b'laka'
truck3.content_type = "image/jpeg"
ImageTruck.new_from_stream.side_effect = [truck1, truck2, truck3]
id1 = str(uuid.uuid4())
id2 = str(uuid.uuid4())
id3 = str(uuid.uuid4())
delay.side_effect = [id1, id2, id3]
response = self.app.post('/add.json', data={
'album': '',
'url': '',
'file[]': [
(StringIO(str('boom')), 'image_1.jpg'),
(StringIO(str('shaka')), 'image_2.jpg'),
(StringIO(str('laka')), 'image_3.jpg'),
]})
eq_(response.status_code, 200, response.data)
session = Client().session()
images = session.query(Image).all()
body = json.loads(response.data)
eq_(body, [
{
'url': 'cloudfrunt.nut/BAD1DEA',
'image_id': images[0].image_id,
'task_id': id1,
},
{
'url': 'cloudfrunt.nut/CAFEBABE',
'image_id': images[1].image_id,
'task_id': id2,
},
{
'url': 'cloudfrunt.nut/DADD1E',
'image_id': images[2].image_id,
'task_id': id3,
},
])
@logged_in
def test_returns_bad_request_if_no_image_provided(self):
response = self.app.post('/add', data={
'url': '',
'image_file': (StringIO(), '')})
eq_(response.status_code, 400)
| {
"content_hash": "09e78d520e035b53bcd682d3ec486955",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 73,
"avg_line_length": 34.10362694300518,
"alnum_prop": 0.5597082953509571,
"repo_name": "ErinCall/catsnap",
"id": "92b04b336a11c5681688d85dfc6075e96f04f970",
"size": "6582",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/web/test_add.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4509"
},
{
"name": "HTML",
"bytes": "15632"
},
{
"name": "JavaScript",
"bytes": "19584"
},
{
"name": "Python",
"bytes": "208716"
}
],
"symlink_target": ""
} |
extensions = [
'sphinx.ext.autodoc',
]
# 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 encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'strong_typing'
copyright = u'2017, Surya Ambrose'
author = u'Surya Ambrose'
# 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.
import strong_typing
version = strong_typing.__VERSION__
# The full version, including alpha/beta/rc tags.
release = u'1.0-alpha'
# 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 = 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.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# 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 = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'classic'
# 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.
# "<project> v<release> documentation" by default.
#
# html_title = u'strong_typing v1.0'
# 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 (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# 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
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'strong_typingdoc'
# -- 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, 'strong_typing.tex', u'strong_typing Documentation',
u'Surya Ambrose', '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 = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# 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 = [
(master_doc, 'strong_typing', u'strong_typing Documentation',
[author], 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 name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'strong_typing', u'strong_typing Documentation',
author, 'strong_typing', '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'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
| {
"content_hash": "effc9ba16026b5723dbc4e06f2560ed0",
"timestamp": "",
"source": "github",
"line_count": 310,
"max_line_length": 80,
"avg_line_length": 28.545161290322582,
"alnum_prop": 0.691264549666629,
"repo_name": "aldebaran/strong_typing",
"id": "1e2021afd947811880e94d3760302c44c011b368",
"size": "9906",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/conf.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "78209"
}
],
"symlink_target": ""
} |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UserScore'
db.create_table(u'leaderboards_userscore', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['accounts.DetectMeProfile'])),
('category', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['leaderboards.Category'])),
))
db.send_create_signal(u'leaderboards', ['UserScore'])
def backwards(self, orm):
# Deleting model 'UserScore'
db.delete_table(u'leaderboards_userscore')
models = {
u'accounts.detectmeprofile': {
'Meta': {'object_name': 'DetectMeProfile'},
'favourite_snack': ('django.db.models.fields.CharField', [], {'max_length': '5'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mugshot': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'privacy': ('django.db.models.fields.CharField', [], {'default': "'registered'", 'max_length': '15'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'my_profile'", 'unique': 'True', 'to': u"orm['auth.User']"})
},
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'detectors.detector': {
'Meta': {'ordering': "('created_at',)", 'object_name': 'Detector'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounts.DetectMeProfile']"}),
'average_image': ('django.db.models.fields.files.ImageField', [], {'default': "'defaults/default.png'", 'max_length': '100', 'null': 'True', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'hash_value': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['detectors.Detector']", 'null': 'True', 'blank': 'True'}),
'sizes': ('django.db.models.fields.TextField', [], {}),
'target_class': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'weights': ('django.db.models.fields.TextField', [], {})
},
u'leaderboards.category': {
'Meta': {'object_name': 'Category'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'leaderboards.performance': {
'Meta': {'object_name': 'Performance'},
'average_precision': ('django.db.models.fields.FloatField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'detector': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['detectors.Detector']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'precision': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'recall': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'test_set': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})
},
u'leaderboards.userscore': {
'Meta': {'object_name': 'UserScore'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['leaderboards.Category']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounts.DetectMeProfile']"})
}
}
complete_apps = ['leaderboards'] | {
"content_hash": "14780dc053fb999db4d19dd1d7c98b68",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 187,
"avg_line_length": 70.5229357798165,
"alnum_prop": 0.5573045401326916,
"repo_name": "mingot/detectme_server",
"id": "46f5e90df547b9ef2ec1fde0cc3874258efc4d33",
"size": "7711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "detectme/leaderboards/migrations/0003_auto__add_userscore.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "7758"
},
{
"name": "CSS",
"bytes": "65143"
},
{
"name": "JavaScript",
"bytes": "333111"
},
{
"name": "Python",
"bytes": "238082"
},
{
"name": "Shell",
"bytes": "5270"
}
],
"symlink_target": ""
} |
try:
# for Python2
from Tkinter import *
import Tkinter as tk
from DiffWord import * # added by Samad
import time
except ImportError:
# for Python3
from tkinter import *
import tkinter as tk
import time
# speech api
import speech_recognition as sr
from oauth2client.client import GoogleCredentials
from diffCheck import *
textFont1 = ("Courier New", 16, "normal")
sec = 0
# These are classes for each step in the QuoteR program
# general page class
class Page(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
def show(self):
self.lift()
def drop(self):
self.lower()
# This page will just be a welcome slide that
# outputs text and directs the user to the next page.
class WelcomePage(Page):
def __init__(self, master):
Page.__init__(self, master)
# welcome label
label = tk.Label(self, text="Welcome to QuoteR")
# set font
label.config(font=("Courier", 44))
# formating
label.pack(side="top", fill="both", expand=True)
# label.configure(background='navajo white')
# this page has a text box where the user can input the correct version of the
# input in text format
class InputPage(Page):
def __init__(self, master, fnout):
Page.__init__(self, master)
# text label and formatting
label = tk.Label(self, text="Enter your text")
label.config(font=("Courier", 44))
label.grid(row=0, column=0, sticky="ns")
# label.configure(background='white')
# using .grid over pack for a more structured ui
self.fnout = fnout
self.mainFrame = tk.Frame(self)
top = self.winfo_toplevel()
top.columnconfigure(0, weight=1)
top.rowconfigure(0, weight=1)
self.mainFrame.grid(row=1, column=0, sticky="nsew")
self.exit = tk.Button(self.mainFrame,
text="Save your text",
command=self.finish)
self.exit.grid(row=4, column=0, sticky="ns")
self.exit.config(font=("Courier", 16))
self.mainFrame.columnconfigure(0, weight=1)
self.mainFrame.rowconfigure(1, weight=1)
vscrollbar = ScrollbarX(self.mainFrame)
vscrollbar.grid(row=1, column=1, sticky="ns")
hscrollbar = ScrollbarX(self.mainFrame, orient=tk.HORIZONTAL)
hscrollbar.grid(row=2, column=0, sticky="ew")
hscrollbar.grid(row=2, column=0, padx=(100, 0))
self.textWidget = tk.Text(self.mainFrame,
yscrollcommand=vscrollbar.set,
xscrollcommand=hscrollbar.set,
wrap=tk.NONE,
height=24,
width=84,
font=textFont1)
self.textWidget.grid(row=1, column=0, sticky="nsew")
self.textWidget.grid(row=1, column=0, padx=(100, 0))
hscrollbar["command"] = self.textWidget.xview
vscrollbar["command"] = self.textWidget.yview
def finish(self):
fout = open(self.fnout, 'w')
fout.write(self.textWidget.get("1.0", "end"))
fout.close()
# this page will be where you begin your reciting
# and where the audio input will be
# entered into the file.
class ReadyPage(Page):
def __init__(self, master):
Page.__init__(self, master)
def speechAPI():
# self.drop()
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)
# This is an alternative to goolge if we want, but it's also a
# requirment for the google api
"""
try:
print("Sphinx thinks you said " + r.recognize_sphinx(audio))
except sr.UnknownValueError:
print("Sphinx could not understand audio")
except sr.RequestError as e:
print("Sphinx error; {0}".format(e))
"""
# recognize speech using Google Speech Recognition
try:
# right now , we are using the default API key
# r.recognize_google
# (audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")
# will get a different one
# instead of `r.recognize_google(audio)`
print(
"Google Speech Recognition thinks you said " +
r.recognize_google(audio))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print(
"Could not request results from Google Speech " +
" Recognition service; {0}".format(e))
file2 = open("audioInput.txt", "w")
try:
file2.write(r.recognize_google(audio))
except sr.UnknownValueError:
file2.write(
"Google Speech Recognition could not understand audio")
except sr.RequestError as e:
file2.write(
"Could not request results from Google Speech" +
"Recognition service; {0}".format(e))
file2.close()
label = tk.Label(
self, text="Ready?\n Click the button below to start reciting")
label.config(font=("Courier", 32))
label.grid(row=0, column=0, sticky="ns")
self.mainFrame = tk.Frame(self)
self.mainFrame.grid(row=1, column=0, sticky="nsew")
top = self.winfo_toplevel()
top.columnconfigure(0, weight=1)
top.rowconfigure(0, weight=1)
self.start = tk.Button(self.mainFrame, command=speechAPI, text="Start")
self.start.config(font=("Courier", 16))
self.start.grid(row=2, column=2, sticky="se")\
# self.start.place(relx=0.5, rely=0.5, anchor=CENTER)
# self.done = tk.Button(self.mainFrame,text="Done")
# self.done.grid(row=3, column=4, sticky="ns")
# self.done.config(font=("Courier", 16))
# self.done.place(relx=.5, rely=.5, anchor=CENTER)
# we might time how long it takes for the speach to take place
class TimerPage(Page):
def __init__(self, master):
Page.__init__(self, master)
label = tk.Label(self, text="Stay silent for 5 seconds\n when finished reciting on next page")
label.config(font=("Courier", 32))
label.pack(side="top", fill="both", expand=True)
# here both the output and the input text will be compared and differences
# will be highlighted
class ComparisonPage(Page):
def __init__(self, master):
def loadInputText():
file = open("input.txt")
i = 0
f1_words = get_words(file)
for word in f1_words:
i += 1
if(i % 7 == 0):
self.textWidget.insert(END, str(word) + " \n")
else:
self.textWidget.insert(END, str(word) + " ")
file.close()
def loadAudioText():
file1 = open("input.txt")
file2 = open("audioInput.txt")
f1_words = get_words(file1)
f2_words = get_words(file2)
num_f1_words = len(f1_words)
num_f2_words = len(f2_words)
diffWords = get_DiffWords(f1_words, f2_words)
i = 0
j = 0
for word in diffWords:
if((num_f2_words == num_f1_words or num_f2_words > num_f1_words) and word.get_pos_in_derived() == -1):
continue
if(num_f1_words > num_f2_words and word.get_pos_in_original() == -1):
continue
else:
i += 1
if (word.isDiff()):
j += 1
# if(j%2 == 0):
if(i % 7 == 0):
self.textWidget2.tag_configure(
'color', foreground='red')
self.textWidget2.insert(
END, str(word) + " \n", 'color')
else:
self.textWidget2.tag_configure(
'color', foreground='red')
self.textWidget2.insert(
END, str(word) + " ", 'color')
else:
if(i % 7 == 0):
self.textWidget2.insert(END, str(word) + " \n")
else:
self.textWidget2.insert(END, str(word) + " ")
# for line2 in file2:
# self.textWidget2.insert(END,line2)
file1.close()
file2.close()
Page.__init__(self, master)
self.fnout = "input.txt"
self.mainFrame = tk.Frame(self)
self.mainFrame.grid(row=1, column=0, sticky="nsew")
top = self.winfo_toplevel()
top.columnconfigure(0, weight=1)
top.rowconfigure(0, weight=1)
# label = tk.Label(self, text="Your Text")
# label.config(font=("Courier", 22))
# label.grid(row=0, column=0)
# label2 = tk.Label(self, text="Your Audio Input")
# label2.config(font=("Courier", 22))
# label2.grid(row=0, column=1)
self.exit = tk.Button(self.mainFrame, command=loadInputText,
text="Load Input Text"
)
self.exit.grid(row=4, column=0, sticky="ns")
self.exit.config(font=("Courier", 16))
self.exit2 = tk.Button(self.mainFrame, command=loadAudioText,
text="Load Audio Text"
)
self.exit2.grid(row=4, column=1, sticky="ns")
self.exit2.config(font=("Courier", 16))
self.mainFrame.columnconfigure(0, weight=1)
self.mainFrame.rowconfigure(1, weight=1)
vscrollbar = ScrollbarX(self.mainFrame)
vscrollbar.grid(row=1, column=1, sticky="ns")
hscrollbar = ScrollbarX(self.mainFrame, orient=tk.HORIZONTAL)
hscrollbar.grid(row=2, column=0, sticky="ew")
hscrollbar.grid(row=2, column=0, padx=(100, 0))
self.textWidget = tk.Text(self.mainFrame,
yscrollcommand=vscrollbar.set,
xscrollcommand=hscrollbar.set,
wrap=tk.NONE,
height=24,
width=44,
font=textFont1)
self.textWidget.grid(row=1, column=0, sticky="nsew")
self.textWidget.grid(row=1, column=0, padx=(100, 0))
vscrollbar2 = ScrollbarX(self.mainFrame)
vscrollbar2.grid(row=1, column=3, sticky="ns")
hscrollbar2 = ScrollbarX(self.mainFrame, orient=tk.HORIZONTAL)
hscrollbar2.grid(row=2, column=1, sticky="ew")
hscrollbar2.grid(row=2, column=1, padx=(100, 0))
self.textWidget2 = tk.Text(self.mainFrame,
yscrollcommand=vscrollbar2.set,
xscrollcommand=hscrollbar2.set,
wrap=tk.NONE,
height=24,
width=44,
font=textFont1)
self.textWidget2.grid(row=1, column=1, sticky="nsew")
self.textWidget2.grid(row=1, column=1, padx=(100, 0))
hscrollbar["command"] = self.textWidget.xview
vscrollbar["command"] = self.textWidget.yview
hscrollbar2["command"] = self.textWidget2.xview
vscrollbar2["command"] = self.textWidget2.yview
# idea for the future
# make a command on each button that loads the input for each
# file
# ie it only inserts the stuff once you click the button
# so it gets an updated version of each file
# scrollbar class
class ScrollbarX(tk.Scrollbar):
def set(self, low, high):
if float(low) <= 0.0 and float(high) >= 1.0:
self.grid_remove()
else:
self.grid()
tk.Scrollbar.set(self, low, high)
# general class where all layers are palaced and buttons implemented
class MyFirstGUI(tk.Frame):
def __init__(self, master):
self.master = master
self.centerWindow()
tk.Frame.__init__(self, master)
# make pages
p0 = WelcomePage(self)
p1 = InputPage(self, inText)
p2 = TimerPage(self)
p3 = ReadyPage(self)
p5 = ComparisonPage(self)
# make button frames
buttonframe = tk.Frame(self)
container = tk.Frame(self)
container.configure(background='black')
buttonframe.pack(side="top", fill="x", expand=False)
container.pack(side="top", fill="both", expand=True)
# place all the pages in the program
p0.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p1.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p2.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p3.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p5.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
# place all the buttons
b0 = tk.Button(buttonframe, text="Welcome", command=p0.lift)
b1 = tk.Button(buttonframe, text="Input", command=p1.lift)
b3 = tk.Button(buttonframe, text="Ready", command=p3.lift)
b2 = tk.Button(buttonframe, text="Instruct", command=p2.lift)
b5 = tk.Button(buttonframe, text="Comparison", command=p5.lift)
b0.pack(side="left")
# b0.configure(background='blue')
b1.pack(side="left")
b2.pack(side="left")
b3.pack(side="left")
b5.pack(side="left")
# show welcome page that will link to others
p0.show()
master.title("QuoteR")
# centers the window based on 1280 x 720 size, might change based on
# users screen later
def centerWindow(self):
w = 1400
h = 800
sw = self.master.winfo_screenwidth()
sh = self.master.winfo_screenheight()
x = (sw - w) / 2
y = (sh - h) / 2
self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))
# initialization and running
inText = "input.txt"
audioText = "audioInput.txt"
root = tk.Tk()
my_gui = MyFirstGUI(root)
root.tk_setPalette(background='navajo white', foreground='black',
activeBackground='black', activeForeground='white')
my_gui.pack(side="top", fill="both", expand=True)
# root.wm_geometry("1024x768")
root.mainloop()
| {
"content_hash": "c14786e65836e74146fd984b398a80ac",
"timestamp": "",
"source": "github",
"line_count": 420,
"max_line_length": 118,
"avg_line_length": 35.326190476190476,
"alnum_prop": 0.5405405405405406,
"repo_name": "faroos3/QuoteR",
"id": "212143cf7693e45ab970a2eff025aceadde06c28",
"size": "14888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/GUI/main.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "32106"
}
],
"symlink_target": ""
} |
from ggrc import db
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import validates
from .associationproxy import association_proxy
from .category import CategoryBase
from .categorization import Categorizable
from .mixins import (
deferred, BusinessObject, Hierarchical, Timeboxed, CustomAttributable, TestPlanned
)
from .object_document import Documentable
from .object_owner import Ownable
from .object_person import Personable
from .audit_object import Auditable
from .reflection import PublishOnly
from .utils import validate_option
from .relationship import Relatable
from .track_object_state import HasObjectState, track_state_for_class
class ControlCategory(CategoryBase):
__mapper_args__ = {
'polymorphic_identity': 'ControlCategory'
}
_table_plural = 'control_categories'
class ControlAssertion(CategoryBase):
__mapper_args__ = {
'polymorphic_identity': 'ControlAssertion'
}
_table_plural = 'control_assertions'
class ControlCategorized(Categorizable):
@declared_attr
def categorizations(cls):
return cls.declare_categorizable(
"ControlCategory", "category", "categories", "categorizations")
_publish_attrs = [
'categories',
PublishOnly('categorizations'),
]
_include_links = [
#'categories',
]
@classmethod
def eager_query(cls):
from sqlalchemy import orm
query = super(ControlCategorized, cls).eager_query()
return query.options(
orm.subqueryload('categorizations').joinedload('category'),
)
class AssertionCategorized(Categorizable):
@declared_attr
def assertations(cls):
return cls.declare_categorizable(
"ControlAssertion", "assertion", "assertions", "assertations")
_publish_attrs = [
'assertions',
PublishOnly('assertations'),
]
_include_links = [
#'assertions',
]
@classmethod
def eager_query(cls):
from sqlalchemy import orm
query = super(AssertionCategorized, cls).eager_query()
return query.options(
orm.subqueryload('assertations').joinedload('category'),
)
class Control(HasObjectState, Relatable,
CustomAttributable, Documentable, Personable, ControlCategorized, AssertionCategorized,
Hierarchical, Timeboxed, Ownable, BusinessObject, Auditable, TestPlanned, db.Model):
__tablename__ = 'controls'
company_control = deferred(db.Column(db.Boolean), 'Control')
directive_id = deferred(
db.Column(db.Integer, db.ForeignKey('directives.id')), 'Control')
kind_id = deferred(db.Column(db.Integer), 'Control')
means_id = deferred(db.Column(db.Integer), 'Control')
version = deferred(db.Column(db.String), 'Control')
documentation_description = deferred(db.Column(db.Text), 'Control')
verify_frequency_id = deferred(db.Column(db.Integer), 'Control')
fraud_related = deferred(db.Column(db.Boolean), 'Control')
key_control = deferred(db.Column(db.Boolean), 'Control')
active = deferred(db.Column(db.Boolean), 'Control')
principal_assessor_id = deferred(
db.Column(db.Integer, db.ForeignKey('people.id')), 'Control')
secondary_assessor_id = deferred(
db.Column(db.Integer, db.ForeignKey('people.id')), 'Control')
principal_assessor = db.relationship(
'Person', uselist=False, foreign_keys='Control.principal_assessor_id')
secondary_assessor = db.relationship(
'Person', uselist=False, foreign_keys='Control.secondary_assessor_id')
kind = db.relationship(
'Option',
primaryjoin='and_(foreign(Control.kind_id) == Option.id, '\
'Option.role == "control_kind")',
uselist=False)
means = db.relationship(
'Option',
primaryjoin='and_(foreign(Control.means_id) == Option.id, '\
'Option.role == "control_means")',
uselist=False)
verify_frequency = db.relationship(
'Option',
primaryjoin='and_(foreign(Control.verify_frequency_id) == Option.id, '\
'Option.role == "verify_frequency")',
uselist=False)
control_sections = db.relationship(
'ControlSection', backref='control', cascade='all, delete-orphan')
sections = association_proxy(
'control_sections', 'section', 'ControlSection')
objective_controls = db.relationship(
'ObjectiveControl', backref='control', cascade='all, delete-orphan')
objectives = association_proxy(
'objective_controls', 'objective', 'ObjectiveControl')
control_controls = db.relationship(
'ControlControl',
foreign_keys='ControlControl.control_id',
backref='control',
cascade='all, delete-orphan',
)
implemented_controls = association_proxy(
'control_controls', 'implemented_control', 'ControlControl')
implementing_control_controls = db.relationship(
'ControlControl',
foreign_keys='ControlControl.implemented_control_id',
backref='implemented_control',
cascade='all, delete-orphan',
)
implementing_controls = association_proxy(
'implementing_control_controls', 'control', 'ControlControl')
object_controls = db.relationship(
'ObjectControl', backref='control', cascade='all, delete-orphan')
directive_controls = db.relationship(
'DirectiveControl', backref='control', cascade='all, delete-orphan')
# Not needed for the client at this time
#mapped_directives = association_proxy(
# 'directive_controls', 'directive', 'DirectiveControl')
@staticmethod
def _extra_table_args(cls):
return (
db.Index('ix_controls_principal_assessor', 'principal_assessor_id'),
db.Index('ix_controls_secondary_assessor', 'secondary_assessor_id'),
)
# REST properties
_publish_attrs = [
'active',
'company_control',
'directive',
'documentation_description',
'fraud_related',
'key_control',
'kind',
'means',
'sections',
'objectives',
'verify_frequency',
'version',
'principal_assessor',
'secondary_assessor',
PublishOnly('control_controls'),
PublishOnly('control_sections'),
PublishOnly('objective_controls'),
PublishOnly('implementing_control_controls'),
PublishOnly('directive_controls'),
'object_controls',
]
_sanitize_html = [
'documentation_description',
'version',
]
_include_links = []
@validates('kind', 'means', 'verify_frequency')
def validate_control_options(self, key, option):
desired_role = key if key == 'verify_frequency' else 'control_' + key
return validate_option(self.__class__.__name__, key, option, desired_role)
@classmethod
def eager_query(cls):
from sqlalchemy import orm
query = super(Control, cls).eager_query()
return cls.eager_inclusions(query, Control._include_links).options(
orm.joinedload('directive'),
orm.joinedload('principal_assessor'),
orm.joinedload('secondary_assessor'),
orm.subqueryload('control_controls'),
orm.subqueryload('implementing_control_controls'),
orm.subqueryload('control_sections'),
orm.subqueryload('objective_controls'),
orm.subqueryload('directive_controls').joinedload('directive'),
orm.subqueryload('object_controls'),
)
def log_json(self):
out_json = super(Control, self).log_json()
# so that event log can refer to deleted directive
if self.directive:
out_json["mapped_directive"] = self.directive.display_name
return out_json
track_state_for_class(Control)
| {
"content_hash": "81c6238639e863fe471c1cde75fd5c09",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 91,
"avg_line_length": 33.84234234234234,
"alnum_prop": 0.6813523226407561,
"repo_name": "vladan-m/ggrc-core",
"id": "792bc1837351973d88443a1e7610001071ab52a0",
"size": "7754",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/ggrc/models/control.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "230813"
},
{
"name": "Cucumber",
"bytes": "148444"
},
{
"name": "HTML",
"bytes": "6041162"
},
{
"name": "JavaScript",
"bytes": "1893341"
},
{
"name": "Makefile",
"bytes": "5483"
},
{
"name": "Mako",
"bytes": "1720"
},
{
"name": "Python",
"bytes": "1489657"
},
{
"name": "Ruby",
"bytes": "1496"
},
{
"name": "Shell",
"bytes": "11555"
}
],
"symlink_target": ""
} |
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_noop, ugettext as _
from corehq.apps.domain.decorators import login_required
from corehq.apps.hqwebapp.views import BaseSectionPageView
from corehq.apps.styleguide.examples.simple_crispy_form.forms import ExampleUserLoginForm
from dimagi.utils.decorators.memoized import memoized
class BaseSimpleCrispyFormSectionView(BaseSectionPageView):
section_name = ugettext_noop("Simple Crispy Form Example")
def section_url(self):
return reverse(DefaultSimpleCrispyFormSectionView.urlname)
@property
def page_url(self):
return reverse(self.urlname)
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(BaseSimpleCrispyFormSectionView, self).dispatch(request, *args, **kwargs)
class DefaultSimpleCrispyFormSectionView(BaseSimpleCrispyFormSectionView):
urlname = 'ex_simple_crispy_forms_default'
def get(self, request, *args, **kwargs):
# decide what to serve based on request
return HttpResponseRedirect(reverse(SimpleCrispyFormView.urlname))
class SimpleCrispyFormView(BaseSimpleCrispyFormSectionView):
"""This shows example usage for crispy forms in an HQ template view.
"""
page_title = ugettext_noop("Register a New User")
urlname = 'ex_simple_crispy_forms'
template_name = 'styleguide/examples/simple_crispy_form/base.html'
@property
@memoized
def simple_crispy_form(self):
initial_data = {}
if self.request.method == 'POST':
return ExampleUserLoginForm(self.request.POST, initial=initial_data)
return ExampleUserLoginForm(initial=initial_data)
@property
def page_context(self):
return {
'simple_crispy_form': self.simple_crispy_form,
}
def post(self, request, *args, **kwargs):
if self.simple_crispy_form.is_valid():
# do something to process the data
# It's always best practice to give some sort of feedback to the
# user that the form was successfully processed.
messages.success(request,
_("Form processed successfully.")
)
return HttpResponseRedirect(self.page_url)
return self.get(request, *args, **kwargs)
| {
"content_hash": "0b5295a25d6d9664f72729143be65970",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 94,
"avg_line_length": 38.01538461538462,
"alnum_prop": 0.7138810198300283,
"repo_name": "qedsoftware/commcare-hq",
"id": "48e465c38554687360d73d8f89659322d5070332",
"size": "2471",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "corehq/apps/styleguide/examples/simple_crispy_form/views.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "15950"
},
{
"name": "CSS",
"bytes": "508392"
},
{
"name": "HTML",
"bytes": "2869325"
},
{
"name": "JavaScript",
"bytes": "2395360"
},
{
"name": "PHP",
"bytes": "2232"
},
{
"name": "PLpgSQL",
"bytes": "125298"
},
{
"name": "Python",
"bytes": "14670713"
},
{
"name": "Shell",
"bytes": "37514"
}
],
"symlink_target": ""
} |
from ....testing import assert_equal
from ..preprocess import ApplyDeformations
def test_ApplyDeformations_inputs():
input_map = dict(deformation_field=dict(field='comp{1}.def',
mandatory=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
in_files=dict(field='fnames',
mandatory=True,
),
interp=dict(field='interp',
),
matlab_cmd=dict(),
mfile=dict(usedefault=True,
),
paths=dict(),
reference_volume=dict(field='comp{2}.id.space',
mandatory=True,
),
use_mcr=dict(),
use_v8struct=dict(min_ver='8',
usedefault=True,
),
)
inputs = ApplyDeformations.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_ApplyDeformations_outputs():
output_map = dict(out_files=dict(),
)
outputs = ApplyDeformations.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(outputs.traits()[key], metakey), value
| {
"content_hash": "a8771ef890fe19761a2b09dc593a72a1",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 78,
"avg_line_length": 27.209302325581394,
"alnum_prop": 0.6410256410256411,
"repo_name": "carolFrohlich/nipype",
"id": "a84d6e82467a16dc07cd20a74ac6421f02acb0da",
"size": "1224",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "nipype/interfaces/spm/tests/test_auto_ApplyDeformations.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "9823"
},
{
"name": "KiCad",
"bytes": "3797"
},
{
"name": "Makefile",
"bytes": "2320"
},
{
"name": "Matlab",
"bytes": "1717"
},
{
"name": "Python",
"bytes": "5451077"
},
{
"name": "Shell",
"bytes": "3302"
},
{
"name": "Tcl",
"bytes": "43408"
}
],
"symlink_target": ""
} |
"""Materialized Path Trees"""
import sys
import operator
if sys.version_info >= (3, 0):
from functools import reduce
from django.core import serializers
from django.db import models, transaction, connection
from django.db.models import F, Q
from django.utils.translation import ugettext_noop as _
from treebeard.numconv import NumConv
from treebeard.models import Node
from treebeard.exceptions import InvalidMoveToDescendant, PathOverflow,\
NodeAlreadySaved
def get_result_class(cls):
"""
For the given model class, determine what class we should use for the
nodes returned by its tree methods (such as get_children).
Usually this will be trivially the same as the initial model class,
but there are special cases when model inheritance is in use:
* If the model extends another via multi-table inheritance, we need to
use whichever ancestor originally implemented the tree behaviour (i.e.
the one which defines the 'path' field). We can't use the
subclass, because it's not guaranteed that the other nodes reachable
from the current one will be instances of the same subclass.
* If the model is a proxy model, the returned nodes should also use
the proxy class.
"""
base_class = cls._meta.get_field('path').model
if cls._meta.proxy_for_model == base_class:
return cls
else:
return base_class
class MP_NodeQuerySet(models.query.QuerySet):
"""
Custom queryset for the tree node manager.
Needed only for the custom delete method.
"""
def delete(self):
"""
Custom delete method, will remove all descendant nodes to ensure a
consistent tree (no orphans)
:returns: ``None``
"""
# we'll have to manually run through all the nodes that are going
# to be deleted and remove nodes from the list if an ancestor is
# already getting removed, since that would be redundant
removed = {}
for node in self.order_by('depth', 'path'):
found = False
for depth in range(1, int(len(node.path) / node.steplen)):
path = node._get_basepath(node.path, depth)
if path in removed:
# we are already removing a parent of this node
# skip
found = True
break
if not found:
removed[node.path] = node
# ok, got the minimal list of nodes to remove...
# we must also remove their children
# and update every parent node's numchild attribute
# LOTS OF FUN HERE!
parents = {}
toremove = []
for path, node in removed.items():
parentpath = node._get_basepath(node.path, node.depth - 1)
if parentpath:
if parentpath not in parents:
parents[parentpath] = node.get_parent(True)
parent = parents[parentpath]
if parent and parent.numchild > 0:
parent.numchild -= 1
parent.save()
if node.is_leaf():
toremove.append(Q(path=node.path))
else:
toremove.append(Q(path__startswith=node.path))
# Django will handle this as a SELECT and then a DELETE of
# ids, and will deal with removing related objects
if toremove:
qset = get_result_class(self.model).objects.filter(reduce(operator.or_, toremove))
super(MP_NodeQuerySet, qset).delete()
class MP_NodeManager(models.Manager):
"""Custom manager for nodes in a Materialized Path tree."""
def get_queryset(self):
"""Sets the custom queryset as the default."""
return MP_NodeQuerySet(self.model).order_by('path')
class MP_AddHandler(object):
def __init__(self):
self.stmts = []
class MP_ComplexAddMoveHandler(MP_AddHandler):
def run_sql_stmts(self):
cursor = self.node_cls._get_database_cursor('write')
for sql, vals in self.stmts:
cursor.execute(sql, vals)
def get_sql_update_numchild(self, path, incdec='inc'):
""":returns: The sql needed the numchild value of a node"""
sql = "UPDATE %s SET numchild=numchild%s1"\
" WHERE path=%%s" % (
connection.ops.quote_name(
get_result_class(self.node_cls)._meta.db_table),
{'inc': '+', 'dec': '-'}[incdec])
vals = [path]
return sql, vals
def reorder_nodes_before_add_or_move(self, pos, newpos, newdepth, target,
siblings, oldpath=None,
movebranch=False):
"""
Handles the reordering of nodes and branches when adding/moving
nodes.
:returns: A tuple containing the old path and the new path.
"""
if (
(pos == 'last-sibling') or
(pos == 'right' and target == target.get_last_sibling())
):
# easy, the last node
last = target.get_last_sibling()
newpath = last._inc_path()
if movebranch:
self.stmts.append(
self.get_sql_newpath_in_branches(oldpath, newpath))
else:
# do the UPDATE dance
if newpos is None:
siblings = target.get_siblings()
siblings = {'left': siblings.filter(path__gte=target.path),
'right': siblings.filter(path__gt=target.path),
'first-sibling': siblings}[pos]
basenum = target._get_lastpos_in_path()
newpos = {'first-sibling': 1,
'left': basenum,
'right': basenum + 1}[pos]
newpath = self.node_cls._get_path(target.path, newdepth, newpos)
# If the move is amongst siblings and is to the left and there
# are siblings to the right of its new position then to be on
# the safe side we temporarily dump it on the end of the list
tempnewpath = None
if movebranch and len(oldpath) == len(newpath):
parentoldpath = self.node_cls._get_basepath(
oldpath,
int(len(oldpath) / self.node_cls.steplen) - 1
)
parentnewpath = self.node_cls._get_basepath(
newpath, newdepth - 1)
if (
parentoldpath == parentnewpath and
siblings and
newpath < oldpath
):
last = target.get_last_sibling()
basenum = last._get_lastpos_in_path()
tempnewpath = self.node_cls._get_path(
newpath, newdepth, basenum + 2)
self.stmts.append(
self.get_sql_newpath_in_branches(
oldpath, tempnewpath))
# Optimisation to only move siblings which need moving
# (i.e. if we've got holes, allow them to compress)
movesiblings = []
priorpath = newpath
for node in siblings:
# If the path of the node is already greater than the path
# of the previous node it doesn't need shifting
if node.path > priorpath:
break
# It does need shifting, so add to the list
movesiblings.append(node)
# Calculate the path that it would be moved to, as that's
# the next "priorpath"
priorpath = node._inc_path()
movesiblings.reverse()
for node in movesiblings:
# moving the siblings (and their branches) at the right of the
# related position one step to the right
sql, vals = self.get_sql_newpath_in_branches(
node.path, node._inc_path())
self.stmts.append((sql, vals))
if movebranch:
if oldpath.startswith(node.path):
# if moving to a parent, update oldpath since we just
# increased the path of the entire branch
oldpath = vals[0] + oldpath[len(vals[0]):]
if target.path.startswith(node.path):
# and if we moved the target, update the object
# django made for us, since the update won't do it
# maybe useful in loops
target.path = vals[0] + target.path[len(vals[0]):]
if movebranch:
# node to move
if tempnewpath:
self.stmts.append(
self.get_sql_newpath_in_branches(
tempnewpath, newpath))
else:
self.stmts.append(
self.get_sql_newpath_in_branches(
oldpath, newpath))
return oldpath, newpath
def get_sql_newpath_in_branches(self, oldpath, newpath):
"""
:returns: The sql needed to move a branch to another position.
.. note::
The generated sql will only update the depth values if needed.
"""
vendor = self.node_cls.get_database_vendor('write')
sql1 = "UPDATE %s SET" % (
connection.ops.quote_name(
get_result_class(self.node_cls)._meta.db_table), )
# <3 "standard" sql
if vendor == 'sqlite':
# I know that the third argument in SUBSTR (LENGTH(path)) is
# awful, but sqlite fails without it:
# OperationalError: wrong number of arguments to function substr()
# even when the documentation says that 2 arguments are valid:
# http://www.sqlite.org/lang_corefunc.html
sqlpath = "%s||SUBSTR(path, %s, LENGTH(path))"
elif vendor == 'mysql':
# hooray for mysql ignoring standards in their default
# configuration!
# to make || work as it should, enable ansi mode
# http://dev.mysql.com/doc/refman/5.0/en/ansi-mode.html
sqlpath = "CONCAT(%s, SUBSTR(path, %s))"
else:
sqlpath = "%s||SUBSTR(path, %s)"
sql2 = ["path=%s" % (sqlpath, )]
vals = [newpath, len(oldpath) + 1]
if len(oldpath) != len(newpath) and vendor != 'mysql':
# when using mysql, this won't update the depth and it has to be
# done in another query
# doesn't even work with sql_mode='ANSI,TRADITIONAL'
# TODO: FIND OUT WHY?!?? right now I'm just blaming mysql
sql2.append("depth=LENGTH(%s)/%%s" % (sqlpath, ))
vals.extend([newpath, len(oldpath) + 1, self.node_cls.steplen])
sql3 = "WHERE path LIKE %s"
vals.extend([oldpath + '%'])
sql = '%s %s %s' % (sql1, ', '.join(sql2), sql3)
return sql, vals
class MP_AddRootHandler(MP_AddHandler):
def __init__(self, cls, **kwargs):
super(MP_AddRootHandler, self).__init__()
self.cls = cls
self.kwargs = kwargs
def process(self):
# do we have a root node already?
last_root = self.cls.get_last_root_node()
if last_root and last_root.node_order_by:
# there are root nodes and node_order_by has been set
# delegate sorted insertion to add_sibling
return last_root.add_sibling('sorted-sibling', **self.kwargs)
if last_root:
# adding the new root node as the last one
newpath = last_root._inc_path()
else:
# adding the first root node
newpath = self.cls._get_path(None, 1, 1)
if len(self.kwargs) == 1 and 'instance' in self.kwargs:
# adding the passed (unsaved) instance to the tree
newobj = self.kwargs['instance']
if newobj.pk:
raise NodeAlreadySaved("Attempted to add a tree node that is "\
"already in the database")
else:
# creating the new object
newobj = self.cls(**self.kwargs)
newobj.depth = 1
newobj.path = newpath
# saving the instance before returning it
newobj.save()
return newobj
class MP_AddChildHandler(MP_AddHandler):
def __init__(self, node, **kwargs):
super(MP_AddChildHandler, self).__init__()
self.node = node
self.node_cls = node.__class__
self.kwargs = kwargs
def process(self):
if self.node_cls.node_order_by and not self.node.is_leaf():
# there are child nodes and node_order_by has been set
# delegate sorted insertion to add_sibling
self.node.numchild += 1
return self.node.get_last_child().add_sibling(
'sorted-sibling', **self.kwargs)
if len(self.kwargs) == 1 and 'instance' in self.kwargs:
# adding the passed (unsaved) instance to the tree
newobj = self.kwargs['instance']
if newobj.pk:
raise NodeAlreadySaved("Attempted to add a tree node that is "\
"already in the database")
else:
# creating a new object
newobj = self.node_cls(**self.kwargs)
newobj.depth = self.node.depth + 1
if self.node.is_leaf():
# the node had no children, adding the first child
newobj.path = self.node_cls._get_path(
self.node.path, newobj.depth, 1)
max_length = self.node_cls._meta.get_field('path').max_length
if len(newobj.path) > max_length:
raise PathOverflow(
_('The new node is too deep in the tree, try'
' increasing the path.max_length property'
' and UPDATE your database'))
else:
# adding the new child as the last one
newobj.path = self.node.get_last_child()._inc_path()
# saving the instance before returning it
newobj.save()
newobj._cached_parent_obj = self.node
get_result_class(self.node_cls).objects.filter(
path=self.node.path).update(numchild=F('numchild')+1)
# we increase the numchild value of the object in memory
self.node.numchild += 1
return newobj
class MP_AddSiblingHandler(MP_ComplexAddMoveHandler):
def __init__(self, node, pos, **kwargs):
super(MP_AddSiblingHandler, self).__init__()
self.node = node
self.node_cls = node.__class__
self.pos = pos
self.kwargs = kwargs
def process(self):
self.pos = self.node._prepare_pos_var_for_add_sibling(self.pos)
if len(self.kwargs) == 1 and 'instance' in self.kwargs:
# adding the passed (unsaved) instance to the tree
newobj = self.kwargs['instance']
if newobj.pk:
raise NodeAlreadySaved("Attempted to add a tree node that is "\
"already in the database")
else:
# creating a new object
newobj = self.node_cls(**self.kwargs)
newobj.depth = self.node.depth
if self.pos == 'sorted-sibling':
siblings = self.node.get_sorted_pos_queryset(
self.node.get_siblings(), newobj)
try:
newpos = siblings.all()[0]._get_lastpos_in_path()
except IndexError:
newpos = None
if newpos is None:
self.pos = 'last-sibling'
else:
newpos, siblings = None, []
_, newpath = self.reorder_nodes_before_add_or_move(
self.pos, newpos, self.node.depth, self.node, siblings, None,
False)
parentpath = self.node._get_basepath(newpath, self.node.depth - 1)
if parentpath:
self.stmts.append(
self.get_sql_update_numchild(parentpath, 'inc'))
self.run_sql_stmts()
# saving the instance before returning it
newobj.path = newpath
newobj.save()
return newobj
class MP_MoveHandler(MP_ComplexAddMoveHandler):
def __init__(self, node, target, pos=None):
super(MP_MoveHandler, self).__init__()
self.node = node
self.node_cls = node.__class__
self.target = target
self.pos = pos
def process(self):
self.pos = self.node._prepare_pos_var_for_move(self.pos)
oldpath = self.node.path
# initialize variables and if moving to a child, updates "move to
# child" to become a "move to sibling" if possible (if it can't
# be done, it means that we are adding the first child)
newdepth, siblings, newpos = self.update_move_to_child_vars()
if self.target.is_descendant_of(self.node):
raise InvalidMoveToDescendant(
_("Can't move node to a descendant."))
if (
oldpath == self.target.path and
(
(self.pos == 'left') or
(
self.pos in ('right', 'last-sibling') and
self.target.path == self.target.get_last_sibling().path
) or
(
self.pos == 'first-sibling' and
self.target.path == self.target.get_first_sibling().path
)
)
):
# special cases, not actually moving the node so no need to UPDATE
return
if self.pos == 'sorted-sibling':
siblings = self.node.get_sorted_pos_queryset(
self.target.get_siblings(), self.node)
try:
newpos = siblings.all()[0]._get_lastpos_in_path()
except IndexError:
newpos = None
if newpos is None:
self.pos = 'last-sibling'
# generate the sql that will do the actual moving of nodes
oldpath, newpath = self.reorder_nodes_before_add_or_move(
self.pos, newpos, newdepth, self.target, siblings, oldpath, True)
# updates needed for mysql and children count in parents
self.sanity_updates_after_move(oldpath, newpath)
self.run_sql_stmts()
def sanity_updates_after_move(self, oldpath, newpath):
"""
Updates the list of sql statements needed after moving nodes.
1. :attr:`depth` updates *ONLY* needed by mysql databases (*sigh*)
2. update the number of children of parent nodes
"""
if (
self.node_cls.get_database_vendor('write') == 'mysql' and
len(oldpath) != len(newpath)
):
# no words can describe how dumb mysql is
# we must update the depth of the branch in a different query
self.stmts.append(
self.get_mysql_update_depth_in_branch(newpath))
oldparentpath = self.node_cls._get_parent_path_from_path(oldpath)
newparentpath = self.node_cls._get_parent_path_from_path(newpath)
if (
(not oldparentpath and newparentpath) or
(oldparentpath and not newparentpath) or
(oldparentpath != newparentpath)
):
# node changed parent, updating count
if oldparentpath:
self.stmts.append(
self.get_sql_update_numchild(oldparentpath, 'dec'))
if newparentpath:
self.stmts.append(
self.get_sql_update_numchild(newparentpath, 'inc'))
def update_move_to_child_vars(self):
"""Update preliminar vars in :meth:`move` when moving to a child"""
newdepth = self.target.depth
newpos = None
siblings = []
if self.pos in ('first-child', 'last-child', 'sorted-child'):
# moving to a child
parent = self.target
newdepth += 1
if self.target.is_leaf():
# moving as a target's first child
newpos = 1
self.pos = 'first-sibling'
siblings = get_result_class(self.node_cls).objects.none()
else:
self.target = self.target.get_last_child()
self.pos = {
'first-child': 'first-sibling',
'last-child': 'last-sibling',
'sorted-child': 'sorted-sibling'}[self.pos]
# this is not for save(), since if needed, will be handled with a
# custom UPDATE, this is only here to update django's object,
# should be useful in loops
parent.numchild += 1
return newdepth, siblings, newpos
def get_mysql_update_depth_in_branch(self, path):
"""
:returns: The sql needed to update the depth of all the nodes in a
branch.
"""
sql = "UPDATE %s SET depth=LENGTH(path)/%%s WHERE path LIKE %%s" % (
connection.ops.quote_name(
get_result_class(self.node_cls)._meta.db_table), )
vals = [self.node_cls.steplen, path + '%']
return sql, vals
class MP_Node(Node):
"""Abstract model to create your own Materialized Path Trees."""
steplen = 4
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
node_order_by = []
path = models.CharField(max_length=255, unique=True)
depth = models.PositiveIntegerField()
numchild = models.PositiveIntegerField(default=0)
gap = 1
objects = MP_NodeManager()
numconv_obj_ = None
@classmethod
def _int2str(cls, num):
return cls.numconv_obj().int2str(num)
@classmethod
def _str2int(cls, num):
return cls.numconv_obj().str2int(num)
@classmethod
def numconv_obj(cls):
if cls.numconv_obj_ is None:
cls.numconv_obj_ = NumConv(len(cls.alphabet), cls.alphabet)
return cls.numconv_obj_
@classmethod
def add_root(cls, **kwargs):
"""
Adds a root node to the tree.
This method saves the node in database. The object is populated as if via:
obj = cls(**kwargs)
:raise PathOverflow: when no more root objects can be added
"""
return MP_AddRootHandler(cls, **kwargs).process()
@classmethod
def dump_bulk(cls, parent=None, keep_ids=True):
"""Dumps a tree branch to a python data structure."""
cls = get_result_class(cls)
# Because of fix_tree, this method assumes that the depth
# and numchild properties in the nodes can be incorrect,
# so no helper methods are used
qset = cls._get_serializable_model().objects.all()
if parent:
qset = qset.filter(path__startswith=parent.path)
ret, lnk = [], {}
for pyobj in serializers.serialize('python', qset):
# django's serializer stores the attributes in 'fields'
fields = pyobj['fields']
path = fields['path']
depth = int(len(path) / cls.steplen)
# this will be useless in load_bulk
del fields['depth']
del fields['path']
del fields['numchild']
if 'id' in fields:
# this happens immediately after a load_bulk
del fields['id']
newobj = {'data': fields}
if keep_ids:
newobj['id'] = pyobj['pk']
if (not parent and depth == 1) or\
(parent and len(path) == len(parent.path)):
ret.append(newobj)
else:
parentpath = cls._get_basepath(path, depth - 1)
parentobj = lnk[parentpath]
if 'children' not in parentobj:
parentobj['children'] = []
parentobj['children'].append(newobj)
lnk[path] = newobj
return ret
@classmethod
def find_problems(cls):
"""
Checks for problems in the tree structure, problems can occur when:
1. your code breaks and you get incomplete transactions (always
use transactions!)
2. changing the ``steplen`` value in a model (you must
:meth:`dump_bulk` first, change ``steplen`` and then
:meth:`load_bulk`
:returns: A tuple of five lists:
1. a list of ids of nodes with characters not found in the
``alphabet``
2. a list of ids of nodes when a wrong ``path`` length
according to ``steplen``
3. a list of ids of orphaned nodes
4. a list of ids of nodes with the wrong depth value for
their path
5. a list of ids nodes that report a wrong number of children
"""
cls = get_result_class(cls)
evil_chars, bad_steplen, orphans = [], [], []
wrong_depth, wrong_numchild = [], []
for node in cls.objects.all():
found_error = False
for char in node.path:
if char not in cls.alphabet:
evil_chars.append(node.pk)
found_error = True
break
if found_error:
continue
if len(node.path) % cls.steplen:
bad_steplen.append(node.pk)
continue
try:
node.get_parent(True)
except cls.DoesNotExist:
orphans.append(node.pk)
continue
if node.depth != int(len(node.path) / cls.steplen):
wrong_depth.append(node.pk)
continue
real_numchild = cls.objects.filter(
path__range=cls._get_children_path_interval(node.path)
).extra(
where=['LENGTH(path)/%d=%d' % (cls.steplen, node.depth + 1)]
).count()
if real_numchild != node.numchild:
wrong_numchild.append(node.pk)
continue
return evil_chars, bad_steplen, orphans, wrong_depth, wrong_numchild
@classmethod
def fix_tree(cls, destructive=False):
"""
Solves some problems that can appear when transactions are not used and
a piece of code breaks, leaving the tree in an inconsistent state.
The problems this method solves are:
1. Nodes with an incorrect ``depth`` or ``numchild`` values due to
incorrect code and lack of database transactions.
2. "Holes" in the tree. This is normal if you move/delete nodes a
lot. Holes in a tree don't affect performance,
3. Incorrect ordering of nodes when ``node_order_by`` is enabled.
Ordering is enforced on *node insertion*, so if an attribute in
``node_order_by`` is modified after the node is inserted, the
tree ordering will be inconsistent.
:param destructive:
A boolean value. If True, a more agressive fix_tree method will be
attempted. If False (the default), it will use a safe (and fast!)
fix approach, but it will only solve the ``depth`` and
``numchild`` nodes, it won't fix the tree holes or broken path
ordering.
.. warning::
Currently what the ``destructive`` method does is:
1. Backup the tree with :meth:`dump_data`
2. Remove all nodes in the tree.
3. Restore the tree with :meth:`load_data`
So, even when the primary keys of your nodes will be preserved,
this method isn't foreign-key friendly. That needs complex
in-place tree reordering, not available at the moment (hint:
patches are welcome).
"""
cls = get_result_class(cls)
if destructive:
dump = cls.dump_bulk(None, True)
cls.objects.all().delete()
cls.load_bulk(dump, None, True)
else:
cursor = cls._get_database_cursor('write')
# fix the depth field
# we need the WHERE to speed up postgres
sql = "UPDATE %s "\
"SET depth=LENGTH(path)/%%s "\
"WHERE depth!=LENGTH(path)/%%s" % (
connection.ops.quote_name(cls._meta.db_table), )
vals = [cls.steplen, cls.steplen]
cursor.execute(sql, vals)
# fix the numchild field
vals = ['_' * cls.steplen]
# the cake and sql portability are a lie
if cls.get_database_vendor('read') == 'mysql':
sql = "SELECT tbn1.path, tbn1.numchild, ("\
"SELECT COUNT(1) "\
"FROM %(table)s AS tbn2 "\
"WHERE tbn2.path LIKE "\
"CONCAT(tbn1.path, %%s)) AS real_numchild "\
"FROM %(table)s AS tbn1 "\
"HAVING tbn1.numchild != real_numchild" % {
'table': connection.ops.quote_name(
cls._meta.db_table)}
else:
subquery = "(SELECT COUNT(1) FROM %(table)s AS tbn2"\
" WHERE tbn2.path LIKE tbn1.path||%%s)"
sql = ("SELECT tbn1.path, tbn1.numchild, " + subquery +
" FROM %(table)s AS tbn1 WHERE tbn1.numchild != " +
subquery)
sql = sql % {
'table': connection.ops.quote_name(cls._meta.db_table)}
# we include the subquery twice
vals *= 2
cursor.execute(sql, vals)
sql = "UPDATE %(table)s "\
"SET numchild=%%s "\
"WHERE path=%%s" % {
'table': connection.ops.quote_name(cls._meta.db_table)}
for node_data in cursor.fetchall():
vals = [node_data[2], node_data[0]]
cursor.execute(sql, vals)
@classmethod
def get_tree(cls, parent=None):
"""
:returns:
A *queryset* of nodes ordered as DFS, including the parent.
If no parent is given, the entire tree is returned.
"""
cls = get_result_class(cls)
if parent is None:
# return the entire tree
return cls.objects.all()
if parent.is_leaf():
return cls.objects.filter(pk=parent.pk)
return cls.objects.filter(path__startswith=parent.path,
depth__gte=parent.depth)
@classmethod
def get_root_nodes(cls):
""":returns: A queryset containing the root nodes in the tree."""
return get_result_class(cls).objects.filter(depth=1)
@classmethod
def get_descendants_group_count(cls, parent=None):
"""
Helper for a very common case: get a group of siblings and the number
of *descendants* in every sibling.
"""
#~
# disclaimer: this is the FOURTH implementation I wrote for this
# function. I really tried to make it return a queryset, but doing so
# with a *single* query isn't trivial with Django's ORM.
# ok, I DID manage to make Django's ORM return a queryset here,
# defining two querysets, passing one subquery in the tables parameters
# of .extra() of the second queryset, using the undocumented order_by
# feature, and using a HORRIBLE hack to avoid django quoting the
# subquery as a table, BUT (and there is always a but) the hack didn't
# survive turning the QuerySet into a ValuesQuerySet, so I just used
# good old SQL.
# NOTE: in case there is interest, the hack to avoid django quoting the
# subquery as a table, was adding the subquery to the alias cache of
# the queryset's query object:
#
# qset.query.quote_cache[subquery] = subquery
#
# If there is a better way to do this in an UNMODIFIED django 1.0, let
# me know.
#~
cls = get_result_class(cls)
if parent:
depth = parent.depth + 1
params = cls._get_children_path_interval(parent.path)
extrand = 'AND path BETWEEN %s AND %s'
else:
depth = 1
params = []
extrand = ''
sql = 'SELECT * FROM %(table)s AS t1 INNER JOIN '\
' (SELECT '\
' SUBSTR(path, 1, %(subpathlen)s) AS subpath, '\
' COUNT(1)-1 AS count '\
' FROM %(table)s '\
' WHERE depth >= %(depth)s %(extrand)s'\
' GROUP BY subpath) AS t2 '\
' ON t1.path=t2.subpath '\
' ORDER BY t1.path' % {
'table': connection.ops.quote_name(cls._meta.db_table),
'subpathlen': depth * cls.steplen,
'depth': depth,
'extrand': extrand}
cursor = cls._get_database_cursor('write')
cursor.execute(sql, params)
ret = []
field_names = [field[0] for field in cursor.description]
for node_data in cursor.fetchall():
node = cls(**dict(zip(field_names, node_data[:-2])))
node.descendants_count = node_data[-1]
ret.append(node)
return ret
def get_depth(self):
""":returns: the depth (level) of the node"""
return self.depth
def get_siblings(self):
"""
:returns: A queryset of all the node's siblings, including the node
itself.
"""
qset = get_result_class(self.__class__).objects.filter(
depth=self.depth)
if self.depth > 1:
# making sure the non-root nodes share a parent
parentpath = self._get_basepath(self.path, self.depth - 1)
qset = qset.filter(
path__range=self._get_children_path_interval(parentpath))
return qset
def get_children(self):
""":returns: A queryset of all the node's children"""
if self.is_leaf():
return get_result_class(self.__class__).objects.none()
return get_result_class(self.__class__).objects.filter(
depth=self.depth + 1,
path__range=self._get_children_path_interval(self.path)
)
def get_next_sibling(self):
"""
:returns: The next node's sibling, or None if it was the rightmost
sibling.
"""
try:
return self.get_siblings().filter(path__gt=self.path)[0]
except IndexError:
return None
def get_descendants(self):
"""
:returns: A queryset of all the node's descendants as DFS, doesn't
include the node itself
"""
return self.__class__.get_tree(self).exclude(pk=self.pk)
def get_prev_sibling(self):
"""
:returns: The previous node's sibling, or None if it was the leftmost
sibling.
"""
try:
return self.get_siblings().filter(path__lt=self.path).reverse()[0]
except IndexError:
return None
def get_children_count(self):
"""
:returns: The number the node's children, calculated in the most
efficient possible way.
"""
return self.numchild
def is_sibling_of(self, node):
"""
:returns: ``True`` if the node is a sibling of another node given as an
argument, else, returns ``False``
"""
aux = self.depth == node.depth
# Check non-root nodes share a parent only if they have the same depth
if aux and self.depth > 1:
# making sure the non-root nodes share a parent
parentpath = self._get_basepath(self.path, self.depth - 1)
return aux and node.path.startswith(parentpath)
return aux
def is_child_of(self, node):
"""
:returns: ``True`` is the node if a child of another node given as an
argument, else, returns ``False``
"""
return (self.path.startswith(node.path) and
self.depth == node.depth + 1)
def is_descendant_of(self, node):
"""
:returns: ``True`` if the node is a descendant of another node given
as an argument, else, returns ``False``
"""
return self.path.startswith(node.path) and self.depth > node.depth
def add_child(self, **kwargs):
"""
Adds a child to the node.
This method saves the node in database. The object is populated as if via:
obj = self.__class__(**kwargs)
:raise PathOverflow: when no more child nodes can be added
"""
return MP_AddChildHandler(self, **kwargs).process()
def add_sibling(self, pos=None, **kwargs):
"""
Adds a new node as a sibling to the current node object.
This method saves the node in database. The object is populated as if via:
obj = self.__class__(**kwargs)
:raise PathOverflow: when the library can't make room for the
node's new position
"""
return MP_AddSiblingHandler(self, pos, **kwargs).process()
def get_root(self):
""":returns: the root node for the current node object."""
return get_result_class(self.__class__).objects.get(
path=self.path[0:self.steplen])
def is_root(self):
""":returns: True if the node is a root node (else, returns False)"""
return self.depth == 1
def is_leaf(self):
""":returns: True if the node is a leaf node (else, returns False)"""
return self.numchild == 0
def get_ancestors(self):
"""
:returns: A queryset containing the current node object's ancestors,
starting by the root node and descending to the parent.
"""
paths = [
self.path[0:pos]
for pos in range(0, len(self.path), self.steplen)[1:]
]
return get_result_class(self.__class__).objects.filter(
path__in=paths).order_by('depth')
def get_parent(self, update=False):
"""
:returns: the parent node of the current node object.
Caches the result in the object itself to help in loops.
"""
depth = int(len(self.path) / self.steplen)
if depth <= 1:
return
try:
if update:
del self._cached_parent_obj
else:
return self._cached_parent_obj
except AttributeError:
pass
parentpath = self._get_basepath(self.path, depth - 1)
self._cached_parent_obj = get_result_class(
self.__class__).objects.get(path=parentpath)
return self._cached_parent_obj
def move(self, target, pos=None):
"""
Moves the current node and all it's descendants to a new position
relative to another node.
:raise PathOverflow: when the library can't make room for the
node's new position
"""
return MP_MoveHandler(self, target, pos).process()
@classmethod
def _get_basepath(cls, path, depth):
""":returns: The base path of another path up to a given depth"""
if path:
return path[0:depth * cls.steplen]
return ''
@classmethod
def _get_path(cls, path, depth, newstep):
"""
Builds a path given some values
:param path: the base path
:param depth: the depth of the node
:param newstep: the value (integer) of the new step
"""
parentpath = cls._get_basepath(path, depth - 1)
key = cls._int2str(newstep)
return '{0}{1}{2}'.format(
parentpath,
cls.alphabet[0] * (cls.steplen - len(key)),
key
)
def _inc_path(self):
""":returns: The path of the next sibling of a given node path."""
newpos = self._str2int(self.path[-self.steplen:]) + 1
key = self._int2str(newpos)
if len(key) > self.steplen:
raise PathOverflow(_("Path Overflow from: '%s'" % (self.path, )))
return '{0}{1}{2}'.format(
self.path[:-self.steplen],
self.alphabet[0] * (self.steplen - len(key)),
key
)
def _get_lastpos_in_path(self):
""":returns: The integer value of the last step in a path."""
return self._str2int(self.path[-self.steplen:])
@classmethod
def _get_parent_path_from_path(cls, path):
""":returns: The parent path for a given path"""
if path:
return path[0:len(path) - cls.steplen]
return ''
@classmethod
def _get_children_path_interval(cls, path):
""":returns: An interval of all possible children paths for a node."""
return (path + cls.alphabet[0] * cls.steplen,
path + cls.alphabet[-1] * cls.steplen)
class Meta:
"""Abstract model."""
abstract = True
| {
"content_hash": "ac01ebbec3791d469be389df3e20f483",
"timestamp": "",
"source": "github",
"line_count": 1094,
"max_line_length": 94,
"avg_line_length": 37.73126142595978,
"alnum_prop": 0.5469257231455013,
"repo_name": "velfimov/django-treebeard",
"id": "d1756782e2a7a0860185555146ca4583316fe4de",
"size": "41278",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "treebeard/mp_tree.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1416"
},
{
"name": "HTML",
"bytes": "2880"
},
{
"name": "JavaScript",
"bytes": "14776"
},
{
"name": "Python",
"bytes": "248484"
},
{
"name": "Shell",
"bytes": "657"
}
],
"symlink_target": ""
} |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# from sqlalchemy import Column, Integer, String
# from app import db
engine = create_engine('sqlite:///database.db', echo=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
# Set your classes here.
'''
class User(Base):
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), unique=True)
email = db.Column(db.String(120), unique=True)
password = db.Column(db.String(30))
def __init__(self, name=None, password=None):
self.name = name
self.password = password
'''
# Create tables.
Base.metadata.create_all(bind=engine)
| {
"content_hash": "26410edf22f2b17436d4749b9ba21bf4",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 58,
"avg_line_length": 30.806451612903224,
"alnum_prop": 0.6544502617801047,
"repo_name": "andycasey/original-oracle",
"id": "e438d665203bc0c90c6304140ed9def0983cd84f",
"size": "955",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "flask-app/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AGS Script",
"bytes": "33792642"
},
{
"name": "Assembly",
"bytes": "1610"
},
{
"name": "C",
"bytes": "5169"
},
{
"name": "CSS",
"bytes": "677554"
},
{
"name": "FORTRAN",
"bytes": "377579"
},
{
"name": "IDL",
"bytes": "6113"
},
{
"name": "JavaScript",
"bytes": "4492601"
},
{
"name": "Perl",
"bytes": "447"
},
{
"name": "Python",
"bytes": "341576"
},
{
"name": "Shell",
"bytes": "1958"
}
],
"symlink_target": ""
} |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'MapView'
db.create_table(u'annotations_mapview', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('latitude', self.gf('django.db.models.fields.FloatField')()),
('longitude', self.gf('django.db.models.fields.FloatField')()),
('zoom', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal(u'annotations', ['MapView'])
def backwards(self, orm):
# Deleting model 'MapView'
db.delete_table(u'annotations_mapview')
models = {
u'annotations.mapview': {
'Meta': {'object_name': 'MapView'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latitude': ('django.db.models.fields.FloatField', [], {}),
'longitude': ('django.db.models.fields.FloatField', [], {}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'zoom': ('django.db.models.fields.IntegerField', [], {})
}
}
complete_apps = ['annotations'] | {
"content_hash": "504361b33c40e23bf5e6585514f42992",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 86,
"avg_line_length": 38,
"alnum_prop": 0.5903271692745377,
"repo_name": "douglay/map_annotator",
"id": "57946cbde2d1b6a1d8febb4e238b89b5630e61bf",
"size": "1430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "annotations/migrations/0002_add_map_view_model.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "2954"
}
],
"symlink_target": ""
} |
import argparse
import io
import os
import platform
import re
import subprocess
import sys
class TestFailedError(Exception):
pass
def escapeCmdArg(arg):
if '"' in arg or ' ' in arg:
return '"%s"' % arg.replace('"', '\\"')
else:
return arg
def run_command(cmd):
if sys.version_info[0] < 3:
cmd = list(map(lambda s: s.encode('utf-8'), cmd))
print(' '.join([escapeCmdArg(arg) for arg in cmd]))
if sys.version_info[0] < 3 or platform.system() == 'Windows':
return subprocess.check_output(cmd, stderr=subprocess.STDOUT)
else:
return subprocess.check_output(list(map(lambda s: s.encode('utf-8'), cmd)),
stderr=subprocess.STDOUT)
def parseLine(line, line_no, test_case, incremental_edit_args, reparse_args,
current_reparse_start):
pre_edit_line = ""
post_edit_line = ""
# We parse one tag at a time in the line while eating away a prefix of the
# line
while line:
# The regular expression to match the template markers
subst_re = re.compile(r'^(.*?)<<(.*?)<(.*?)\|\|\|(.*?)>>>(.*\n?)')
reparse_re = re.compile(r'^(.*?)<(/?)reparse ?(.*?)>(.*\n?)')
subst_match = subst_re.match(line)
reparse_match = reparse_re.match(line)
if subst_match and reparse_match:
# If both regex match use the one with the shorter prefix
if len(subst_match.group(1)) < len(reparse_match.group(1)):
reparse_match = None
else:
subst_match = None
if subst_match:
prefix = subst_match.group(1)
match_test_case = subst_match.group(2)
pre_edit = subst_match.group(3)
post_edit = subst_match.group(4)
suffix = subst_match.group(5)
if match_test_case == test_case:
# Compute the -incremental-edit argument for swift-syntax-test
column = len(pre_edit_line) + len(prefix) + 1
edit_arg = '%d:%d-%d:%d=%s' % \
(line_no, column, line_no, column + len(pre_edit.encode('utf-8')),
post_edit)
incremental_edit_args.append('-incremental-edit')
incremental_edit_args.append(edit_arg)
pre_edit_line += prefix + pre_edit
post_edit_line += prefix + post_edit
else:
# For different test cases just take the pre-edit text
pre_edit_line += prefix + pre_edit
post_edit_line += prefix + pre_edit
line = suffix
elif reparse_match:
prefix = reparse_match.group(1)
is_closing = len(reparse_match.group(2)) > 0
match_test_case = reparse_match.group(3)
suffix = reparse_match.group(4)
if match_test_case == test_case:
column = len(post_edit_line) + len(prefix) + 1
if is_closing:
if not current_reparse_start:
raise TestFailedError('Closing unopened reparse tag '
'in line %d' % line_no)
reparse_args.append('-reparse-region')
reparse_args.append(
'%d:%d-%d:%d' % (current_reparse_start[0],
current_reparse_start[1],
line_no, column))
current_reparse_start = None
else:
if current_reparse_start:
raise TestFailedError('Opening nested reparse tags '
'for the same test case in line '
'%d' % line_no)
current_reparse_start = [line_no, column]
pre_edit_line += prefix
post_edit_line += prefix
line = suffix
else:
pre_edit_line += line
post_edit_line += line
# Nothing more to do
line = ''
return (pre_edit_line.encode('utf-8'),
post_edit_line.encode('utf-8'),
current_reparse_start)
def prepareForIncrParse(test_file, test_case, pre_edit_file, post_edit_file,
incremental_edit_args, reparse_args):
with io.open(test_file, mode='r', encoding='utf-8',
newline='\n') as test_file_handle, \
io.open(pre_edit_file, mode='w+', encoding='utf-8',
newline='\n') as pre_edit_file_handle, \
io.open(post_edit_file, mode='w+', encoding='utf-8',
newline='\n') as post_edit_file_handle:
current_reparse_start = None
line_no = 1
for line in test_file_handle.readlines():
parseLineRes = parseLine(line, line_no, test_case,
incremental_edit_args,
reparse_args, current_reparse_start)
(pre_edit_line, post_edit_line, current_reparse_start) = \
parseLineRes
pre_edit_file_handle.write(pre_edit_line.decode('utf-8'))
post_edit_file_handle.write(post_edit_line.decode('utf-8'))
line_no += 1
if current_reparse_start:
raise TestFailedError('Unclosed reparse tag for test case %s' %
test_case)
def serializeIncrParseMarkupFile(test_file, test_case, mode,
omit_node_ids, output_file, diags_output_file,
temp_dir, swift_syntax_test,
print_visual_reuse_info):
test_file_name = os.path.basename(test_file)
pre_edit_file = temp_dir + '/' + test_file_name + '.' + test_case + \
'.pre.swift'
post_edit_file = temp_dir + '/' + test_file_name + '.' + test_case + \
'.post.swift'
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
# =========================================================================
# First generate the pre-edit and post-edit Swift file and gather the edits
# and expected reparse regions. This is the parser for the special edit
# markup for testing incremental parsing
# =========================================================================
# Gather command line arguments for swift-syntax-test specifiying the
# performed edits in this list
incremental_edit_args = []
reparse_args = []
prepareForIncrParse(test_file, test_case, pre_edit_file, post_edit_file,
incremental_edit_args, reparse_args)
# =========================================================================
# Now generate the requested serialized file
# =========================================================================
# Build the command to serialize the tree depending on the command line
# arguments
try:
command = [
swift_syntax_test,
'-serialize-raw-tree',
'-output-filename', output_file
]
if diags_output_file:
command.extend(['-diags-output-filename', diags_output_file])
if omit_node_ids:
command.extend(['-omit-node-ids'])
if mode == 'pre-edit':
command.extend(['-input-source-filename', pre_edit_file])
elif mode == 'post-edit':
command.extend(['-input-source-filename', post_edit_file])
elif mode == 'incremental':
# We need to build the syntax tree of the pre-edit file first so
# that we can pass it to swift-syntax-test to perform incremental
# parsing
pre_edit_tree_file = pre_edit_file + '.serialized.json'
run_command([swift_syntax_test] +
['-serialize-raw-tree'] +
['-input-source-filename', pre_edit_file] +
['-output-filename', pre_edit_tree_file])
# Then perform incremental parsing with the old syntax tree on the
# post-edit file
command.extend(['-input-source-filename', post_edit_file])
command.extend(['-old-syntax-tree-filename',
pre_edit_tree_file])
command.extend(['--old-source-filename', pre_edit_file])
command.extend(incremental_edit_args)
command.extend(reparse_args)
if print_visual_reuse_info:
command.extend([
'-print-visual-reuse-info',
'-force-colored-output'
])
else:
raise ValueError('Unknown mode "%s"' % mode)
output = run_command(command)
if print_visual_reuse_info:
print(output)
except subprocess.CalledProcessError as e:
raise TestFailedError(e.output.decode('utf-8'))
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='Utility for testing incremental syntax parsing',
epilog='''
This utility can parse a special markup to dedicate a pre-edit and a
post-edit version of a file simulateously and generate a serialized version
of the libSyntax tree by parsing either the pre-edit file, the post-edit
file or the edits that are required to retrieve the post-edit file from the
pre-edit file incrementally.
To generate the pre-edit and the post-edit file from the template, it
operates on markers of the form:
<<test_case<pre|||post>>>
These placeholders are replaced by:
- 'pre' if a different test case than 'test_case' is run
- 'pre' for the pre-edit version of 'test_case'
- 'post' for the post-edit version of 'test_case''')
parser.add_argument(
'file', type=argparse.FileType(),
help='The template file to test')
parser.add_argument(
'--test-case', default='',
help='The test case to execute. If no test case is specified all \
unnamed substitutions are applied')
parser.add_argument(
'--mode', choices=['pre-edit', 'incremental', 'post-edit'],
required=True, help='''
The type of parsing to perform:
- pre-edit: Serialize the syntax tree when parsing the pre-edit file \
from scratch
- incremental: Serialize the syntax tree that results from parsing the \
edits between the pre-edit and post-edit file incrementally
- post-edit: Serialize the syntax tree that results from parsing the \
post-edit file from scratch
''')
parser.add_argument(
'--omit-node-ids', default=False, action='store_true',
help='Don\'t include the ids of the nodes in the serialized syntax \
tree')
parser.add_argument(
'--output-file', required=True,
help='The file to which the serialized tree shall be written.')
parser.add_argument(
'--temp-dir', required=True,
help='A temporary directory where pre-edit and post-edit files can be \
saved')
parser.add_argument(
'--swift-syntax-test', required=True,
help='The path to swift-syntax-test')
parser.add_argument(
'--print-visual-reuse-info', default=False, action='store_true',
help='Print visual reuse information about the incremental parse \
instead of diffing the syntax trees. This option is intended \
for debug purposes only.')
args = parser.parse_args(sys.argv[1:])
test_file = args.file.name
test_case = args.test_case
mode = args.mode
omit_node_ids = args.omit_node_ids
output_file = args.output_file
temp_dir = args.temp_dir
swift_syntax_test = args.swift_syntax_test
visual_reuse_info = args.print_visual_reuse_info
try:
serializeIncrParseMarkupFile(test_file=test_file,
test_case=test_case,
mode=mode,
omit_node_ids=omit_node_ids,
output_file=output_file,
diags_output_file=None,
temp_dir=temp_dir,
swift_syntax_test=swift_syntax_test,
print_visual_reuse_info=visual_reuse_info)
except TestFailedError as e:
print(e.message, file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()
| {
"content_hash": "b7447cb0a7fa052d8157756276ba6688",
"timestamp": "",
"source": "github",
"line_count": 312,
"max_line_length": 86,
"avg_line_length": 40.41025641025641,
"alnum_prop": 0.5398159898477157,
"repo_name": "gregomni/swift",
"id": "654887b12efde541787933c20e7cbe4edcc8ca6c",
"size": "12632",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "utils/incrparse/test_util.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "45870"
},
{
"name": "C",
"bytes": "5439487"
},
{
"name": "C++",
"bytes": "46893530"
},
{
"name": "CMake",
"bytes": "689115"
},
{
"name": "D",
"bytes": "1107"
},
{
"name": "DTrace",
"bytes": "2593"
},
{
"name": "Emacs Lisp",
"bytes": "57594"
},
{
"name": "LLVM",
"bytes": "74528"
},
{
"name": "Makefile",
"bytes": "2361"
},
{
"name": "Objective-C",
"bytes": "459842"
},
{
"name": "Objective-C++",
"bytes": "159687"
},
{
"name": "Python",
"bytes": "1966291"
},
{
"name": "Roff",
"bytes": "3683"
},
{
"name": "Ruby",
"bytes": "2132"
},
{
"name": "Shell",
"bytes": "214878"
},
{
"name": "Swift",
"bytes": "38374455"
},
{
"name": "Vim script",
"bytes": "20025"
},
{
"name": "sed",
"bytes": "1050"
}
],
"symlink_target": ""
} |
"""Tests for Building Blocks of the TensorFlow Debugger CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import stat
import tempfile
import numpy as np
from tensorflow.python.client import pywrap_tf_session
from tensorflow.python.debug.cli import debugger_cli_common
from tensorflow.python.framework import test_util
from tensorflow.python.platform import gfile
from tensorflow.python.platform import googletest
class CommandLineExitTest(test_util.TensorFlowTestCase):
def testConstructionWithoutToken(self):
exit_exc = debugger_cli_common.CommandLineExit()
self.assertTrue(isinstance(exit_exc, Exception))
def testConstructionWithToken(self):
exit_exc = debugger_cli_common.CommandLineExit(exit_token={"foo": "bar"})
self.assertTrue(isinstance(exit_exc, Exception))
self.assertEqual({"foo": "bar"}, exit_exc.exit_token)
class RichTextLinesTest(test_util.TensorFlowTestCase):
def testRichTextLinesConstructorComplete(self):
# Test RichTextLines constructor.
screen_output = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]},
annotations={0: "longer wavelength",
1: "shorter wavelength"})
self.assertEqual(2, len(screen_output.lines))
self.assertEqual(2, len(screen_output.font_attr_segs))
self.assertEqual(1, len(screen_output.font_attr_segs[0]))
self.assertEqual(1, len(screen_output.font_attr_segs[1]))
self.assertEqual(2, len(screen_output.annotations))
self.assertEqual(2, screen_output.num_lines())
def testRichTextLinesConstructorWithInvalidType(self):
with self.assertRaisesRegexp(ValueError, "Unexpected type in lines"):
debugger_cli_common.RichTextLines(123)
def testRichTextLinesConstructorWithString(self):
# Test constructing a RichTextLines object with a string, instead of a list
# of strings.
screen_output = debugger_cli_common.RichTextLines(
"Roses are red",
font_attr_segs={0: [(0, 5, "red")]},
annotations={0: "longer wavelength"})
self.assertEqual(1, len(screen_output.lines))
self.assertEqual(1, len(screen_output.font_attr_segs))
self.assertEqual(1, len(screen_output.font_attr_segs[0]))
self.assertEqual(1, len(screen_output.annotations))
def testRichLinesAppendRichLine(self):
rtl = debugger_cli_common.RichTextLines(
"Roses are red",
font_attr_segs={0: [(0, 5, "red")]})
rtl.append_rich_line(debugger_cli_common.RichLine("Violets are ") +
debugger_cli_common.RichLine("blue", "blue"))
self.assertEqual(2, len(rtl.lines))
self.assertEqual(2, len(rtl.font_attr_segs))
self.assertEqual(1, len(rtl.font_attr_segs[0]))
self.assertEqual(1, len(rtl.font_attr_segs[1]))
def testRichLineLenMethodWorks(self):
self.assertEqual(0, len(debugger_cli_common.RichLine()))
self.assertEqual(0, len(debugger_cli_common.RichLine("")))
self.assertEqual(1, len(debugger_cli_common.RichLine("x")))
self.assertEqual(6, len(debugger_cli_common.RichLine("x y z ", "blue")))
def testRichTextLinesConstructorIncomplete(self):
# Test RichTextLines constructor, with incomplete keyword arguments.
screen_output = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]})
self.assertEqual(2, len(screen_output.lines))
self.assertEqual(2, len(screen_output.font_attr_segs))
self.assertEqual(1, len(screen_output.font_attr_segs[0]))
self.assertEqual(1, len(screen_output.font_attr_segs[1]))
self.assertEqual({}, screen_output.annotations)
def testModifyRichTextLinesObject(self):
screen_output = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"])
self.assertEqual(2, len(screen_output.lines))
screen_output.lines.append("Sugar is sweet")
self.assertEqual(3, len(screen_output.lines))
def testMergeRichTextLines(self):
screen_output_1 = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]},
annotations={0: "longer wavelength",
1: "shorter wavelength"})
screen_output_2 = debugger_cli_common.RichTextLines(
["Lilies are white", "Sunflowers are yellow"],
font_attr_segs={0: [(0, 6, "white")],
1: [(0, 7, "yellow")]},
annotations={
"metadata": "foo",
0: "full spectrum",
1: "medium wavelength"
})
screen_output_1.extend(screen_output_2)
self.assertEqual(4, screen_output_1.num_lines())
self.assertEqual([
"Roses are red", "Violets are blue", "Lilies are white",
"Sunflowers are yellow"
], screen_output_1.lines)
self.assertEqual({
0: [(0, 5, "red")],
1: [(0, 7, "blue")],
2: [(0, 6, "white")],
3: [(0, 7, "yellow")]
}, screen_output_1.font_attr_segs)
self.assertEqual({
0: [(0, 5, "red")],
1: [(0, 7, "blue")],
2: [(0, 6, "white")],
3: [(0, 7, "yellow")]
}, screen_output_1.font_attr_segs)
self.assertEqual({
"metadata": "foo",
0: "longer wavelength",
1: "shorter wavelength",
2: "full spectrum",
3: "medium wavelength"
}, screen_output_1.annotations)
def testMergeRichTextLinesEmptyOther(self):
screen_output_1 = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]},
annotations={0: "longer wavelength",
1: "shorter wavelength"})
screen_output_2 = debugger_cli_common.RichTextLines([])
screen_output_1.extend(screen_output_2)
self.assertEqual(2, screen_output_1.num_lines())
self.assertEqual(["Roses are red", "Violets are blue"],
screen_output_1.lines)
self.assertEqual({
0: [(0, 5, "red")],
1: [(0, 7, "blue")],
}, screen_output_1.font_attr_segs)
self.assertEqual({
0: [(0, 5, "red")],
1: [(0, 7, "blue")],
}, screen_output_1.font_attr_segs)
self.assertEqual({
0: "longer wavelength",
1: "shorter wavelength",
}, screen_output_1.annotations)
def testMergeRichTextLinesEmptySelf(self):
screen_output_1 = debugger_cli_common.RichTextLines([])
screen_output_2 = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]},
annotations={0: "longer wavelength",
1: "shorter wavelength"})
screen_output_1.extend(screen_output_2)
self.assertEqual(2, screen_output_1.num_lines())
self.assertEqual(["Roses are red", "Violets are blue"],
screen_output_1.lines)
self.assertEqual({
0: [(0, 5, "red")],
1: [(0, 7, "blue")],
}, screen_output_1.font_attr_segs)
self.assertEqual({
0: [(0, 5, "red")],
1: [(0, 7, "blue")],
}, screen_output_1.font_attr_segs)
self.assertEqual({
0: "longer wavelength",
1: "shorter wavelength",
}, screen_output_1.annotations)
def testAppendALineWithAttributeSegmentsWorks(self):
screen_output_1 = debugger_cli_common.RichTextLines(
["Roses are red"],
font_attr_segs={0: [(0, 5, "red")]},
annotations={0: "longer wavelength"})
screen_output_1.append("Violets are blue", [(0, 7, "blue")])
self.assertEqual(["Roses are red", "Violets are blue"],
screen_output_1.lines)
self.assertEqual({
0: [(0, 5, "red")],
1: [(0, 7, "blue")],
}, screen_output_1.font_attr_segs)
def testPrependALineWithAttributeSegmentsWorks(self):
screen_output_1 = debugger_cli_common.RichTextLines(
["Roses are red"],
font_attr_segs={0: [(0, 5, "red")]},
annotations={0: "longer wavelength"})
screen_output_1.prepend("Violets are blue", font_attr_segs=[(0, 7, "blue")])
self.assertEqual(["Violets are blue", "Roses are red"],
screen_output_1.lines)
self.assertEqual({
0: [(0, 7, "blue")],
1: [(0, 5, "red")],
}, screen_output_1.font_attr_segs)
def testWriteToFileSucceeds(self):
screen_output = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]})
file_path = tempfile.mktemp()
screen_output.write_to_file(file_path)
with gfile.Open(file_path, "r") as f:
self.assertEqual("Roses are red\nViolets are blue\n", f.read())
# Clean up.
gfile.Remove(file_path)
def testAttemptToWriteToADirectoryFails(self):
screen_output = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]})
with self.assertRaises(Exception):
screen_output.write_to_file("/")
def testAttemptToWriteToFileInNonexistentDirectoryFails(self):
screen_output = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]})
file_path = os.path.join(tempfile.mkdtemp(), "foo", "bar.txt")
with self.assertRaises(Exception):
screen_output.write_to_file(file_path)
class CommandHandlerRegistryTest(test_util.TensorFlowTestCase):
def setUp(self):
self._intentional_error_msg = "Intentionally raised exception"
def _noop_handler(self, argv, screen_info=None):
# A handler that does nothing other than returning "Done."
return debugger_cli_common.RichTextLines(["Done."])
def _handler_raising_exception(self, argv, screen_info=None):
# A handler that intentionally raises an exception.
raise RuntimeError(self._intentional_error_msg)
def _handler_returning_wrong_type(self, argv, screen_info=None):
# A handler that returns a wrong type, instead of the correct type
# (RichTextLines).
return "Hello"
def _echo_screen_cols(self, argv, screen_info=None):
# A handler that uses screen_info.
return debugger_cli_common.RichTextLines(
["cols = %d" % screen_info["cols"]])
def _exiting_handler(self, argv, screen_info=None):
"""A handler that exits with an exit token."""
if argv:
exit_token = argv[0]
else:
exit_token = None
raise debugger_cli_common.CommandLineExit(exit_token=exit_token)
def testRegisterEmptyCommandPrefix(self):
registry = debugger_cli_common.CommandHandlerRegistry()
# Attempt to register an empty-string as a command prefix should trigger
# an exception.
with self.assertRaisesRegexp(ValueError, "Empty command prefix"):
registry.register_command_handler("", self._noop_handler, "")
def testRegisterAndInvokeHandler(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler("noop", self._noop_handler, "")
self.assertTrue(registry.is_registered("noop"))
self.assertFalse(registry.is_registered("beep"))
cmd_output = registry.dispatch_command("noop", [])
self.assertEqual(["Done."], cmd_output.lines)
# Attempt to invoke an unregistered command prefix should trigger an
# exception.
with self.assertRaisesRegexp(ValueError, "No handler is registered"):
registry.dispatch_command("beep", [])
# Empty command prefix should trigger an exception.
with self.assertRaisesRegexp(ValueError, "Prefix is empty"):
registry.dispatch_command("", [])
def testExitingHandler(self):
"""Test that exit exception is correctly raised."""
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler("exit", self._exiting_handler, "")
self.assertTrue(registry.is_registered("exit"))
exit_token = None
try:
registry.dispatch_command("exit", ["foo"])
except debugger_cli_common.CommandLineExit as e:
exit_token = e.exit_token
self.assertEqual("foo", exit_token)
def testInvokeHandlerWithScreenInfo(self):
registry = debugger_cli_common.CommandHandlerRegistry()
# Register and invoke a command handler that uses screen_info.
registry.register_command_handler("cols", self._echo_screen_cols, "")
cmd_output = registry.dispatch_command(
"cols", [], screen_info={"cols": 100})
self.assertEqual(["cols = 100"], cmd_output.lines)
def testRegisterAndInvokeHandlerWithAliases(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler(
"noop", self._noop_handler, "", prefix_aliases=["n", "NOOP"])
# is_registered() should work for full prefix and aliases.
self.assertTrue(registry.is_registered("noop"))
self.assertTrue(registry.is_registered("n"))
self.assertTrue(registry.is_registered("NOOP"))
cmd_output = registry.dispatch_command("n", [])
self.assertEqual(["Done."], cmd_output.lines)
cmd_output = registry.dispatch_command("NOOP", [])
self.assertEqual(["Done."], cmd_output.lines)
def testHandlerWithWrongReturnType(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler("wrong_return",
self._handler_returning_wrong_type, "")
# If the command handler fails to return a RichTextLines instance, an error
# should be triggered.
with self.assertRaisesRegexp(
ValueError,
"Return value from command handler.*is not None or a RichTextLines "
"instance"):
registry.dispatch_command("wrong_return", [])
def testRegisterDuplicateHandlers(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler("noop", self._noop_handler, "")
# Registering the same command prefix more than once should trigger an
# exception.
with self.assertRaisesRegexp(
ValueError, "A handler is already registered for command prefix"):
registry.register_command_handler("noop", self._noop_handler, "")
cmd_output = registry.dispatch_command("noop", [])
self.assertEqual(["Done."], cmd_output.lines)
def testRegisterDuplicateAliases(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler(
"noop", self._noop_handler, "", prefix_aliases=["n"])
# Clash with existing alias.
with self.assertRaisesRegexp(ValueError,
"clashes with existing prefixes or aliases"):
registry.register_command_handler(
"cols", self._echo_screen_cols, "", prefix_aliases=["n"])
# The name clash should have prevent the handler from being registered.
self.assertFalse(registry.is_registered("cols"))
# Aliases can also clash with command prefixes.
with self.assertRaisesRegexp(ValueError,
"clashes with existing prefixes or aliases"):
registry.register_command_handler(
"cols", self._echo_screen_cols, "", prefix_aliases=["noop"])
self.assertFalse(registry.is_registered("cols"))
def testDispatchHandlerRaisingException(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler("raise_exception",
self._handler_raising_exception, "")
# The registry should catch and wrap exceptions that occur during command
# handling.
cmd_output = registry.dispatch_command("raise_exception", [])
# The error output contains a stack trace.
# So the line count should be >= 2.
self.assertGreater(len(cmd_output.lines), 2)
self.assertTrue(cmd_output.lines[0].startswith(
"Error occurred during handling of command"))
self.assertTrue(cmd_output.lines[1].endswith(self._intentional_error_msg))
def testRegisterNonCallableHandler(self):
registry = debugger_cli_common.CommandHandlerRegistry()
# Attempt to register a non-callable handler should fail.
with self.assertRaisesRegexp(ValueError, "handler is not callable"):
registry.register_command_handler("non_callable", 1, "")
def testRegisterHandlerWithInvalidHelpInfoType(self):
registry = debugger_cli_common.CommandHandlerRegistry()
with self.assertRaisesRegexp(ValueError, "help_info is not a str"):
registry.register_command_handler("noop", self._noop_handler, ["foo"])
def testGetHelpFull(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler(
"noop",
self._noop_handler,
"No operation.\nI.e., do nothing.",
prefix_aliases=["n", "NOOP"])
registry.register_command_handler(
"cols",
self._echo_screen_cols,
"Show screen width in number of columns.",
prefix_aliases=["c"])
help_lines = registry.get_help().lines
# The help info should list commands in alphabetically sorted order,
# regardless of order in which the commands are reigstered.
self.assertEqual("cols", help_lines[0])
self.assertTrue(help_lines[1].endswith("Aliases: c"))
self.assertFalse(help_lines[2])
self.assertTrue(help_lines[3].endswith(
"Show screen width in number of columns."))
self.assertFalse(help_lines[4])
self.assertFalse(help_lines[5])
# The default help command should appear in the help output.
self.assertEqual("help", help_lines[6])
self.assertEqual("noop", help_lines[12])
self.assertTrue(help_lines[13].endswith("Aliases: n, NOOP"))
self.assertFalse(help_lines[14])
self.assertTrue(help_lines[15].endswith("No operation."))
self.assertTrue(help_lines[16].endswith("I.e., do nothing."))
def testGetHelpSingleCommand(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler(
"noop",
self._noop_handler,
"No operation.\nI.e., do nothing.",
prefix_aliases=["n", "NOOP"])
registry.register_command_handler(
"cols",
self._echo_screen_cols,
"Show screen width in number of columns.",
prefix_aliases=["c"])
# Get help info for one of the two commands, using full prefix.
help_lines = registry.get_help("cols").lines
self.assertTrue(help_lines[0].endswith("cols"))
self.assertTrue(help_lines[1].endswith("Aliases: c"))
self.assertFalse(help_lines[2])
self.assertTrue(help_lines[3].endswith(
"Show screen width in number of columns."))
# Get help info for one of the two commands, using alias.
help_lines = registry.get_help("c").lines
self.assertTrue(help_lines[0].endswith("cols"))
self.assertTrue(help_lines[1].endswith("Aliases: c"))
self.assertFalse(help_lines[2])
self.assertTrue(help_lines[3].endswith(
"Show screen width in number of columns."))
# Get help info for a nonexistent command.
help_lines = registry.get_help("foo").lines
self.assertEqual("Invalid command prefix: \"foo\"", help_lines[0])
def testHelpCommandWithoutIntro(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler(
"noop",
self._noop_handler,
"No operation.\nI.e., do nothing.",
prefix_aliases=["n", "NOOP"])
registry.register_command_handler(
"cols",
self._echo_screen_cols,
"Show screen width in number of columns.",
prefix_aliases=["c"])
# Get help for all commands.
output = registry.dispatch_command("help", [])
self.assertEqual(["cols", " Aliases: c", "",
" Show screen width in number of columns.", "", "",
"help", " Aliases: h", "", " Print this help message.",
"", "", "noop", " Aliases: n, NOOP", "",
" No operation.", " I.e., do nothing.", "", "",
"version", " Aliases: ver", "",
" Print the versions of TensorFlow and its key "
"dependencies.", "", ""],
output.lines)
# Get help for one specific command prefix.
output = registry.dispatch_command("help", ["noop"])
self.assertEqual(["noop", " Aliases: n, NOOP", "", " No operation.",
" I.e., do nothing."], output.lines)
# Get help for a nonexistent command prefix.
output = registry.dispatch_command("help", ["foo"])
self.assertEqual(["Invalid command prefix: \"foo\""], output.lines)
def testHelpCommandWithIntro(self):
registry = debugger_cli_common.CommandHandlerRegistry()
registry.register_command_handler(
"noop",
self._noop_handler,
"No operation.\nI.e., do nothing.",
prefix_aliases=["n", "NOOP"])
help_intro = debugger_cli_common.RichTextLines(
["Introductory comments.", ""])
registry.set_help_intro(help_intro)
output = registry.dispatch_command("help", [])
self.assertEqual(help_intro.lines + [
"help", " Aliases: h", "", " Print this help message.", "", "",
"noop", " Aliases: n, NOOP", "", " No operation.",
" I.e., do nothing.", "", "",
"version", " Aliases: ver", "",
" Print the versions of TensorFlow and its key dependencies.", "", ""
], output.lines)
class RegexFindTest(test_util.TensorFlowTestCase):
def setUp(self):
self._orig_screen_output = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"])
def testRegexFindWithoutExistingFontAttrSegs(self):
new_screen_output = debugger_cli_common.regex_find(self._orig_screen_output,
"are", "yellow")
self.assertEqual(2, len(new_screen_output.font_attr_segs))
self.assertEqual([(6, 9, "yellow")], new_screen_output.font_attr_segs[0])
self.assertEqual([(8, 11, "yellow")], new_screen_output.font_attr_segs[1])
# Check field in annotations carrying a list of matching line indices.
self.assertEqual([0, 1], new_screen_output.annotations[
debugger_cli_common.REGEX_MATCH_LINES_KEY])
def testRegexFindWithExistingFontAttrSegs(self):
# Add a font attribute segment first.
self._orig_screen_output.font_attr_segs[0] = [(9, 12, "red")]
self.assertEqual(1, len(self._orig_screen_output.font_attr_segs))
new_screen_output = debugger_cli_common.regex_find(self._orig_screen_output,
"are", "yellow")
self.assertEqual(2, len(new_screen_output.font_attr_segs))
self.assertEqual([(6, 9, "yellow"), (9, 12, "red")],
new_screen_output.font_attr_segs[0])
self.assertEqual([0, 1], new_screen_output.annotations[
debugger_cli_common.REGEX_MATCH_LINES_KEY])
def testRegexFindWithNoMatches(self):
new_screen_output = debugger_cli_common.regex_find(self._orig_screen_output,
"infrared", "yellow")
self.assertEqual({}, new_screen_output.font_attr_segs)
self.assertEqual([], new_screen_output.annotations[
debugger_cli_common.REGEX_MATCH_LINES_KEY])
def testInvalidRegex(self):
with self.assertRaisesRegexp(ValueError, "Invalid regular expression"):
debugger_cli_common.regex_find(self._orig_screen_output, "[", "yellow")
def testRegexFindOnPrependedLinesWorks(self):
rich_lines = debugger_cli_common.RichTextLines(["Violets are blue"])
rich_lines.prepend(["Roses are red"])
searched_rich_lines = debugger_cli_common.regex_find(
rich_lines, "red", "bold")
self.assertEqual(
{0: [(10, 13, "bold")]}, searched_rich_lines.font_attr_segs)
rich_lines = debugger_cli_common.RichTextLines(["Violets are blue"])
rich_lines.prepend(["A poem"], font_attr_segs=[(0, 1, "underline")])
searched_rich_lines = debugger_cli_common.regex_find(
rich_lines, "poem", "italic")
self.assertEqual(
{0: [(0, 1, "underline"), (2, 6, "italic")]},
searched_rich_lines.font_attr_segs)
class WrapScreenOutputTest(test_util.TensorFlowTestCase):
def setUp(self):
self._orig_screen_output = debugger_cli_common.RichTextLines(
["Folk song:", "Roses are red", "Violets are blue"],
font_attr_segs={1: [(0, 5, "red"), (6, 9, "gray"), (10, 12, "red"),
(12, 13, "crimson")],
2: [(0, 7, "blue"), (8, 11, "gray"), (12, 14, "blue"),
(14, 16, "indigo")]},
annotations={1: "longer wavelength",
2: "shorter wavelength"})
def testNoActualWrapping(self):
# Large column limit should lead to no actual wrapping.
out, new_line_indices = debugger_cli_common.wrap_rich_text_lines(
self._orig_screen_output, 100)
self.assertEqual(self._orig_screen_output.lines, out.lines)
self.assertEqual(self._orig_screen_output.font_attr_segs,
out.font_attr_segs)
self.assertEqual(self._orig_screen_output.annotations, out.annotations)
self.assertEqual(new_line_indices, [0, 1, 2])
def testWrappingWithAttrCutoff(self):
out, new_line_indices = debugger_cli_common.wrap_rich_text_lines(
self._orig_screen_output, 11)
# Add non-row-index field to out.
out.annotations["metadata"] = "foo"
# Check wrapped text.
self.assertEqual(5, len(out.lines))
self.assertEqual("Folk song:", out.lines[0])
self.assertEqual("Roses are r", out.lines[1])
self.assertEqual("ed", out.lines[2])
self.assertEqual("Violets are", out.lines[3])
self.assertEqual(" blue", out.lines[4])
# Check wrapped font_attr_segs.
self.assertFalse(0 in out.font_attr_segs)
self.assertEqual([(0, 5, "red"), (6, 9, "gray"), (10, 11, "red")],
out.font_attr_segs[1])
self.assertEqual([(0, 1, "red"), (1, 2, "crimson")], out.font_attr_segs[2])
self.assertEqual([(0, 7, "blue"), (8, 11, "gray")], out.font_attr_segs[3])
self.assertEqual([(1, 3, "blue"), (3, 5, "indigo")], out.font_attr_segs[4])
# Check annotations.
self.assertFalse(0 in out.annotations)
self.assertEqual("longer wavelength", out.annotations[1])
self.assertFalse(2 in out.annotations)
self.assertEqual("shorter wavelength", out.annotations[3])
self.assertFalse(4 in out.annotations)
# Chec that the non-row-index field is present in output.
self.assertEqual("foo", out.annotations["metadata"])
self.assertEqual(new_line_indices, [0, 1, 3])
def testWrappingWithMultipleAttrCutoff(self):
self._orig_screen_output = debugger_cli_common.RichTextLines(
["Folk song:", "Roses are red", "Violets are blue"],
font_attr_segs={1: [(0, 12, "red")],
2: [(1, 16, "blue")]},
annotations={1: "longer wavelength",
2: "shorter wavelength"})
out, new_line_indices = debugger_cli_common.wrap_rich_text_lines(
self._orig_screen_output, 5)
# Check wrapped text.
self.assertEqual(9, len(out.lines))
self.assertEqual("Folk ", out.lines[0])
self.assertEqual("song:", out.lines[1])
self.assertEqual("Roses", out.lines[2])
self.assertEqual(" are ", out.lines[3])
self.assertEqual("red", out.lines[4])
self.assertEqual("Viole", out.lines[5])
self.assertEqual("ts ar", out.lines[6])
self.assertEqual("e blu", out.lines[7])
self.assertEqual("e", out.lines[8])
# Check wrapped font_attr_segs.
self.assertFalse(0 in out.font_attr_segs)
self.assertFalse(1 in out.font_attr_segs)
self.assertEqual([(0, 5, "red")], out.font_attr_segs[2])
self.assertEqual([(0, 5, "red")], out.font_attr_segs[3])
self.assertEqual([(0, 2, "red")], out.font_attr_segs[4])
self.assertEqual([(1, 5, "blue")], out.font_attr_segs[5])
self.assertEqual([(0, 5, "blue")], out.font_attr_segs[6])
self.assertEqual([(0, 5, "blue")], out.font_attr_segs[7])
self.assertEqual([(0, 1, "blue")], out.font_attr_segs[8])
# Check annotations.
self.assertFalse(0 in out.annotations)
self.assertFalse(1 in out.annotations)
self.assertEqual("longer wavelength", out.annotations[2])
self.assertFalse(3 in out.annotations)
self.assertFalse(4 in out.annotations)
self.assertEqual("shorter wavelength", out.annotations[5])
self.assertFalse(6 in out.annotations)
self.assertFalse(7 in out.annotations)
self.assertFalse(8 in out.annotations)
self.assertEqual(new_line_indices, [0, 2, 5])
def testWrappingInvalidArguments(self):
with self.assertRaisesRegexp(ValueError,
"Invalid type of input screen_output"):
debugger_cli_common.wrap_rich_text_lines("foo", 12)
with self.assertRaisesRegexp(ValueError, "Invalid type of input cols"):
debugger_cli_common.wrap_rich_text_lines(
debugger_cli_common.RichTextLines(["foo", "bar"]), "12")
def testWrappingEmptyInput(self):
out, new_line_indices = debugger_cli_common.wrap_rich_text_lines(
debugger_cli_common.RichTextLines([]), 10)
self.assertEqual([], out.lines)
self.assertEqual([], new_line_indices)
class SliceRichTextLinesTest(test_util.TensorFlowTestCase):
def setUp(self):
self._original = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]},
annotations={
0: "longer wavelength",
1: "shorter wavelength",
"foo_metadata": "bar"
})
def testSliceBeginning(self):
sliced = self._original.slice(0, 1)
self.assertEqual(["Roses are red"], sliced.lines)
self.assertEqual({0: [(0, 5, "red")]}, sliced.font_attr_segs)
# Non-line-number metadata should be preseved.
self.assertEqual({
0: "longer wavelength",
"foo_metadata": "bar"
}, sliced.annotations)
self.assertEqual(1, sliced.num_lines())
def testSliceEnd(self):
sliced = self._original.slice(1, 2)
self.assertEqual(["Violets are blue"], sliced.lines)
# The line index should have changed from 1 to 0.
self.assertEqual({0: [(0, 7, "blue")]}, sliced.font_attr_segs)
self.assertEqual({
0: "shorter wavelength",
"foo_metadata": "bar"
}, sliced.annotations)
self.assertEqual(1, sliced.num_lines())
def testAttemptSliceWithNegativeIndex(self):
with self.assertRaisesRegexp(ValueError, "Encountered negative index"):
self._original.slice(0, -1)
class TabCompletionRegistryTest(test_util.TensorFlowTestCase):
def setUp(self):
self._tc_reg = debugger_cli_common.TabCompletionRegistry()
# Register the items in an unsorted order deliberately, to test the sorted
# output from get_completions().
self._tc_reg.register_tab_comp_context(
["print_tensor", "pt"],
["node_b:1", "node_b:2", "node_a:1", "node_a:2"])
self._tc_reg.register_tab_comp_context(["node_info"],
["node_c", "node_b", "node_a"])
def testTabCompletion(self):
# The returned completions should have sorted order.
self.assertEqual(
(["node_a:1", "node_a:2", "node_b:1", "node_b:2"], "node_"),
self._tc_reg.get_completions("print_tensor", "node_"))
self.assertEqual((["node_a:1", "node_a:2", "node_b:1", "node_b:2"],
"node_"), self._tc_reg.get_completions("pt", ""))
self.assertEqual((["node_a:1", "node_a:2"], "node_a:"),
self._tc_reg.get_completions("print_tensor", "node_a"))
self.assertEqual((["node_a:1"], "node_a:1"),
self._tc_reg.get_completions("pt", "node_a:1"))
self.assertEqual(([], ""),
self._tc_reg.get_completions("print_tensor", "node_a:3"))
self.assertEqual((None, None), self._tc_reg.get_completions("foo", "node_"))
def testExtendCompletionItems(self):
self.assertEqual(
(["node_a:1", "node_a:2", "node_b:1", "node_b:2"], "node_"),
self._tc_reg.get_completions("print_tensor", "node_"))
self.assertEqual((["node_a", "node_b", "node_c"], "node_"),
self._tc_reg.get_completions("node_info", "node_"))
self._tc_reg.extend_comp_items("print_tensor", ["node_A:1", "node_A:2"])
self.assertEqual((["node_A:1", "node_A:2", "node_a:1", "node_a:2",
"node_b:1", "node_b:2"], "node_"),
self._tc_reg.get_completions("print_tensor", "node_"))
# Extending the completions for one of the context's context words should
# have taken effect on other context words of the same context as well.
self.assertEqual((["node_A:1", "node_A:2", "node_a:1", "node_a:2",
"node_b:1", "node_b:2"], "node_"),
self._tc_reg.get_completions("pt", "node_"))
self.assertEqual((["node_a", "node_b", "node_c"], "node_"),
self._tc_reg.get_completions("node_info", "node_"))
def testExtendCompletionItemsNonexistentContext(self):
with self.assertRaisesRegexp(
KeyError, "Context word \"foo\" has not been registered"):
self._tc_reg.extend_comp_items("foo", ["node_A:1", "node_A:2"])
def testRemoveCompletionItems(self):
self.assertEqual(
(["node_a:1", "node_a:2", "node_b:1", "node_b:2"], "node_"),
self._tc_reg.get_completions("print_tensor", "node_"))
self.assertEqual((["node_a", "node_b", "node_c"], "node_"),
self._tc_reg.get_completions("node_info", "node_"))
self._tc_reg.remove_comp_items("pt", ["node_a:1", "node_a:2"])
self.assertEqual((["node_b:1", "node_b:2"], "node_b:"),
self._tc_reg.get_completions("print_tensor", "node_"))
self.assertEqual((["node_a", "node_b", "node_c"], "node_"),
self._tc_reg.get_completions("node_info", "node_"))
def testRemoveCompletionItemsNonexistentContext(self):
with self.assertRaisesRegexp(
KeyError, "Context word \"foo\" has not been registered"):
self._tc_reg.remove_comp_items("foo", ["node_a:1", "node_a:2"])
def testDeregisterContext(self):
self.assertEqual(
(["node_a:1", "node_a:2", "node_b:1", "node_b:2"], "node_"),
self._tc_reg.get_completions("print_tensor", "node_"))
self.assertEqual((["node_a", "node_b", "node_c"], "node_"),
self._tc_reg.get_completions("node_info", "node_"))
self._tc_reg.deregister_context(["print_tensor"])
self.assertEqual((None, None),
self._tc_reg.get_completions("print_tensor", "node_"))
# The alternative context word should be unaffected.
self.assertEqual(
(["node_a:1", "node_a:2", "node_b:1", "node_b:2"], "node_"),
self._tc_reg.get_completions("pt", "node_"))
def testDeregisterNonexistentContext(self):
self.assertEqual(
(["node_a:1", "node_a:2", "node_b:1", "node_b:2"], "node_"),
self._tc_reg.get_completions("print_tensor", "node_"))
self.assertEqual((["node_a", "node_b", "node_c"], "node_"),
self._tc_reg.get_completions("node_info", "node_"))
self._tc_reg.deregister_context(["print_tensor"])
with self.assertRaisesRegexp(
KeyError,
"Cannot deregister unregistered context word \"print_tensor\""):
self._tc_reg.deregister_context(["print_tensor"])
class CommandHistoryTest(test_util.TensorFlowTestCase):
def setUp(self):
self._history_file_path = tempfile.mktemp()
self._cmd_hist = debugger_cli_common.CommandHistory(
limit=3, history_file_path=self._history_file_path)
def tearDown(self):
if os.path.isfile(self._history_file_path):
os.remove(self._history_file_path)
def _restoreFileReadWritePermissions(self, file_path):
os.chmod(file_path,
(stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR |
stat.S_IWGRP | stat.S_IWOTH))
def testLookUpMostRecent(self):
self.assertEqual([], self._cmd_hist.most_recent_n(3))
self._cmd_hist.add_command("list_tensors")
self._cmd_hist.add_command("node_info node_a")
self.assertEqual(["node_info node_a"], self._cmd_hist.most_recent_n(1))
self.assertEqual(["list_tensors", "node_info node_a"],
self._cmd_hist.most_recent_n(2))
self.assertEqual(["list_tensors", "node_info node_a"],
self._cmd_hist.most_recent_n(3))
self._cmd_hist.add_command("node_info node_b")
self.assertEqual(["node_info node_b"], self._cmd_hist.most_recent_n(1))
self.assertEqual(["node_info node_a", "node_info node_b"],
self._cmd_hist.most_recent_n(2))
self.assertEqual(["list_tensors", "node_info node_a", "node_info node_b"],
self._cmd_hist.most_recent_n(3))
self.assertEqual(["list_tensors", "node_info node_a", "node_info node_b"],
self._cmd_hist.most_recent_n(4))
# Go over the limit.
self._cmd_hist.add_command("node_info node_a")
self.assertEqual(["node_info node_a"], self._cmd_hist.most_recent_n(1))
self.assertEqual(["node_info node_b", "node_info node_a"],
self._cmd_hist.most_recent_n(2))
self.assertEqual(
["node_info node_a", "node_info node_b", "node_info node_a"],
self._cmd_hist.most_recent_n(3))
self.assertEqual(
["node_info node_a", "node_info node_b", "node_info node_a"],
self._cmd_hist.most_recent_n(4))
def testLookUpPrefix(self):
self._cmd_hist.add_command("node_info node_b")
self._cmd_hist.add_command("list_tensors")
self._cmd_hist.add_command("node_info node_a")
self.assertEqual(["node_info node_b", "node_info node_a"],
self._cmd_hist.lookup_prefix("node_info", 10))
self.assertEqual(["node_info node_a"], self._cmd_hist.lookup_prefix(
"node_info", 1))
self.assertEqual([], self._cmd_hist.lookup_prefix("print_tensor", 10))
def testAddNonStrCommand(self):
with self.assertRaisesRegexp(
TypeError, "Attempt to enter non-str entry to command history"):
self._cmd_hist.add_command(["print_tensor node_a:0"])
def testRepeatingCommandsDoNotGetLoggedRepeatedly(self):
self._cmd_hist.add_command("help")
self._cmd_hist.add_command("help")
self.assertEqual(["help"], self._cmd_hist.most_recent_n(2))
def testCommandHistoryFileIsCreated(self):
self.assertFalse(os.path.isfile(self._history_file_path))
self._cmd_hist.add_command("help")
self.assertTrue(os.path.isfile(self._history_file_path))
with open(self._history_file_path, "rt") as f:
self.assertEqual(["help\n"], f.readlines())
def testLoadingCommandHistoryFileObeysLimit(self):
self._cmd_hist.add_command("help 1")
self._cmd_hist.add_command("help 2")
self._cmd_hist.add_command("help 3")
self._cmd_hist.add_command("help 4")
cmd_hist_2 = debugger_cli_common.CommandHistory(
limit=3, history_file_path=self._history_file_path)
self.assertEqual(["help 2", "help 3", "help 4"],
cmd_hist_2.most_recent_n(3))
with open(self._history_file_path, "rt") as f:
self.assertEqual(
["help 2\n", "help 3\n", "help 4\n"], f.readlines())
def testCommandHistoryHandlesReadingIOErrorGracoiusly(self):
with open(self._history_file_path, "wt") as f:
f.write("help\n")
# Change file to not readable by anyone.
os.chmod(self._history_file_path, 0)
# The creation of a CommandHistory object should not error out.
debugger_cli_common.CommandHistory(
limit=3, history_file_path=self._history_file_path)
self._restoreFileReadWritePermissions(self._history_file_path)
def testCommandHistoryHandlesWritingIOErrorGracoiusly(self):
with open(self._history_file_path, "wt") as f:
f.write("help\n")
# Change file to read-only.
os.chmod(self._history_file_path,
stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
# Reading from the file should still work.
cmd_hist_2 = debugger_cli_common.CommandHistory(
limit=3, history_file_path=self._history_file_path)
self.assertEqual(["help"], cmd_hist_2.most_recent_n(1))
# Writing should no longer work, but it should fail silently and
# the within instance-command history should still work.
cmd_hist_2.add_command("foo")
self.assertEqual(["help", "foo"], cmd_hist_2.most_recent_n(2))
cmd_hist_3 = debugger_cli_common.CommandHistory(
limit=3, history_file_path=self._history_file_path)
self.assertEqual(["help"], cmd_hist_3.most_recent_n(1))
self._restoreFileReadWritePermissions(self._history_file_path)
class MenuNodeTest(test_util.TensorFlowTestCase):
def testCommandTypeConstructorSucceeds(self):
menu_node = debugger_cli_common.MenuItem("water flower", "water_flower")
self.assertEqual("water flower", menu_node.caption)
self.assertEqual("water_flower", menu_node.content)
def testDisableWorks(self):
menu_node = debugger_cli_common.MenuItem("water flower", "water_flower")
self.assertTrue(menu_node.is_enabled())
menu_node.disable()
self.assertFalse(menu_node.is_enabled())
menu_node.enable()
self.assertTrue(menu_node.is_enabled())
def testConstructAsDisabledWorks(self):
menu_node = debugger_cli_common.MenuItem(
"water flower", "water_flower", enabled=False)
self.assertFalse(menu_node.is_enabled())
menu_node.enable()
self.assertTrue(menu_node.is_enabled())
class MenuTest(test_util.TensorFlowTestCase):
def setUp(self):
self.menu = debugger_cli_common.Menu()
self.assertEqual(0, self.menu.num_items())
self.node1 = debugger_cli_common.MenuItem("water flower", "water_flower")
self.node2 = debugger_cli_common.MenuItem(
"measure wavelength", "measure_wavelength")
self.menu.append(self.node1)
self.menu.append(self.node2)
self.assertEqual(2, self.menu.num_items())
def testFormatAsSingleLineWithStrItemAttrsWorks(self):
output = self.menu.format_as_single_line(
prefix="Menu: ", divider=", ", enabled_item_attrs="underline")
self.assertEqual(["Menu: water flower, measure wavelength, "], output.lines)
self.assertEqual((6, 18, [self.node1, "underline"]),
output.font_attr_segs[0][0])
self.assertEqual((20, 38, [self.node2, "underline"]),
output.font_attr_segs[0][1])
self.assertEqual({}, output.annotations)
def testFormatAsSingleLineWithListItemAttrsWorks(self):
output = self.menu.format_as_single_line(
prefix="Menu: ", divider=", ", enabled_item_attrs=["underline", "bold"])
self.assertEqual(["Menu: water flower, measure wavelength, "], output.lines)
self.assertEqual((6, 18, [self.node1, "underline", "bold"]),
output.font_attr_segs[0][0])
self.assertEqual((20, 38, [self.node2, "underline", "bold"]),
output.font_attr_segs[0][1])
self.assertEqual({}, output.annotations)
def testFormatAsSingleLineWithNoneItemAttrsWorks(self):
output = self.menu.format_as_single_line(prefix="Menu: ", divider=", ")
self.assertEqual(["Menu: water flower, measure wavelength, "], output.lines)
self.assertEqual((6, 18, [self.node1]), output.font_attr_segs[0][0])
self.assertEqual((20, 38, [self.node2]), output.font_attr_segs[0][1])
self.assertEqual({}, output.annotations)
def testInsertNode(self):
self.assertEqual(["water flower", "measure wavelength"],
self.menu.captions())
node2 = debugger_cli_common.MenuItem("write poem", "write_poem")
self.menu.insert(1, node2)
self.assertEqual(["water flower", "write poem", "measure wavelength"],
self.menu.captions())
output = self.menu.format_as_single_line(prefix="Menu: ", divider=", ")
self.assertEqual(["Menu: water flower, write poem, measure wavelength, "],
output.lines)
def testFormatAsSingleLineWithDisabledNode(self):
node2 = debugger_cli_common.MenuItem(
"write poem", "write_poem", enabled=False)
self.menu.append(node2)
output = self.menu.format_as_single_line(
prefix="Menu: ", divider=", ", disabled_item_attrs="bold")
self.assertEqual(["Menu: water flower, measure wavelength, write poem, "],
output.lines)
self.assertEqual((6, 18, [self.node1]), output.font_attr_segs[0][0])
self.assertEqual((20, 38, [self.node2]), output.font_attr_segs[0][1])
self.assertEqual((40, 50, ["bold"]), output.font_attr_segs[0][2])
class GetTensorFlowVersionLinesTest(test_util.TensorFlowTestCase):
def testGetVersionWithoutDependencies(self):
out = debugger_cli_common.get_tensorflow_version_lines()
self.assertEqual(2, len(out.lines))
self.assertEqual("TensorFlow version: %s" % pywrap_tf_session.__version__,
out.lines[0])
def testGetVersionWithDependencies(self):
out = debugger_cli_common.get_tensorflow_version_lines(True)
self.assertIn("TensorFlow version: %s" % pywrap_tf_session.__version__,
out.lines)
self.assertIn(" numpy: %s" % np.__version__, out.lines)
if __name__ == "__main__":
googletest.main()
| {
"content_hash": "7a6ad2511b666d67a4bc8bf7164d9e50",
"timestamp": "",
"source": "github",
"line_count": 1160,
"max_line_length": 80,
"avg_line_length": 39.43189655172414,
"alnum_prop": 0.6346385081218163,
"repo_name": "jhseu/tensorflow",
"id": "774f49f65d12e132d01f72738c7911883437e3b7",
"size": "46430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorflow/python/debug/cli/debugger_cli_common_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "27480"
},
{
"name": "Batchfile",
"bytes": "49527"
},
{
"name": "C",
"bytes": "875455"
},
{
"name": "C#",
"bytes": "8562"
},
{
"name": "C++",
"bytes": "80051513"
},
{
"name": "CMake",
"bytes": "6500"
},
{
"name": "Dockerfile",
"bytes": "112748"
},
{
"name": "Go",
"bytes": "1853641"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "961600"
},
{
"name": "Jupyter Notebook",
"bytes": "549457"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "1729057"
},
{
"name": "Makefile",
"bytes": "62498"
},
{
"name": "Objective-C",
"bytes": "116558"
},
{
"name": "Objective-C++",
"bytes": "304661"
},
{
"name": "PHP",
"bytes": "4236"
},
{
"name": "Pascal",
"bytes": "318"
},
{
"name": "Pawn",
"bytes": "19515"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "36791185"
},
{
"name": "RobotFramework",
"bytes": "891"
},
{
"name": "Roff",
"bytes": "2705"
},
{
"name": "Ruby",
"bytes": "7464"
},
{
"name": "SWIG",
"bytes": "56741"
},
{
"name": "Shell",
"bytes": "685877"
},
{
"name": "Smarty",
"bytes": "35147"
},
{
"name": "Starlark",
"bytes": "3504187"
},
{
"name": "Swift",
"bytes": "62814"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
"""Tests for tensorflow.ops.test_util."""
import collections
import copy
import random
import threading
import unittest
import weakref
from absl.testing import parameterized
import numpy as np
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.python import pywrap_sanitizers
from tensorflow.python.compat import compat
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import combinations
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import test_ops # pylint: disable=unused-import
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import lookup_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.ops.ragged import ragged_tensor
from tensorflow.python.platform import googletest
class TestUtilTest(test_util.TensorFlowTestCase, parameterized.TestCase):
def test_assert_ops_in_graph(self):
with ops.Graph().as_default():
constant_op.constant(["hello", "taffy"], name="hello")
test_util.assert_ops_in_graph({"hello": "Const"}, ops.get_default_graph())
self.assertRaises(ValueError, test_util.assert_ops_in_graph,
{"bye": "Const"}, ops.get_default_graph())
self.assertRaises(ValueError, test_util.assert_ops_in_graph,
{"hello": "Variable"}, ops.get_default_graph())
@test_util.run_deprecated_v1
def test_session_functions(self):
with self.test_session() as sess:
sess_ref = weakref.ref(sess)
with self.cached_session(graph=None, config=None) as sess2:
# We make sure that sess2 is sess.
assert sess2 is sess
# We make sure we raise an exception if we use cached_session with
# different values.
with self.assertRaises(ValueError):
with self.cached_session(graph=ops.Graph()) as sess2:
pass
with self.assertRaises(ValueError):
with self.cached_session(force_gpu=True) as sess2:
pass
# We make sure that test_session will cache the session even after the
# with scope.
assert not sess_ref()._closed
with self.session() as unique_sess:
unique_sess_ref = weakref.ref(unique_sess)
with self.session() as sess2:
assert sess2 is not unique_sess
# We make sure the session is closed when we leave the with statement.
assert unique_sess_ref()._closed
def test_assert_equal_graph_def(self):
with ops.Graph().as_default() as g:
def_empty = g.as_graph_def()
constant_op.constant(5, name="five")
constant_op.constant(7, name="seven")
def_57 = g.as_graph_def()
with ops.Graph().as_default() as g:
constant_op.constant(7, name="seven")
constant_op.constant(5, name="five")
def_75 = g.as_graph_def()
# Comparing strings is order dependent
self.assertNotEqual(str(def_57), str(def_75))
# assert_equal_graph_def doesn't care about order
test_util.assert_equal_graph_def(def_57, def_75)
# Compare two unequal graphs
with self.assertRaisesRegex(AssertionError,
r"^Found unexpected node '{{node seven}}"):
test_util.assert_equal_graph_def(def_57, def_empty)
def test_assert_equal_graph_def_hash_table(self):
def get_graph_def():
with ops.Graph().as_default() as g:
x = constant_op.constant([2, 9], name="x")
keys = constant_op.constant([1, 2], name="keys")
values = constant_op.constant([3, 4], name="values")
default = constant_op.constant(-1, name="default")
table = lookup_ops.StaticHashTable(
lookup_ops.KeyValueTensorInitializer(keys, values), default)
_ = table.lookup(x)
return g.as_graph_def()
def_1 = get_graph_def()
def_2 = get_graph_def()
# The unique shared_name of each table makes the graph unequal.
with self.assertRaisesRegex(AssertionError, "hash_table_"):
test_util.assert_equal_graph_def(def_1, def_2,
hash_table_shared_name=False)
# That can be ignored. (NOTE: modifies GraphDefs in-place.)
test_util.assert_equal_graph_def(def_1, def_2,
hash_table_shared_name=True)
def testIsGoogleCudaEnabled(self):
# The test doesn't assert anything. It ensures the py wrapper
# function is generated correctly.
if test_util.IsGoogleCudaEnabled():
print("GoogleCuda is enabled")
else:
print("GoogleCuda is disabled")
def testIsMklEnabled(self):
# This test doesn't assert anything.
# It ensures the py wrapper function is generated correctly.
if test_util.IsMklEnabled():
print("MKL is enabled")
else:
print("MKL is disabled")
@test_util.disable_asan("Skip test if ASAN is enabled.")
def testDisableAsan(self):
self.assertFalse(pywrap_sanitizers.is_asan_enabled())
@test_util.disable_msan("Skip test if MSAN is enabled.")
def testDisableMsan(self):
self.assertFalse(pywrap_sanitizers.is_msan_enabled())
@test_util.disable_tsan("Skip test if TSAN is enabled.")
def testDisableTsan(self):
self.assertFalse(pywrap_sanitizers.is_tsan_enabled())
@test_util.disable_ubsan("Skip test if UBSAN is enabled.")
def testDisableUbsan(self):
self.assertFalse(pywrap_sanitizers.is_ubsan_enabled())
@test_util.run_in_graph_and_eager_modes
def testAssertProtoEqualsStr(self):
graph_str = "node { name: 'w1' op: 'params' }"
graph_def = graph_pb2.GraphDef()
text_format.Merge(graph_str, graph_def)
# test string based comparison
self.assertProtoEquals(graph_str, graph_def)
# test original comparison
self.assertProtoEquals(graph_def, graph_def)
@test_util.run_in_graph_and_eager_modes
def testAssertProtoEqualsAny(self):
# Test assertProtoEquals with a protobuf.Any field.
meta_graph_def_str = """
meta_info_def {
meta_graph_version: "outer"
any_info {
[type.googleapis.com/tensorflow.MetaGraphDef] {
meta_info_def {
meta_graph_version: "inner"
}
}
}
}
"""
meta_graph_def_outer = meta_graph_pb2.MetaGraphDef()
meta_graph_def_outer.meta_info_def.meta_graph_version = "outer"
meta_graph_def_inner = meta_graph_pb2.MetaGraphDef()
meta_graph_def_inner.meta_info_def.meta_graph_version = "inner"
meta_graph_def_outer.meta_info_def.any_info.Pack(meta_graph_def_inner)
self.assertProtoEquals(meta_graph_def_str, meta_graph_def_outer)
self.assertProtoEquals(meta_graph_def_outer, meta_graph_def_outer)
# Check if the assertion failure message contains the content of
# the inner proto.
with self.assertRaisesRegex(AssertionError, r'meta_graph_version: "inner"'):
self.assertProtoEquals("", meta_graph_def_outer)
@test_util.run_in_graph_and_eager_modes
def testNDArrayNear(self):
a1 = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
a2 = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
a3 = np.array([[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]])
self.assertTrue(self._NDArrayNear(a1, a2, 1e-5))
self.assertFalse(self._NDArrayNear(a1, a3, 1e-5))
@test_util.run_in_graph_and_eager_modes
def testCheckedThreadSucceeds(self):
def noop(ev):
ev.set()
event_arg = threading.Event()
self.assertFalse(event_arg.is_set())
t = self.checkedThread(target=noop, args=(event_arg,))
t.start()
t.join()
self.assertTrue(event_arg.is_set())
@test_util.run_in_graph_and_eager_modes
def testCheckedThreadFails(self):
def err_func():
return 1 // 0
t = self.checkedThread(target=err_func)
t.start()
with self.assertRaises(self.failureException) as fe:
t.join()
self.assertTrue("integer division or modulo by zero" in str(fe.exception))
@test_util.run_in_graph_and_eager_modes
def testCheckedThreadWithWrongAssertionFails(self):
x = 37
def err_func():
self.assertTrue(x < 10)
t = self.checkedThread(target=err_func)
t.start()
with self.assertRaises(self.failureException) as fe:
t.join()
self.assertTrue("False is not true" in str(fe.exception))
@test_util.run_in_graph_and_eager_modes
def testMultipleThreadsWithOneFailure(self):
def err_func(i):
self.assertTrue(i != 7)
threads = [
self.checkedThread(
target=err_func, args=(i,)) for i in range(10)
]
for t in threads:
t.start()
for i, t in enumerate(threads):
if i == 7:
with self.assertRaises(self.failureException):
t.join()
else:
t.join()
def _WeMustGoDeeper(self, msg):
with self.assertRaisesOpError(msg):
with ops.Graph().as_default():
node_def = ops._NodeDef("IntOutput", "name")
node_def_orig = ops._NodeDef("IntOutput", "orig")
op_orig = ops.Operation(node_def_orig, ops.get_default_graph())
op = ops.Operation(node_def, ops.get_default_graph(),
original_op=op_orig)
raise errors.UnauthenticatedError(node_def, op, "true_err")
@test_util.run_in_graph_and_eager_modes
def testAssertRaisesOpErrorDoesNotPassMessageDueToLeakedStack(self):
with self.assertRaises(AssertionError):
self._WeMustGoDeeper("this_is_not_the_error_you_are_looking_for")
self._WeMustGoDeeper("true_err")
self._WeMustGoDeeper("name")
self._WeMustGoDeeper("orig")
@parameterized.named_parameters(
dict(testcase_name="tensors", ragged_tensors=False),
dict(testcase_name="ragged_tensors", ragged_tensors=True))
@test_util.run_in_graph_and_eager_modes
def testAllCloseTensors(self, ragged_tensors: bool):
a_raw_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
a = constant_op.constant(a_raw_data)
b = math_ops.add(1, constant_op.constant([[0, 1, 2], [3, 4, 5], [6, 7, 8]]))
if ragged_tensors:
a = ragged_tensor.RaggedTensor.from_tensor(a)
b = ragged_tensor.RaggedTensor.from_tensor(b)
self.assertAllClose(a, b)
self.assertAllClose(a, a_raw_data)
a_dict = {"key": a}
b_dict = {"key": b}
self.assertAllClose(a_dict, b_dict)
x_list = [a, b]
y_list = [a_raw_data, b]
self.assertAllClose(x_list, y_list)
@test_util.run_in_graph_and_eager_modes
def testAllCloseScalars(self):
self.assertAllClose(7, 7 + 1e-8)
with self.assertRaisesRegex(AssertionError, r"Not equal to tolerance"):
self.assertAllClose(7, 7 + 1e-5)
@test_util.run_in_graph_and_eager_modes
def testAllCloseList(self):
with self.assertRaisesRegex(AssertionError, r"not close dif"):
self.assertAllClose([0], [1])
@test_util.run_in_graph_and_eager_modes
def testAllCloseDictToNonDict(self):
with self.assertRaisesRegex(ValueError, r"Can't compare dict to non-dict"):
self.assertAllClose(1, {"a": 1})
with self.assertRaisesRegex(ValueError, r"Can't compare dict to non-dict"):
self.assertAllClose({"a": 1}, 1)
@test_util.run_in_graph_and_eager_modes
def testAllCloseNamedtuples(self):
a = 7
b = (2., 3.)
c = np.ones((3, 2, 4)) * 7.
expected = {"a": a, "b": b, "c": c}
my_named_tuple = collections.namedtuple("MyNamedTuple", ["a", "b", "c"])
# Identity.
self.assertAllClose(expected, my_named_tuple(a=a, b=b, c=c))
self.assertAllClose(
my_named_tuple(a=a, b=b, c=c), my_named_tuple(a=a, b=b, c=c))
@test_util.run_in_graph_and_eager_modes
def testAllCloseDicts(self):
a = 7
b = (2., 3.)
c = np.ones((3, 2, 4)) * 7.
expected = {"a": a, "b": b, "c": c}
# Identity.
self.assertAllClose(expected, expected)
self.assertAllClose(expected, dict(expected))
# With each item removed.
for k in expected:
actual = dict(expected)
del actual[k]
with self.assertRaisesRegex(AssertionError, r"mismatched keys"):
self.assertAllClose(expected, actual)
# With each item changed.
with self.assertRaisesRegex(AssertionError, r"Not equal to tolerance"):
self.assertAllClose(expected, {"a": a + 1e-5, "b": b, "c": c})
with self.assertRaisesRegex(AssertionError, r"Shape mismatch"):
self.assertAllClose(expected, {"a": a, "b": b + (4.,), "c": c})
c_copy = np.array(c)
c_copy[1, 1, 1] += 1e-5
with self.assertRaisesRegex(AssertionError, r"Not equal to tolerance"):
self.assertAllClose(expected, {"a": a, "b": b, "c": c_copy})
@test_util.run_in_graph_and_eager_modes
def testAllCloseListOfNamedtuples(self):
my_named_tuple = collections.namedtuple("MyNamedTuple", ["x", "y"])
l1 = [
my_named_tuple(x=np.array([[2.3, 2.5]]), y=np.array([[0.97, 0.96]])),
my_named_tuple(x=np.array([[3.3, 3.5]]), y=np.array([[0.98, 0.99]]))
]
l2 = [
([[2.3, 2.5]], [[0.97, 0.96]]),
([[3.3, 3.5]], [[0.98, 0.99]]),
]
self.assertAllClose(l1, l2)
@test_util.run_in_graph_and_eager_modes
def testAllCloseNestedStructure(self):
a = {"x": np.ones((3, 2, 4)) * 7, "y": (2, [{"nested": {"m": 3, "n": 4}}])}
self.assertAllClose(a, a)
b = copy.deepcopy(a)
self.assertAllClose(a, b)
# Test mismatched values
b["y"][1][0]["nested"]["n"] = 4.2
with self.assertRaisesRegex(AssertionError,
r"\[y\]\[1\]\[0\]\[nested\]\[n\]"):
self.assertAllClose(a, b)
@test_util.run_in_graph_and_eager_modes
def testAssertDictEqual(self):
a = 7
b = (2., 3.)
c = np.ones((3, 2, 4)) * 7.
d = "testing123"
expected = {"a": a, "b": b, "c": c, "d": d}
actual = {"a": a, "b": b, "c": constant_op.constant(c), "d": d}
self.assertDictEqual(expected, expected)
self.assertDictEqual(expected, actual)
@test_util.run_in_graph_and_eager_modes
def testArrayNear(self):
a = [1, 2]
b = [1, 2, 5]
with self.assertRaises(AssertionError):
self.assertArrayNear(a, b, 0.001)
a = [1, 2]
b = [[1, 2], [3, 4]]
with self.assertRaises(TypeError):
self.assertArrayNear(a, b, 0.001)
a = [1, 2]
b = [1, 2]
self.assertArrayNear(a, b, 0.001)
@test_util.skip_if(True) # b/117665998
def testForceGPU(self):
with self.assertRaises(errors.InvalidArgumentError):
with self.test_session(force_gpu=True):
# this relies on us not having a GPU implementation for assert, which
# seems sensible
x = constant_op.constant(True)
y = [15]
control_flow_ops.Assert(x, y).run()
@test_util.run_in_graph_and_eager_modes
def testAssertAllCloseAccordingToType(self):
# test plain int
self.assertAllCloseAccordingToType(1, 1, rtol=1e-8, atol=1e-8)
# test float64
self.assertAllCloseAccordingToType(
np.asarray([1e-8], dtype=np.float64),
np.asarray([2e-8], dtype=np.float64),
rtol=1e-8, atol=1e-8
)
self.assertAllCloseAccordingToType(
constant_op.constant([1e-8], dtype=dtypes.float64),
constant_op.constant([2e-8], dtype=dtypes.float64),
rtol=1e-8,
atol=1e-8)
with (self.assertRaises(AssertionError)):
self.assertAllCloseAccordingToType(
np.asarray([1e-7], dtype=np.float64),
np.asarray([2e-7], dtype=np.float64),
rtol=1e-8, atol=1e-8
)
# test float32
self.assertAllCloseAccordingToType(
np.asarray([1e-7], dtype=np.float32),
np.asarray([2e-7], dtype=np.float32),
rtol=1e-8, atol=1e-8,
float_rtol=1e-7, float_atol=1e-7
)
self.assertAllCloseAccordingToType(
constant_op.constant([1e-7], dtype=dtypes.float32),
constant_op.constant([2e-7], dtype=dtypes.float32),
rtol=1e-8,
atol=1e-8,
float_rtol=1e-7,
float_atol=1e-7)
with (self.assertRaises(AssertionError)):
self.assertAllCloseAccordingToType(
np.asarray([1e-6], dtype=np.float32),
np.asarray([2e-6], dtype=np.float32),
rtol=1e-8, atol=1e-8,
float_rtol=1e-7, float_atol=1e-7
)
# test float16
self.assertAllCloseAccordingToType(
np.asarray([1e-4], dtype=np.float16),
np.asarray([2e-4], dtype=np.float16),
rtol=1e-8, atol=1e-8,
float_rtol=1e-7, float_atol=1e-7,
half_rtol=1e-4, half_atol=1e-4
)
self.assertAllCloseAccordingToType(
constant_op.constant([1e-4], dtype=dtypes.float16),
constant_op.constant([2e-4], dtype=dtypes.float16),
rtol=1e-8,
atol=1e-8,
float_rtol=1e-7,
float_atol=1e-7,
half_rtol=1e-4,
half_atol=1e-4)
with (self.assertRaises(AssertionError)):
self.assertAllCloseAccordingToType(
np.asarray([1e-3], dtype=np.float16),
np.asarray([2e-3], dtype=np.float16),
rtol=1e-8, atol=1e-8,
float_rtol=1e-7, float_atol=1e-7,
half_rtol=1e-4, half_atol=1e-4
)
@test_util.run_in_graph_and_eager_modes
def testAssertAllEqual(self):
i = variables.Variable([100] * 3, dtype=dtypes.int32, name="i")
j = constant_op.constant([20] * 3, dtype=dtypes.int32, name="j")
k = math_ops.add(i, j, name="k")
self.evaluate(variables.global_variables_initializer())
self.assertAllEqual([100] * 3, i)
self.assertAllEqual([120] * 3, k)
self.assertAllEqual([20] * 3, j)
with self.assertRaisesRegex(AssertionError, r"not equal lhs"):
self.assertAllEqual([0] * 3, k)
@test_util.run_in_graph_and_eager_modes
def testAssertNotAllEqual(self):
i = variables.Variable([100], dtype=dtypes.int32, name="i")
j = constant_op.constant([20], dtype=dtypes.int32, name="j")
k = math_ops.add(i, j, name="k")
self.evaluate(variables.global_variables_initializer())
self.assertNotAllEqual([100] * 3, i)
self.assertNotAllEqual([120] * 3, k)
self.assertNotAllEqual([20] * 3, j)
with self.assertRaisesRegex(
AssertionError, r"two values are equal at all elements.*extra message"):
self.assertNotAllEqual([120], k, msg="extra message")
@test_util.run_in_graph_and_eager_modes
def testAssertNotAllClose(self):
# Test with arrays
self.assertNotAllClose([0.1], [0.2])
with self.assertRaises(AssertionError):
self.assertNotAllClose([-1.0, 2.0], [-1.0, 2.0])
# Test with tensors
x = constant_op.constant([1.0, 1.0], name="x")
y = math_ops.add(x, x)
self.assertAllClose([2.0, 2.0], y)
self.assertNotAllClose([0.9, 1.0], x)
with self.assertRaises(AssertionError):
self.assertNotAllClose([1.0, 1.0], x)
@test_util.run_in_graph_and_eager_modes
def testAssertNotAllCloseRTol(self):
# Test with arrays
with self.assertRaises(AssertionError):
self.assertNotAllClose([1.1, 2.1], [1.0, 2.0], rtol=0.2)
# Test with tensors
x = constant_op.constant([1.0, 1.0], name="x")
y = math_ops.add(x, x)
self.assertAllClose([2.0, 2.0], y)
with self.assertRaises(AssertionError):
self.assertNotAllClose([0.9, 1.0], x, rtol=0.2)
@test_util.run_in_graph_and_eager_modes
def testAssertNotAllCloseATol(self):
# Test with arrays
with self.assertRaises(AssertionError):
self.assertNotAllClose([1.1, 2.1], [1.0, 2.0], atol=0.2)
# Test with tensors
x = constant_op.constant([1.0, 1.0], name="x")
y = math_ops.add(x, x)
self.assertAllClose([2.0, 2.0], y)
with self.assertRaises(AssertionError):
self.assertNotAllClose([0.9, 1.0], x, atol=0.2)
@test_util.run_in_graph_and_eager_modes
def testAssertAllGreaterLess(self):
x = constant_op.constant([100.0, 110.0, 120.0], dtype=dtypes.float32)
y = constant_op.constant([10.0] * 3, dtype=dtypes.float32)
z = math_ops.add(x, y)
self.assertAllClose([110.0, 120.0, 130.0], z)
self.assertAllGreater(x, 95.0)
self.assertAllLess(x, 125.0)
with self.assertRaises(AssertionError):
self.assertAllGreater(x, 105.0)
with self.assertRaises(AssertionError):
self.assertAllGreater(x, 125.0)
with self.assertRaises(AssertionError):
self.assertAllLess(x, 115.0)
with self.assertRaises(AssertionError):
self.assertAllLess(x, 95.0)
@test_util.run_in_graph_and_eager_modes
def testAssertAllGreaterLessEqual(self):
x = constant_op.constant([100.0, 110.0, 120.0], dtype=dtypes.float32)
y = constant_op.constant([10.0] * 3, dtype=dtypes.float32)
z = math_ops.add(x, y)
self.assertAllEqual([110.0, 120.0, 130.0], z)
self.assertAllGreaterEqual(x, 95.0)
self.assertAllLessEqual(x, 125.0)
with self.assertRaises(AssertionError):
self.assertAllGreaterEqual(x, 105.0)
with self.assertRaises(AssertionError):
self.assertAllGreaterEqual(x, 125.0)
with self.assertRaises(AssertionError):
self.assertAllLessEqual(x, 115.0)
with self.assertRaises(AssertionError):
self.assertAllLessEqual(x, 95.0)
def testAssertAllInRangeWithNonNumericValuesFails(self):
s1 = constant_op.constant("Hello, ", name="s1")
c = constant_op.constant([1 + 2j, -3 + 5j], name="c")
b = constant_op.constant([False, True], name="b")
with self.assertRaises(AssertionError):
self.assertAllInRange(s1, 0.0, 1.0)
with self.assertRaises(AssertionError):
self.assertAllInRange(c, 0.0, 1.0)
with self.assertRaises(AssertionError):
self.assertAllInRange(b, 0, 1)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInRange(self):
x = constant_op.constant([10.0, 15.0], name="x")
self.assertAllInRange(x, 10, 15)
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 10, 15, open_lower_bound=True)
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 10, 15, open_upper_bound=True)
with self.assertRaises(AssertionError):
self.assertAllInRange(
x, 10, 15, open_lower_bound=True, open_upper_bound=True)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInRangeScalar(self):
x = constant_op.constant(10.0, name="x")
nan = constant_op.constant(np.nan, name="nan")
self.assertAllInRange(x, 5, 15)
with self.assertRaises(AssertionError):
self.assertAllInRange(nan, 5, 15)
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 10, 15, open_lower_bound=True)
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 1, 2)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInRangeErrorMessageEllipses(self):
x_init = np.array([[10.0, 15.0]] * 12)
x = constant_op.constant(x_init, name="x")
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 5, 10)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInRangeDetectsNaNs(self):
x = constant_op.constant(
[[np.nan, 0.0], [np.nan, np.inf], [np.inf, np.nan]], name="x")
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 0.0, 2.0)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInRangeWithInfinities(self):
x = constant_op.constant([10.0, np.inf], name="x")
self.assertAllInRange(x, 10, np.inf)
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 10, np.inf, open_upper_bound=True)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInSet(self):
b = constant_op.constant([True, False], name="b")
x = constant_op.constant([13, 37], name="x")
self.assertAllInSet(b, [False, True])
self.assertAllInSet(b, (False, True))
self.assertAllInSet(b, {False, True})
self.assertAllInSet(x, [0, 13, 37, 42])
self.assertAllInSet(x, (0, 13, 37, 42))
self.assertAllInSet(x, {0, 13, 37, 42})
with self.assertRaises(AssertionError):
self.assertAllInSet(b, [False])
with self.assertRaises(AssertionError):
self.assertAllInSet(x, (42,))
@test_util.run_in_graph_and_eager_modes
def testAssertShapeEqualSameInputTypes(self):
# Test with arrays
array_a = np.random.rand(3, 1)
array_b = np.random.rand(3, 1)
array_c = np.random.rand(4, 2)
self.assertShapeEqual(array_a, array_b)
with self.assertRaises(AssertionError):
self.assertShapeEqual(array_a, array_c)
# Test with tensors
tensor_x = random_ops.random_uniform((5, 2, 1))
tensor_y = random_ops.random_uniform((5, 2, 1))
tensor_z = random_ops.random_uniform((2, 4))
self.assertShapeEqual(tensor_x, tensor_y)
with self.assertRaises(AssertionError):
self.assertShapeEqual(tensor_x, tensor_z)
@test_util.run_in_graph_and_eager_modes
def testAssertShapeEqualMixedInputTypes(self):
# Test mixed multi-dimensional inputs
array_input = np.random.rand(4, 3, 2)
tensor_input = random_ops.random_uniform((4, 3, 2))
tensor_input_2 = random_ops.random_uniform((10, 5))
self.assertShapeEqual(array_input, tensor_input)
self.assertShapeEqual(tensor_input, array_input)
with self.assertRaises(AssertionError):
self.assertShapeEqual(array_input, tensor_input_2)
# Test with scalar inputs
array_input = np.random.rand(1)
tensor_input = random_ops.random_uniform((1,))
tensor_input_2 = random_ops.random_uniform((3, 1))
self.assertShapeEqual(array_input, tensor_input)
self.assertShapeEqual(tensor_input, array_input)
with self.assertRaises(AssertionError):
self.assertShapeEqual(array_input, tensor_input_2)
def testAssertShapeEqualDynamicShapes(self):
array_a = np.random.rand(4)
values = [1, 1, 2, 3, 4, 4]
# Dynamic shape should be resolved in eager execution.
with context.eager_mode():
tensor_b = array_ops.unique(values)[0]
self.assertShapeEqual(array_a, tensor_b)
# Shape comparison should fail when a graph is traced but not evaluated.
with context.graph_mode():
tensor_c = array_ops.unique(values)[0]
with self.assertRaises(AssertionError):
self.assertShapeEqual(array_a, tensor_c)
def testRandomSeed(self):
# Call setUp again for WithCApi case (since it makes a new default graph
# after setup).
# TODO(skyewm): remove this when C API is permanently enabled.
with context.eager_mode():
self.setUp()
a = random.randint(1, 1000)
a_np_rand = np.random.rand(1)
a_rand = random_ops.random_normal([1])
# ensure that randomness in multiple testCases is deterministic.
self.setUp()
b = random.randint(1, 1000)
b_np_rand = np.random.rand(1)
b_rand = random_ops.random_normal([1])
self.assertEqual(a, b)
self.assertEqual(a_np_rand, b_np_rand)
self.assertAllEqual(a_rand, b_rand)
@test_util.run_in_graph_and_eager_modes
def test_callable_evaluate(self):
def model():
return resource_variable_ops.ResourceVariable(
name="same_name",
initial_value=1) + 1
with context.eager_mode():
self.assertEqual(2, self.evaluate(model))
@test_util.run_in_graph_and_eager_modes
def test_nested_tensors_evaluate(self):
expected = {"a": 1, "b": 2, "nested": {"d": 3, "e": 4}}
nested = {"a": constant_op.constant(1),
"b": constant_op.constant(2),
"nested": {"d": constant_op.constant(3),
"e": constant_op.constant(4)}}
self.assertEqual(expected, self.evaluate(nested))
def test_run_in_graph_and_eager_modes(self):
l = []
def inc(self, with_brackets):
del self # self argument is required by run_in_graph_and_eager_modes.
mode = "eager" if context.executing_eagerly() else "graph"
with_brackets = "with_brackets" if with_brackets else "without_brackets"
l.append((with_brackets, mode))
f = test_util.run_in_graph_and_eager_modes(inc)
f(self, with_brackets=False)
f = test_util.run_in_graph_and_eager_modes()(inc) # pylint: disable=assignment-from-no-return
f(self, with_brackets=True)
self.assertEqual(len(l), 4)
self.assertEqual(set(l), {
("with_brackets", "graph"),
("with_brackets", "eager"),
("without_brackets", "graph"),
("without_brackets", "eager"),
})
def test_get_node_def_from_graph(self):
graph_def = graph_pb2.GraphDef()
node_foo = graph_def.node.add()
node_foo.name = "foo"
self.assertIs(test_util.get_node_def_from_graph("foo", graph_def), node_foo)
self.assertIsNone(test_util.get_node_def_from_graph("bar", graph_def))
def test_run_in_eager_and_graph_modes_test_class(self):
msg = "`run_in_graph_and_eager_modes` only supports test methods.*"
with self.assertRaisesRegex(ValueError, msg):
@test_util.run_in_graph_and_eager_modes()
class Foo(object):
pass
del Foo # Make pylint unused happy.
def test_run_in_eager_and_graph_modes_skip_graph_runs_eager(self):
modes = []
def _test(self):
if not context.executing_eagerly():
self.skipTest("Skipping in graph mode")
modes.append("eager" if context.executing_eagerly() else "graph")
test_util.run_in_graph_and_eager_modes(_test)(self)
self.assertEqual(modes, ["eager"])
def test_run_in_eager_and_graph_modes_skip_eager_runs_graph(self):
modes = []
def _test(self):
if context.executing_eagerly():
self.skipTest("Skipping in eager mode")
modes.append("eager" if context.executing_eagerly() else "graph")
test_util.run_in_graph_and_eager_modes(_test)(self)
self.assertEqual(modes, ["graph"])
def test_run_in_graph_and_eager_modes_setup_in_same_mode(self):
modes = []
mode_name = lambda: "eager" if context.executing_eagerly() else "graph"
class ExampleTest(test_util.TensorFlowTestCase):
def runTest(self):
pass
def setUp(self):
modes.append("setup_" + mode_name())
@test_util.run_in_graph_and_eager_modes
def testBody(self):
modes.append("run_" + mode_name())
e = ExampleTest()
e.setUp()
e.testBody()
self.assertEqual(modes[1:2], ["run_graph"])
self.assertEqual(modes[2:], ["setup_eager", "run_eager"])
@parameterized.named_parameters(dict(testcase_name="argument",
arg=True))
@test_util.run_in_graph_and_eager_modes
def test_run_in_graph_and_eager_works_with_parameterized_keyword(self, arg):
self.assertEqual(arg, True)
@combinations.generate(combinations.combine(arg=True))
@test_util.run_in_graph_and_eager_modes
def test_run_in_graph_and_eager_works_with_combinations(self, arg):
self.assertEqual(arg, True)
def test_build_as_function_and_v1_graph(self):
class GraphModeAndFunctionTest(parameterized.TestCase):
def __init__(inner_self): # pylint: disable=no-self-argument
super(GraphModeAndFunctionTest, inner_self).__init__()
inner_self.graph_mode_tested = False
inner_self.inside_function_tested = False
def runTest(self):
del self
@test_util.build_as_function_and_v1_graph
def test_modes(inner_self): # pylint: disable=no-self-argument
if ops.inside_function():
self.assertFalse(inner_self.inside_function_tested)
inner_self.inside_function_tested = True
else:
self.assertFalse(inner_self.graph_mode_tested)
inner_self.graph_mode_tested = True
test_object = GraphModeAndFunctionTest()
test_object.test_modes_v1_graph()
test_object.test_modes_function()
self.assertTrue(test_object.graph_mode_tested)
self.assertTrue(test_object.inside_function_tested)
@test_util.run_in_graph_and_eager_modes
def test_consistent_random_seed_in_assert_all_equal(self):
random_seed.set_seed(1066)
index = random_ops.random_shuffle([0, 1, 2, 3, 4], seed=2021)
# This failed when `a` and `b` were evaluated in separate sessions.
self.assertAllEqual(index, index)
def test_with_forward_compatibility_horizons(self):
tested_codepaths = set()
def some_function_with_forward_compat_behavior():
if compat.forward_compatible(2050, 1, 1):
tested_codepaths.add("future")
else:
tested_codepaths.add("present")
@test_util.with_forward_compatibility_horizons(None, [2051, 1, 1])
def some_test(self):
del self # unused
some_function_with_forward_compat_behavior()
some_test(None)
self.assertEqual(tested_codepaths, set(["present", "future"]))
class SkipTestTest(test_util.TensorFlowTestCase):
def _verify_test_in_set_up_or_tear_down(self):
with self.assertRaises(unittest.SkipTest):
with test_util.skip_if_error(self, ValueError,
["foo bar", "test message"]):
raise ValueError("test message")
try:
with self.assertRaisesRegex(ValueError, "foo bar"):
with test_util.skip_if_error(self, ValueError, "test message"):
raise ValueError("foo bar")
except unittest.SkipTest:
raise RuntimeError("Test is not supposed to skip.")
def setUp(self):
super(SkipTestTest, self).setUp()
self._verify_test_in_set_up_or_tear_down()
def tearDown(self):
super(SkipTestTest, self).tearDown()
self._verify_test_in_set_up_or_tear_down()
def test_skip_if_error_should_skip(self):
with self.assertRaises(unittest.SkipTest):
with test_util.skip_if_error(self, ValueError, "test message"):
raise ValueError("test message")
def test_skip_if_error_should_skip_with_list(self):
with self.assertRaises(unittest.SkipTest):
with test_util.skip_if_error(self, ValueError,
["foo bar", "test message"]):
raise ValueError("test message")
def test_skip_if_error_should_skip_without_expected_message(self):
with self.assertRaises(unittest.SkipTest):
with test_util.skip_if_error(self, ValueError):
raise ValueError("test message")
def test_skip_if_error_should_skip_without_error_message(self):
with self.assertRaises(unittest.SkipTest):
with test_util.skip_if_error(self, ValueError):
raise ValueError()
def test_skip_if_error_should_raise_message_mismatch(self):
try:
with self.assertRaisesRegex(ValueError, "foo bar"):
with test_util.skip_if_error(self, ValueError, "test message"):
raise ValueError("foo bar")
except unittest.SkipTest:
raise RuntimeError("Test is not supposed to skip.")
def test_skip_if_error_should_raise_no_message(self):
try:
with self.assertRaisesRegex(ValueError, ""):
with test_util.skip_if_error(self, ValueError, "test message"):
raise ValueError()
except unittest.SkipTest:
raise RuntimeError("Test is not supposed to skip.")
# Its own test case to reproduce variable sharing issues which only pop up when
# setUp() is overridden and super() is not called.
class GraphAndEagerNoVariableSharing(test_util.TensorFlowTestCase):
def setUp(self):
pass # Intentionally does not call TensorFlowTestCase's super()
@test_util.run_in_graph_and_eager_modes
def test_no_variable_sharing(self):
variable_scope.get_variable(
name="step_size",
initializer=np.array(1e-5, np.float32),
use_resource=True,
trainable=False)
class GarbageCollectionTest(test_util.TensorFlowTestCase):
def test_no_reference_cycle_decorator(self):
class ReferenceCycleTest(object):
def __init__(inner_self): # pylint: disable=no-self-argument
inner_self.assertEqual = self.assertEqual # pylint: disable=invalid-name
@test_util.assert_no_garbage_created
def test_has_cycle(self):
a = []
a.append(a)
@test_util.assert_no_garbage_created
def test_has_no_cycle(self):
pass
with self.assertRaises(AssertionError):
ReferenceCycleTest().test_has_cycle()
ReferenceCycleTest().test_has_no_cycle()
@test_util.run_in_graph_and_eager_modes
def test_no_leaked_tensor_decorator(self):
class LeakedTensorTest(object):
def __init__(inner_self): # pylint: disable=no-self-argument
inner_self.assertEqual = self.assertEqual # pylint: disable=invalid-name
@test_util.assert_no_new_tensors
def test_has_leak(self):
self.a = constant_op.constant([3.], name="leak")
@test_util.assert_no_new_tensors
def test_has_no_leak(self):
constant_op.constant([3.], name="no-leak")
with self.assertRaisesRegex(AssertionError, "Tensors not deallocated"):
LeakedTensorTest().test_has_leak()
LeakedTensorTest().test_has_no_leak()
def test_no_new_objects_decorator(self):
class LeakedObjectTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(LeakedObjectTest, self).__init__(*args, **kwargs)
self.accumulation = []
@unittest.expectedFailure
@test_util.assert_no_new_pyobjects_executing_eagerly
def test_has_leak(self):
self.accumulation.append([1.])
@test_util.assert_no_new_pyobjects_executing_eagerly
def test_has_no_leak(self):
self.not_accumulating = [1.]
self.assertTrue(LeakedObjectTest("test_has_leak").run().wasSuccessful())
self.assertTrue(LeakedObjectTest("test_has_no_leak").run().wasSuccessful())
class RunFunctionsEagerlyInV2Test(test_util.TensorFlowTestCase,
parameterized.TestCase):
@parameterized.named_parameters(
[("_RunEagerly", True), ("_RunGraph", False)])
def test_run_functions_eagerly(self, run_eagerly): # pylint: disable=g-wrong-blank-lines
results = []
@def_function.function
def add_two(x):
for _ in range(5):
x += 2
results.append(x)
return x
with test_util.run_functions_eagerly(run_eagerly):
add_two(constant_op.constant(2.))
if context.executing_eagerly():
if run_eagerly:
self.assertTrue(isinstance(t, ops.EagerTensor) for t in results)
else:
self.assertTrue(isinstance(t, ops.Tensor) for t in results)
else:
self.assertTrue(isinstance(t, ops.Tensor) for t in results)
if __name__ == "__main__":
googletest.main()
| {
"content_hash": "9cee4e8e16e30f6b79582aaca7ef6581",
"timestamp": "",
"source": "github",
"line_count": 1097,
"max_line_length": 98,
"avg_line_length": 35.16043755697356,
"alnum_prop": 0.6566591480646081,
"repo_name": "gautam1858/tensorflow",
"id": "5d51ab7a1b0161ee98632bc506c44e6d780ae57e",
"size": "39260",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tensorflow/python/framework/test_util_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "47492"
},
{
"name": "C",
"bytes": "1129549"
},
{
"name": "C#",
"bytes": "13496"
},
{
"name": "C++",
"bytes": "116904214"
},
{
"name": "CMake",
"bytes": "165809"
},
{
"name": "Cython",
"bytes": "5003"
},
{
"name": "Dockerfile",
"bytes": "341994"
},
{
"name": "Go",
"bytes": "2052513"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "1053827"
},
{
"name": "JavaScript",
"bytes": "5772"
},
{
"name": "Jupyter Notebook",
"bytes": "787371"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "9549263"
},
{
"name": "Makefile",
"bytes": "2760"
},
{
"name": "Objective-C",
"bytes": "180638"
},
{
"name": "Objective-C++",
"bytes": "295149"
},
{
"name": "Pawn",
"bytes": "5336"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "43775271"
},
{
"name": "Roff",
"bytes": "5034"
},
{
"name": "Ruby",
"bytes": "7854"
},
{
"name": "Shell",
"bytes": "566970"
},
{
"name": "Smarty",
"bytes": "89664"
},
{
"name": "SourcePawn",
"bytes": "8509"
},
{
"name": "Starlark",
"bytes": "6897556"
},
{
"name": "Swift",
"bytes": "78435"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
from __future__ import print_function
VERSION = "0.4"
import glob, sys
# drivers
from PIL import BdfFontFile
from PIL import PcfFontFile
if len(sys.argv) <= 1:
print("PILFONT", VERSION, "-- PIL font compiler.")
print()
print("Usage: pilfont fontfiles...")
print()
print("Convert given font files to the PIL raster font format.")
print("This version of pilfont supports X BDF and PCF fonts.")
sys.exit(1)
files = []
for f in sys.argv[1:]:
files = files + glob.glob(f)
for f in files:
print(f + "...", end=' ')
try:
fp = open(f, "rb")
try:
p = PcfFontFile.PcfFontFile(fp)
except SyntaxError:
fp.seek(0)
p = BdfFontFile.BdfFontFile(fp)
p.save(f)
except (SyntaxError, IOError):
print("failed")
else:
print("OK")
| {
"content_hash": "91557edc0253fd62a8b3e4f52bbeefd5",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 68,
"avg_line_length": 19.386363636363637,
"alnum_prop": 0.5791324736225087,
"repo_name": "kitanata/resume",
"id": "f18310f79771a22bb015533d56ae9f58f29f403b",
"size": "1053",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "env/bin/pilfont.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4224"
},
{
"name": "CoffeeScript",
"bytes": "385"
},
{
"name": "JavaScript",
"bytes": "37733"
}
],
"symlink_target": ""
} |
__author__ = 'kajal'
from crowdsourcing.serializers.template import *
from rest_framework import viewsets
class TemplateViewSet(viewsets.ModelViewSet):
from crowdsourcing.models import Template
queryset = Template.objects.all()
serializer_class = TemplateSerializer
class TemplateItemViewSet(viewsets.ModelViewSet):
from crowdsourcing.models import TemplateItem
queryset = TemplateItem.objects.all()
serializer_class = TemplateItemSerializer
class TemplateItemPropertiesViewSet(viewsets.ModelViewSet):
from crowdsourcing.models import TemplateItemProperties
queryset = TemplateItemProperties.objects.all()
serializer_class = TemplateItemPropertiesSerializer | {
"content_hash": "b9ad1d7b02fb0fd1df4dc89cb82ccd86",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 59,
"avg_line_length": 35.68421052631579,
"alnum_prop": 0.831858407079646,
"repo_name": "radhikabhanu/crowdsource-platform",
"id": "9e6194cd08c9788a813e242d99c0114af7347e97",
"size": "678",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop2",
"path": "crowdsourcing/viewsets/template.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "304886"
},
{
"name": "HTML",
"bytes": "201118"
},
{
"name": "JavaScript",
"bytes": "108716"
},
{
"name": "Python",
"bytes": "180510"
}
],
"symlink_target": ""
} |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/shield_generator/shared_shd_incom_techscreen_1.iff"
result.attribute_template_id = 8
result.stfName("space/space_item","shd_incom_techscreen_1_n")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | {
"content_hash": "fbc2c79bd18eff732188ac3c73bca808",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 103,
"avg_line_length": 27.23076923076923,
"alnum_prop": 0.7175141242937854,
"repo_name": "anhstudios/swganh",
"id": "866ec48d7cd7436abf38b234a56a7ffe2127f8eb",
"size": "499",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "data/scripts/templates/object/tangible/ship/components/shield_generator/shared_shd_incom_techscreen_1.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "11887"
},
{
"name": "C",
"bytes": "7699"
},
{
"name": "C++",
"bytes": "2357839"
},
{
"name": "CMake",
"bytes": "41264"
},
{
"name": "PLSQL",
"bytes": "42065"
},
{
"name": "Python",
"bytes": "7503510"
},
{
"name": "SQLPL",
"bytes": "42770"
}
],
"symlink_target": ""
} |
from os.path import dirname, join
import pkgutil
import unittest
class TestOpenCVContrib(unittest.TestCase):
def test_haarcascade_jpg(self):
self.check_haarcascade("jpg")
def test_haarcascade_png(self):
self.check_haarcascade("png")
# Adapted from https://realpython.com/face-recognition-with-python/
def check_haarcascade(self, ext):
import cv2.data
import numpy
classifier = cv2.CascadeClassifier(cv2.data.haarcascades +
"haarcascade_frontalface_default.xml")
array = numpy.frombuffer(pkgutil.get_data(__name__, "abba." + ext), numpy.uint8)
image = cv2.imdecode(array, cv2.IMREAD_GRAYSCALE)
faces = classifier.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
noses = [(95, 101), (202, 109), (306, 118), (393, 122)]
for x, y, w, h in faces:
self.assertLess(w, 100)
self.assertLess(h, 100)
for nose_x, nose_y in noses:
if (x < nose_x < x + w) and (y < nose_y < y + h):
noses.remove((nose_x, nose_y))
break
else:
self.fail("Unexpected face: {}, {}, {}, {}".format(x, y, w, h))
if noses:
self.fail("Failed to find expected faces at {}".format(noses))
def test_sift(self):
import cv2.xfeatures2d
img = cv2.imread(join(dirname(__file__), "triangle.png"))
EXPECTED = [
(216, 204, 6), # Top-left corner
(472, 114, 10), # Top-right corner
(765, 868, 12), # Bottom corner
(400, 250, 100), # Apparently represents the triangle as a whole
]
def close(expected, actual, margin):
return abs(expected - actual) <= margin
for point in cv2.xfeatures2d.SIFT_create().detect(img):
for x_expected, y_expected, size_expected in EXPECTED:
if close(x_expected, point.pt[0], 50) and \
close(y_expected, point.pt[1], 50) and \
close(size_expected, point.size, size_expected / 2):
break
else:
self.fail(f"Unexpected point: pt={point.pt}, size={point.size}")
| {
"content_hash": "a461ae6dc6a85a1c4962f283d92eef7c",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 92,
"avg_line_length": 38.81967213114754,
"alnum_prop": 0.5418074324324325,
"repo_name": "chaquo/chaquopy",
"id": "3c7b38762eb434182eed500bbd478a824d03e5b9",
"size": "2368",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "server/pypi/packages/opencv-contrib-python-headless/test/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "30"
},
{
"name": "C",
"bytes": "174108"
},
{
"name": "CMake",
"bytes": "1897"
},
{
"name": "CSS",
"bytes": "991"
},
{
"name": "Cython",
"bytes": "251545"
},
{
"name": "Dockerfile",
"bytes": "6938"
},
{
"name": "Groovy",
"bytes": "42472"
},
{
"name": "Java",
"bytes": "159387"
},
{
"name": "Kotlin",
"bytes": "697"
},
{
"name": "Python",
"bytes": "8043408"
},
{
"name": "Roff",
"bytes": "232"
},
{
"name": "Shell",
"bytes": "53150"
},
{
"name": "Starlark",
"bytes": "2018"
}
],
"symlink_target": ""
} |
from django.db import models
from datetime import date
## TODO: replace this with something that doesn't hit the db. At this point the traffic should be low and it's not much of a concern.
## also we're not pushing the stats anywhere...
class logreport(models.Model):
date = models.DateField()
apikey = models.CharField(max_length=63)
count = models.IntegerField()
def ApiLogIncrement(apikey):
""" increment today's calls from an apikey. Assumes that the client api key has already been filtered out. Returns daily calls."""
today = date.today()
try:
report = logreport.objects.get(apikey=apikey, date=today)
report.count += 1
report.save()
return report.count
except logreport.DoesNotExist:
newreport = logreport(date=today, apikey=apikey, count=1)
newreport.save()
return 1
| {
"content_hash": "f45ceb0632ff8573f870eacdba96074b",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 134,
"avg_line_length": 32.48148148148148,
"alnum_prop": 0.6818700114025086,
"repo_name": "sunlightlabs/read_FEC",
"id": "8f1f8d26e98efaa1ce09bc4a802b502377df9f12",
"size": "877",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fecreader/api/models.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "27432"
},
{
"name": "HTML",
"bytes": "357960"
},
{
"name": "JavaScript",
"bytes": "129989"
},
{
"name": "Python",
"bytes": "1881514"
},
{
"name": "Shell",
"bytes": "10604"
}
],
"symlink_target": ""
} |
"""
scripts for build constraint files and models and for optimizing models
"""
import os.path as osp
import h5py
import sys
from string import lower
from features import BatchRCFeats, MulFeats, QuadSimpleMulFeats, QuadSimpleMulIndFeats, QuadSimpleMulMapIndFeats, QuadSimpleMulBendIndFeats, SimpleMulFeats, SimpleMulGripperFeats, SimpleMulMapIndFeats, LandmarkFeats, TimestepActionMulFeats
from constraints import ConstraintGenerator, BatchCPMargin
from lfd.mmqe.max_margin import MaxMarginModel, BellmanMaxMarginModel
class State(object):
"""
placeholder state
"""
def __init__(self, id, cloud):
self.id = id
self.cloud = cloud
def get_feat_cls(args):
if args.feature_type == 'base':
return BatchRCFeats
elif args.feature_type == 'mul':
return MulFeats
elif args.feature_type == 'mul_s':
return SimpleMulFeats
elif args.feature_type == 'mul_grip':
return SimpleMulGripperFeats
elif args.feature_type == 'mul_s_map':
return SimpleMulMapIndFeats
elif args.feature_type == 'mul_quad':
return QuadSimpleMulFeats
elif args.feature_type == 'mul_quad_ind':
return QuadSimpleMulIndFeats
elif args.feature_type == 'mul_quad_mapind':
return QuadSimpleMulMapIndFeats
elif args.feature_type == 'mul_quad_bendind':
return QuadSimpleMulBendIndFeats
elif args.feature_type == 'landmark':
return LandmarkFeats
elif args.feature_type == 'timestep':
return TimestepActionMulFeats
def get_model_cls(args):
if args.model_type == 'bellman':
return BellmanMaxMarginModel
else:
return MaxMarginModel
def get_constr_generator(args):
feats = get_feat_cls(args)(args.actionfile)
try:
feats.set_landmark_file(args.landmarkfile)
except AttributeError:
pass
marg = BatchCPMargin(feats)
constr_gen = ConstraintGenerator(feats, marg, args.actionfile)
return constr_gen
def check_exists(fname):
if osp.exists(fname):
resp = raw_input("Really Overwrite File {}?[y/N]".format(fname))
if lower(resp) != 'y':
return False
return True
def get_actions(args):
f = h5py.File(args.actionfile, 'r')
actions = f.keys()
f.close()
return actions
def parse_key(key):
# parsing hackery to get a tuple of ints from its str representation
return [int(x) for x in key.strip('(').strip(')').strip(' ').split(',')]
def build_constraints(args):
print "Loading Constraints from {} to {}".format(args.demofile, args.constrfile)
start = time.time()
constr_generator = get_constr_generator(args)
exp_demofile = h5py.File(args.demofile, 'r')
if not check_exists(args.constrfile):
return
constrfile = h5py.File(args.constrfile, 'w')
n_constraints = len([k for k in exp_demofile.keys() if k.startswith('(')])
for i, demo_k in enumerate(exp_demofile):
sys.stdout.write('\rcomputing constraints {}/{}\t\t\t\t'.format(i, n_constraints))
sys.stdout.flush()
demo_info = exp_demofile[demo_k]
state = State(i, demo_info['cloud_xyz'][:])
if demo_k.startswith('f'):
exp_a = 'failure'
else:
demo, timestep = parse_key(demo_k)
## we expect states to be an identifier and a
## point cloud, we won't use the identifier here
exp_a = demo_info['action'][()]
if exp_a.startswith('endstate'): # this is a knot
continue
exp_phi, phi, margins = constr_generator.compute_constrs(state, exp_a, timestep)
constr_generator.store_constrs(exp_phi, phi, margins, exp_a, constrfile, constr_k=str(demo_k))
constrfile.flush()
print ""
print "Constraint Generation Complete\nTime Taken:\t{}".format(time.time() - start)
constrfile.close()
exp_demofile.close()
def build_model(args):
if not check_exists(args.modelfile):
return
print 'Building model into {}.'.format(args.modelfile)
actions = get_actions(args)
start = time.time()
N = len(actions)
feat_cls = get_feat_cls(args)
mm_model = get_model_cls(args)(actions, feat_cls.get_size(N))
mm_model.load_constraints_from_file(args.constrfile, max_constrs=args.max_constraints)
mm_model.save_model(args.modelfile)
print "Model Created and Saved\nTime Taken:\t{}".format(time.time() - start)
def optimize_model(args):
print 'Found model: {}'.format(args.modelfile)
actions = get_actions(args)
feat_cls = get_feat_cls(args)
mm_model = get_model_cls(args).read(args.modelfile, actions, feat_cls.get_size(len(actions)))
try:
mm_model.scale_objective(args.C, args.D)
except TypeError:
mm_model.scale_objective(args.C)
# Use dual simplex method
mm_model.model.setParam('method', 1)
#mm_model.model.setParam('method', 0) # Use primal simplex method to solve model
# mm_model.model.setParam('threads', 1) # Use single thread instead of maximum
# # barrier method (#2) is default for QP, but uses more memory and could lead to error
mm_model.optimize_model()
# mm_model.model.setParam('method', 2) # try solving model with barrier
assert mm_model.model.status == 2
mm_model.save_weights_to_file(args.weightfile)
def do_all(args):
model_dir = '../data/models'
weights_dir = '../data/weights'
_, demofname = osp.split(args.demofile)
labels = osp.splitext(demofname)[0]
args.constrfile = '{}/{}_{}.h5'.format(model_dir, labels, args.feature_type)
args.modelfile=osp.splitext(args.constrfile)[0] + '_{}.mps'.format(args.model_type)
build_constraints(args)
build_model(args)
c_vals = args.C
d_vals = args.D
for c in c_vals:
for d in d_vals:
args.weightfile='{}/{}_{}_c={}_d={}_{}.h5'.format(weights_dir, labels, args.feature_type, c, d, args.model_type)
args.C = c
args.D = d
optimize_model(args)
def parse_arguments():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("feature_type", type=str, choices=['base', 'mul', 'mul_quad', 'mul_s', 'mul_grip', 'mul_s_map', 'mul_quad_ind', 'mul_quad_mapind', 'mul_quad_bendind', 'landmark', 'timestep'])
parser.add_argument("model_type", type=str, choices=['max-margin', 'bellman'])
parser.add_argument("landmarkfile", type=str, nargs='?', default='../data/misc/landmarks.h5')
subparsers = parser.add_subparsers()
# build-constraints subparser
parser_build_constraints = subparsers.add_parser('build-constraints')
parser_build_constraints.add_argument('demofile', nargs='?', default='../data/labels/all_labels_fixed.h5')
parser_build_constraints.add_argument('constrfile', nargs='?', default='../data/models/all_labels_fixed.h5')
parser_build_constraints.add_argument('actionfile', nargs='?', default='../data/misc/actions.h5')
parser_build_constraints.set_defaults(func=build_constraints)
# build-model subparser
parser_build_model = subparsers.add_parser('build-model')
parser_build_model.add_argument('constrfile', nargs='?', default='../data/models/all_labels_fixed.h5')
parser_build_model.add_argument('modelfile', nargs='?', default='../data/models/all_labels_fixed.mps')
parser_build_model.add_argument('actionfile', nargs='?', default='../data/misc/actions.h5')
parser_build_model.add_argument('--max_constraints', type=int, default=1000)
parser_build_model.set_defaults(func=build_model)
# optimize-model subparser
parser_optimize = subparsers.add_parser('optimize-model')
parser_optimize.add_argument('--C', '-c', type=float, default=1)
parser_optimize.add_argument('--D', '-d', type=float, default=1)
parser_optimize.add_argument('--F', '-f', type=float, default=1)
parser_optimize.add_argument('modelfile', nargs='?', default='../data/models/all_labels_fixed.mps')
parser_optimize.add_argument('weightfile', nargs='?', default='../data/weights/all_labels_fixed.h5')
parser_optimize.add_argument('actionfile', nargs='?', default='../data/misc/actions.h5')
parser_optimize.set_defaults(func=optimize_model)
parser_all = subparsers.add_parser('full')
parser_all.add_argument('demofile', nargs='?', default='../data/labels/labels_Jul_3_0.1.h5')
parser_all.add_argument('actionfile', nargs='?', default='../data/misc/actions.h5')
parser_all.add_argument('--max_constraints', type=int, default=1000)
parser_all.add_argument('--C', '-c', type=float, nargs='*', default=[1])
parser_all.add_argument('--D', '-d', type=float, nargs='*', default=[1])
parser_all.add_argument('--F', '-f', type=float, default=1)
parser_all.set_defaults(func=do_all)
return parser.parse_args()
if __name__=='__main__':
import time
args = parse_arguments()
args.func(args)
| {
"content_hash": "3d97dae81ea8be6370b8eb1843f34832",
"timestamp": "",
"source": "github",
"line_count": 208,
"max_line_length": 239,
"avg_line_length": 42.75480769230769,
"alnum_prop": 0.662768469582818,
"repo_name": "rll/lfd",
"id": "d1703456256b16ac20520895c6c94fa5e9466194",
"size": "8893",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lfd/mmqe/build.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C++",
"bytes": "8518"
},
{
"name": "Cuda",
"bytes": "21972"
},
{
"name": "Makefile",
"bytes": "7036"
},
{
"name": "Python",
"bytes": "870155"
},
{
"name": "Shell",
"bytes": "26332"
}
],
"symlink_target": ""
} |
import re
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.http import HttpResponse, Http404
from django.core.urlresolvers import reverse, resolve
from django.contrib import messages
from teacher.apps.accounts.authorization import is_teacher
from teacher.apps.accounts.tools import set_user_message
class LoginRequiredMiddleware(object):
BASE_TEACHER_URL = '/teacher/'
REQUIRED_LOGIN_URL = (
)
LOGIN_REQUIRED_URLS_EXCEPTIONS = (
r''+ BASE_TEACHER_URL + 'account/login/(.*)$',
r''+ BASE_TEACHER_URL + '/$',
r''+ BASE_TEACHER_URL + 'account/register/(.*)$',
r''+ BASE_TEACHER_URL + 'account/logout/(.*)$',
)
"""
Middleware component that wraps the login_required decorator around
matching URL patterns. To use, add the class to MIDDLEWARE_CLASSES and
define LOGIN_REQUIRED_URLS and LOGIN_REQUIRED_URLS_EXCEPTIONS in your
settings.py. For example:
------
------
LOGIN_REQUIRED_URLS is where you define URL patterns; each pattern must
be a valid regex.
LOGIN_REQUIRED_URLS_EXCEPTIONS is, conversely, where you explicitly
define any exceptions (like login and logout URLs).
"""
def __init__(self):
self.required = tuple(re.compile(url) for url in self.REQUIRED_LOGIN_URL)
self.exceptions = tuple(re.compile(url) for url in self.LOGIN_REQUIRED_URLS_EXCEPTIONS)
def process_view(self, request, view_func, view_args, view_kwargs):
#FIXME check for teacher
# No need to process URLs if user already logged in
# An exception match should immediately return None
for url in self.exceptions:
if url.match(request.path):
requested_url = resolve (request.path)
try :
name = requested_url.url_name
if name == 'teacher_account_logout' :
return None
if request.user.is_authenticated() and is_teacher(request):
set_user_message(request, messages.INFO, "your are already logged In")
return redirect ('/teacher/')
except Exception, e:
raise Http404
return None
for url in self.required:
if url.match(request.path):
if request.user.is_authenticated() and is_teacher (request):
return redirect ('/teacher')
else :
return login_required(view_func)(request, *view_args, **view_kwargs)
# Explicitly return None for all non-matching requests
return None | {
"content_hash": "f5275f10c8efad5142ba6f6ccdecf60d",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 95,
"avg_line_length": 39.56521739130435,
"alnum_prop": 0.6142857142857143,
"repo_name": "houssemFat/MeeM-Dev",
"id": "6d2610c22149f5c0dda57ce83842b7c6e25dc369",
"size": "2730",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "teacher/middleware/access.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "54148"
},
{
"name": "HTML",
"bytes": "360877"
},
{
"name": "JavaScript",
"bytes": "1651985"
},
{
"name": "Nginx",
"bytes": "1597"
},
{
"name": "PHP",
"bytes": "3195"
},
{
"name": "Python",
"bytes": "374180"
},
{
"name": "Smarty",
"bytes": "7600"
}
],
"symlink_target": ""
} |
from pig_util import outputSchema
@outputSchema('value:int')
def return_one():
"""
Return the integer value 1
"""
return 1 | {
"content_hash": "ffa120276ed8569b1b1573448cead7a4",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 33,
"avg_line_length": 16.875,
"alnum_prop": 0.6666666666666666,
"repo_name": "MinerKasch/HadoopWithPython",
"id": "0cd7fe2fdba42d3fc378b188562e076e873a5416",
"size": "135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pig/udfs/my_first_udf.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PigLatin",
"bytes": "2240"
},
{
"name": "Python",
"bytes": "10790"
}
],
"symlink_target": ""
} |
import getpass
import requests
import os
import sys
import json
STRIKETRACKER_URL = os.environ['STRIKETRACKER_URL'] if 'STRIKETRACKER_URL' in os.environ else 'https://striketracker.highwinds.com'
if len(sys.argv) != 3:
print "Usage: python add_permission.py [account hash] [userId]"
sys.exit()
PARENT_ACCOUNT = sys.argv[1]
USERID = sys.argv[2] # Integer ID for user that is to be updated
with open('%s_%s.txt' % (PARENT_ACCOUNT, USERID), 'w') as log:
OAUTH_TOKEN = os.environ['STRIKETRACKER_TOKEN']
# Get user
get_response = requests.get(
STRIKETRACKER_URL + "/api/accounts/{accountHash}/users/{userId}".format(
accountHash=PARENT_ACCOUNT,
userId=USERID),
headers={"Authorization": "Bearer %s" % OAUTH_TOKEN, "Content-Type": "application/json"})
user = get_response.json()
if user['userType'] != 'Normal':
log.write("User is of type %s" % user['userType'])
sys.exit(1)
log.write("BEFORE:")
json.dump(user, log, indent=4, separators=(',', ': '))
phone = user['phone'] or '9'
if user['roles']['userAccount']['content'] == 'EDIT':
log.write("\nAlready has CONTENT EDIT\n\n\n")
sys.exit(1)
# Add content edit permission to a user so they can log into FTP
update_response = requests.put(
STRIKETRACKER_URL + "/api/accounts/{accountHash}/users/{userId}".format(
accountHash=PARENT_ACCOUNT,
userId=USERID),
headers={"Authorization": "Bearer %s" % OAUTH_TOKEN, "Content-Type": "application/json"},
data=json.dumps({
"phone": phone,
"roles": {
"userAccount": {
"content": "EDIT"
}
}
}))
user_after = update_response.json()
log.write("\n\nAFTER:")
json.dump(user_after, log, indent=4, separators=(',', ': '))
log.write("\n\n\n") | {
"content_hash": "1d277a5e78757b1c3d46aec6a6fa3cf1",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 131,
"avg_line_length": 36.67307692307692,
"alnum_prop": 0.5967488201363398,
"repo_name": "Highwinds/CDNWS-examples",
"id": "63b5a7a806635d4994586cf32a82a17c0d63bbd6",
"size": "1907",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "add_permission/add_permission.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "1601"
},
{
"name": "Python",
"bytes": "19459"
}
],
"symlink_target": ""
} |
import codesters
import math
def go_to(x,y):
sprite = codesters.Sprite()
sprite.go_to(x,y)
return [sprite.get_x(),sprite.get_y()]
def test_go_to():
coords = go_to(200,300)
x = coords[0]
y = coords[1]
assert x == 200 and y == 300
def glide_to(x,y):
sprite = codesters.Sprite()
sprite.go_to(x,y)
return [sprite.get_x(),sprite.get_y()]
def test_glide_to():
coords = glide_to(200,300)
x = coords[0]
y = coords[1]
assert x == 200 and y == 300
def right(amount):
sprite = codesters.Sprite()
sprite.move_right(amount)
return sprite.get_x()
def test_right():
amount_to_move_right = 79
new_x = right(amount_to_move_right)
assert amount_to_move_right == new_x
def left(amount):
sprite = codesters.Sprite()
sprite.move_left(amount)
return sprite.get_x()
def test_left():
amount_to_move_left = -100
new_x = left(amount_to_move_left)
assert amount_to_move_left == -new_x
def down(amount):
sprite = codesters.Sprite()
sprite.move_down(amount)
return sprite.get_y()
def test_down():
amount_to_move_down = 54
new_y = down(amount_to_move_down)
assert amount_to_move_down == -new_y
def up(amount):
sprite = codesters.Sprite()
sprite.move_up(amount)
return sprite.get_y()
def test_up():
amount_to_move_up = 63
new_y = up(amount_to_move_up)
assert amount_to_move_up == new_y
def clockwise(amount):
sprite = codesters.Sprite()
sprite.turn_clockwise(amount)
return sprite.get_rotation()
def test_clockwise():
amount_to_turn_clockwise = 78
new_heading = clockwise(amount_to_turn_clockwise)
assert new_heading == -amount_to_turn_clockwise
def counterclockwise(amount):
sprite = codesters.Sprite()
sprite.turn_counterclockwise(amount)
return sprite.get_rotation()
def test_counterclockwise():
amount_to_turn_counterclockwise = -0
new_heading = counterclockwise(amount_to_turn_counterclockwise)
assert new_heading == amount_to_turn_counterclockwise
def forward(amount, angle):
sprite = codesters.Sprite()
sprite.turn_counterclockwise(angle)
sprite.forward(amount)
return [sprite.get_x(), sprite.get_y(), sprite.get_rotation()]
def test_forward():
turn_angle = -78
step_size = -82
coords = forward(step_size, turn_angle)
assert coords[0] == step_size * math.cos(turn_angle * math.pi/180)
assert coords[1] == step_size * math.sin(turn_angle * math.pi/180)
assert coords[2] == turn_angle
def backward(amount, angle):
sprite = codesters.Sprite()
sprite.turn_counterclockwise(angle)
sprite.backward(amount)
return [-sprite.get_x(), -sprite.get_y(), sprite.get_rotation()]
def test_backward():
turn_angle = 40
step_size = 100
coords = backward(step_size, turn_angle)
assert coords[0] == step_size * math.cos(turn_angle * math.pi/180)
assert coords[1] == step_size * math.sin(turn_angle * math.pi/180)
assert coords[2] == turn_angle
def width(amount):
sprite = codesters.Sprite()
sprite.set_width(amount)
return sprite.get_width()
def test_width():
amount = -32
new_width = width(amount)
assert amount == new_width
def height(amount):
sprite = codesters.Sprite()
sprite.set_height(amount)
return sprite.get_height()
def test_height():
amount = 44
new_height = height(amount)
assert amount == new_height
def size(amount):
sprite = codesters.Sprite()
sprite.set_size(amount)
return sprite.get_size()
def test_size():
amount = -0.4
new_size = size(amount)
assert amount == new_size | {
"content_hash": "907b483d7c98186fc38183c7d53489de",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 70,
"avg_line_length": 25.514084507042252,
"alnum_prop": 0.6538780016560861,
"repo_name": "codestersnyc/codesters-graphics",
"id": "fe6db5e1dd24e84aa9d5656eace9b3787e850766",
"size": "3623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_codesters.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "169198"
}
],
"symlink_target": ""
} |
from collections import namedtuple
Add = namedtuple('Add', 'location left right')
Sub = namedtuple('Sub', 'location left right')
Mul = namedtuple('Mul', 'location left right')
Div = namedtuple('Div', 'location left right')
Pow = namedtuple('Pow', 'location left right')
UnaryMin = namedtuple('UnaryMin', 'location operand')
Number = namedtuple('Number', 'location value')
Embedded = namedtuple('Embedded', 'location content')
| {
"content_hash": "545870e11a4bcbeea46bf2a511b0d551",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 53,
"avg_line_length": 38.90909090909091,
"alnum_prop": 0.7313084112149533,
"repo_name": "TomiBelan/multiparser",
"id": "b50adf38095e1731962c2d19596e2f4d93d42afe",
"size": "429",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "toycalc/ast.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Lua",
"bytes": "1736"
},
{
"name": "Makefile",
"bytes": "984"
},
{
"name": "Python",
"bytes": "57950"
},
{
"name": "Shell",
"bytes": "173"
}
],
"symlink_target": ""
} |
""" smashlib.util.ipy
import shortcuts for ipython. this also might help to keep
smashlib in sync with changing ipython target versions?
"""
import re
import keyword
from IPython.utils.coloransi import TermColors
from goulash.cache import MWT
from peak.util.imports import lazyModule
logging = lazyModule('smashlib._logging')
r_cmd = re.compile('^[\w-]+$')
def green(txt):
return TermColors.Green + txt + TermColors.Normal
def uninstall_prefilter(HandlerOrCheckerClass):
""" uninstalls argument from running IPython instance,
where the argument may be either a class describing either
a prefilter Handler or a Checker.
"""
# are singletons involved here? not sure we can use
# manager.unregister_handler() etc, since it does an
# instance check instead of a class check.
ip = get_ipython()
# uninstall if handler
handlers = ip.prefilter_manager.handlers
for handler_name, handler in handlers.items():
if isinstance(handler, HandlerOrCheckerClass):
break
del handlers[handler_name]
# uninstall if checker
checker_list = ip.prefilter_manager._checkers
for tmp in checker_list:
if isinstance(tmp, HandlerOrCheckerClass):
del checker_list[checker_list.index(tmp)]
@MWT(timeout=500)
def have_command_alias(x):
""" this helper function is fairly expensive to be running on
(almost) every input line. caching seems tricky but necessary
"""
if not r_cmd.match(x):
return False
blacklist = [
# posix line oriented, not very useful so
# this should not override ipython edit
'ed',
# often used as in ip=get_ipython()
'ip',
] + keyword.kwlist
if x in blacklist:
result = False
else:
alias_list = get_ipython().alias_manager.aliases
cmd_list = set()
for alias, cmd in alias_list:
if alias == cmd:
cmd_list = cmd_list.union(set([alias]))
result = x in cmd_list
logging.smash_log.info('"{0}"? {1}'.format(x, result))
return result
have_alias = have_command_alias
def register_prefilter(Checker, Handler):
ip = get_ipython()
pm = ip.prefilter_manager
kargs = dict(
shell=pm.shell,
prefilter_manager=pm,
config=pm.config)
handler = Handler(**kargs)
if Checker is not None: # hack, remove with dotchecker exists
checker = Checker(**kargs)
ip.prefilter_manager.register_checker(checker)
else:
checker = None
ip.prefilter_manager.register_handler(Handler.handler_name, handler, [])
return checker, handler
| {
"content_hash": "41a55c260cde9f044cfc3daa799646e6",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 76,
"avg_line_length": 31.31764705882353,
"alnum_prop": 0.6562734785875282,
"repo_name": "mattvonrocketstein/smash",
"id": "9ee8de3d61fe4173dfcfbfd9866c9f1775c3e71e",
"size": "2662",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "smashlib/util/ipy.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "162188"
},
{
"name": "HTML",
"bytes": "32106"
},
{
"name": "JavaScript",
"bytes": "1615935"
},
{
"name": "Makefile",
"bytes": "550"
},
{
"name": "Python",
"bytes": "4934398"
},
{
"name": "Shell",
"bytes": "2990"
}
],
"symlink_target": ""
} |
from universe.envs.vnc_core_env.vnc_core_env import GymCoreEnv, GymCoreSyncEnv
from universe.envs.vnc_core_env.translator import AtariTranslator, CartPoleTranslator
| {
"content_hash": "dc09e5c751af7e8f5496b84c4902dae4",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 85,
"avg_line_length": 82.5,
"alnum_prop": 0.8545454545454545,
"repo_name": "rht/universe",
"id": "83b202752c478a1f4ca0d7fd00337378c80ba159",
"size": "165",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "universe/envs/vnc_core_env/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "2718"
},
{
"name": "Python",
"bytes": "536345"
}
],
"symlink_target": ""
} |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class RetrieveStatistics(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the RetrieveStatistics Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(RetrieveStatistics, self).__init__(temboo_session, '/Library/SendGrid/WebAPI/Statistics/RetrieveStatistics')
def new_input_set(self):
return RetrieveStatisticsInputSet()
def _make_result_set(self, result, path):
return RetrieveStatisticsResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return RetrieveStatisticsChoreographyExecution(session, exec_id, path)
class RetrieveStatisticsInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the RetrieveStatistics
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_APIKey(self, value):
"""
Set the value of the APIKey input for this Choreo. ((required, string) The API Key obtained from SendGrid.)
"""
super(RetrieveStatisticsInputSet, self)._set_input('APIKey', value)
def set_APIUser(self, value):
"""
Set the value of the APIUser input for this Choreo. ((required, string) The username registered with SendGrid.)
"""
super(RetrieveStatisticsInputSet, self)._set_input('APIUser', value)
def set_Days(self, value):
"""
Set the value of the Days input for this Choreo. ((optional, integer) The number of days (greater than 0) for which block data will be retrieved.)
"""
super(RetrieveStatisticsInputSet, self)._set_input('Days', value)
def set_EndDate(self, value):
"""
Set the value of the EndDate input for this Choreo. ((optional, string) Specify the end of the date range for which blocks are to be retireved. The specified date must be in YYYY-MM-DD format.)
"""
super(RetrieveStatisticsInputSet, self)._set_input('EndDate', value)
def set_ResponseFormat(self, value):
"""
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format of the response from SendGrid, in either json, or xml. Default is set to json.)
"""
super(RetrieveStatisticsInputSet, self)._set_input('ResponseFormat', value)
def set_StartDate(self, value):
"""
Set the value of the StartDate input for this Choreo. ((optional, string) The start of the date range for which blocks are to be retireved. The specified date must be in YYYY-MM-DD format, and must be earlier than the EndDate variable value.)
"""
super(RetrieveStatisticsInputSet, self)._set_input('StartDate', value)
class RetrieveStatisticsResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the RetrieveStatistics Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from SendGrid. The format corresponds to the ResponseFormat input. Default is json.)
"""
return self._output.get('Response', None)
class RetrieveStatisticsChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return RetrieveStatisticsResultSet(response, path)
| {
"content_hash": "77685a9e3c9170f868f4f2a4b38bf369",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 250,
"avg_line_length": 46.1219512195122,
"alnum_prop": 0.7017451084082496,
"repo_name": "jordanemedlock/psychtruths",
"id": "3ecdab0de352ec87e2442e7189c4e55c6ca6dafb",
"size": "4633",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "temboo/core/Library/SendGrid/WebAPI/Statistics/RetrieveStatistics.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18544"
},
{
"name": "HTML",
"bytes": "34650"
},
{
"name": "JavaScript",
"bytes": "423"
},
{
"name": "PHP",
"bytes": "1097"
},
{
"name": "Python",
"bytes": "23444578"
}
],
"symlink_target": ""
} |
"""
Tests - Deuce Client - Auth - OpenStack Authentication
"""
import datetime
import time
import uuid
from unittest import TestCase
import contextlib
import keystoneclient.exceptions
import mock
import deuceclient.auth
import deuceclient.auth.openstackauth as openstackauth
import deuceclient.tests.test_auth
from deuceclient.tests import fastsleep
class FakeAccess(object):
"""Fake Keystone Access Object for testing
"""
raise_until = 0
raise_counter = 0
raise_error = False
expire_time = None
user_data = {
'tenant': {
'id': None,
'name': None
},
'user': {
'id': None,
'name': None
}
}
def __init__(self):
pass
@classmethod
def raise_error(cls, raise_or_not):
cls.raise_error = raise_or_not
@classmethod
def raise_reset(cls, raise_until=0, raise_error=False):
cls.raise_until = raise_until
cls.raise_error = raise_error
cls.raise_counter = 0
@property
def tenant_id(self):
if self.__class__.user_data['tenant']['id'] is None:
raise RuntimeError('mocking')
else:
return self.__class__.user_data['tenant']['id']
@property
def tenant_name(self):
if self.__class__.user_data['tenant']['name'] is None:
raise RuntimeError('mocking')
else:
return self.__class__.user_data['tenant']['name']
@property
def user_id(self):
if self.__class__.user_data['user']['id'] is None:
raise RuntimeError('mocking')
else:
return self.__class__.user_data['user']['id']
@property
def username(self):
if self.__class__.user_data['user']['name'] is None:
raise RuntimeError('mocking')
else:
return self.__class__.user_data['user']['name']
@property
def auth_token(self):
if self.__class__.raise_until > 0:
self.__class__.raise_error = (
self.__class__.raise_counter < self.__class__.raise_until)
if self.__class__.raise_error:
self.__class__.raise_counter = self.__class__.raise_counter + 1
if self.__class__.raise_error is True:
raise keystoneclient.exceptions.AuthorizationFailure('mocking')
else:
return 'token_{0:}'.format(str(uuid.uuid4()))
@property
def expires(self):
if self.__class__.expire_time is None:
print('Raising exception')
raise keystoneclient.exceptions.AuthorizationFailure('mocking')
else:
print('Returning')
return self.__class__.expire_time
def will_expire_soon(self, stale_duration=None):
if self.__class__.expire_time is None:
# Expired already
return True
else:
check_time = self.__class__.expire_time
if stale_duration is not None:
# otherwise we need to apply stale_duration and check
check_time = check_time + \
datetime.timedelta(seconds=stale_duration)
now_time = datetime.datetime.utcnow()
return (check_time <= now_time)
class FakeClient(object):
"""Fake Keystone Client Object for testing
"""
def __init__(self, *args, **kwargs):
pass
def get_raw_token_from_identity_service(self, *args, **kwargs):
return FakeAccess()
class OpenStackAuthTest(TestCase,
deuceclient.tests.test_auth.AuthenticationBaseTest):
def setUp(self):
time.sleep = fastsleep
keystone_discovery_version_data = [
{
"id": "v1.0",
"links": [
{
"href": "https://identity.api.rackspacecloud.com/"
"v1.0",
"rel": "self"
}
],
"status": "DEPRECATED",
"updated": "2011-07-19T22:30:00Z"
},
{
"id": "v1.1",
"links": [
{
"href": "http://docs.rackspacecloud.com/"
"auth/api/v1.1/auth.wadl",
"rel": "describedby",
"type": "application/vnd.sun.wadl+xml"
}
],
"status": "CURRENT",
"updated": "2012-01-19T22:30:00.25Z"
},
{
"id": "v2.0",
"links": [
{
"href":
"http://docs.rackspacecloud.com/"
"auth/api/v2.0/auth.wadl",
"rel": "describedby",
"type": "application/vnd.sun.wadl+xml"
}
],
"status": "CURRENT",
"updated": "2012-01-19T22:30:00.25Z"
}
]
def create_authengine(self, userid=None, usertype=None,
credentials=None, auth_method=None,
datacenter=None, auth_url=None):
return openstackauth.OpenStackAuthentication(userid=userid,
usertype=usertype,
credentials=credentials,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
def test_parameter_no_authurl(self):
userid = self.create_userid()
apikey = self.create_apikey()
with self.assertRaises(deuceclient.auth.AuthenticationError) \
as auth_error:
authengine = self.create_authengine(userid=userid,
usertype='user_id',
credentials=apikey,
auth_method=None,
datacenter='test',
auth_url=None)
def test_keystone_parameters(self):
userid = self.create_userid()
username = self.create_username()
tenantid = self.create_tenant_id()
tenantname = self.create_tenant_name()
apikey = self.create_apikey()
password = self.create_password()
token = self.create_token()
datacenter = 'test'
auth_url = 'https://identity.api.rackspacecloud.com'
usertype = 'user_id'
auth_method = 'apikey'
mok_ky_gen_client = 'keystoneclient.client.Client'
mok_ky_v2_client = 'keystoneclient.v2_0.client.Client'
with mock.patch(mok_ky_gen_client) as keystone_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client:
keystone_mock.return_value = True
keystone_v2_client.return_value = True
authengine = self.create_authengine(userid=userid,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
client = authengine.get_client()
try:
kargs, kwargs = keystone_mock.call_args
except TypeError:
kargs, kwargs = keystone_v2_client.call_args
self.assertIn('username', kwargs)
self.assertEqual(kwargs['username'], userid)
self.assertIn('password', kwargs)
self.assertEqual(kwargs['password'], apikey)
self.assertIn('auth_url', kwargs)
self.assertEqual(kwargs['auth_url'], auth_url)
usertype = 'user_name'
auth_method = 'password'
with mock.patch(mok_ky_gen_client) as keystone_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client:
keystone_mock.return_value = True
keystone_v2_client.return_value = True
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=password,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
client = authengine.get_client()
try:
kargs, kwargs = keystone_mock.call_args
except TypeError:
kargs, kwargs = keystone_v2_client.call_args
self.assertIn('username', kwargs)
self.assertEqual(kwargs['username'], username)
self.assertIn('password', kwargs)
self.assertEqual(kwargs['password'], password)
self.assertIn('auth_url', kwargs)
self.assertEqual(kwargs['auth_url'], auth_url)
usertype = 'tenant_name'
auth_method = 'token'
with mock.patch(mok_ky_gen_client) as keystone_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client:
keystone_mock.return_value = True
keystone_v2_client.return_value = True
authengine = self.create_authengine(userid=tenantname,
usertype=usertype,
credentials=token,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
client = authengine.get_client()
try:
kargs, kwargs = keystone_mock.call_args
except TypeError:
kargs, kwargs = keystone_v2_client.call_args
self.assertIn('tenant_name', kwargs)
self.assertEqual(kwargs['tenant_name'], tenantname)
self.assertIn('token', kwargs)
self.assertEqual(kwargs['token'], token)
self.assertIn('auth_url', kwargs)
self.assertEqual(kwargs['auth_url'], auth_url)
usertype = 'tenant_id'
auth_method = 'token'
with mock.patch(mok_ky_gen_client) as keystone_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client:
keystone_mock.return_value = True
keystone_v2_client.return_value = True
authengine = self.create_authengine(userid=tenantid,
usertype=usertype,
credentials=token,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
client = authengine.get_client()
try:
kargs, kwargs = keystone_mock.call_args
except TypeError:
kargs, kwargs = keystone_v2_client.call_args
self.assertIn('tenant_id', kwargs)
self.assertEqual(kwargs['tenant_id'], tenantid)
self.assertIn('token', kwargs)
self.assertEqual(kwargs['token'], token)
self.assertIn('auth_url', kwargs)
self.assertEqual(kwargs['auth_url'], auth_url)
usertype = 'bison'
with mock.patch(mok_ky_gen_client) as keystone_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client:
keystone_mock.return_value = False
keystone_v2_client.return_value = False
authengine = self.create_authengine(userid=tenantid,
usertype=usertype,
credentials=token,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
with self.assertRaises(deuceclient.auth.base.AuthenticationError) \
as auth_error:
client = authengine.get_client()
self.assertIn('usertype', str(auth_error))
usertype = 'tenant_id'
auth_method = 'yak'
with mock.patch(mok_ky_gen_client) as keystone_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client:
keystone_mock.return_value = False
keystone_v2_client.return_value = False
authengine = self.create_authengine(userid=tenantid,
usertype=usertype,
credentials=token,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
with self.assertRaises(deuceclient.auth.base.AuthenticationError) \
as auth_error:
client = authengine.get_client()
self.assertIn('auth_method', str(auth_error))
def test_get_token_invalid_client_username_password(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
with mock.patch(
'deuceclient.auth.openstackauth.OpenStackAuthentication.get_client'
) as mok_get_client:
mok_get_client.side_effect = \
deuceclient.auth.AuthenticationError('mock')
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
with self.assertRaises(deuceclient.auth.AuthenticationError) \
as auth_error:
authengine.GetToken(retry=0)
def test_get_token_invalid_client_tenant_id_token(self):
usertype = 'tenant_id'
username = self.create_tenant_id()
token = self.create_token()
auth_method = 'token'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
with mock.patch(
'deuceclient.auth.openstackauth.OpenStackAuthentication.get_client'
) as mok_get_client:
mok_get_client.side_effect = \
deuceclient.auth.AuthenticationError('mock')
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=token,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
with self.assertRaises(deuceclient.auth.AuthenticationError) \
as auth_error:
authengine.GetToken(retry=0)
def test_get_token_failed(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
# Because the mock strings are so long, we're going to store them
# in variables here to keep the mocking statements short
mok_ky_base = 'keystoneclient'
mok_ky_httpclient = '{0:}.httpclient.HTTPClient'.format(mok_ky_base)
mok_ky_auth = '{0:}.authenticate'.format(mok_ky_httpclient)
mok_ky_v2_client = '{0:}.v2_0.client.Client'.format(mok_ky_base)
mok_ky_v2_rawtoken = '{0:}.get_raw_token_from_identity_service'\
.format(mok_ky_v2_client)
mok_ky_discover = '{0:}.discover'.format(mok_ky_base)
mok_ky_discovery = '{0:}.Discover'.format(mok_ky_discover)
mok_ky_discovery_init = '{0:}.__init__'.format(mok_ky_discovery)
mok_ky_discover_client = '{0:}.create_client'.format(mok_ky_discovery)
mok_ky_discover_int = '{0:}._discover'.format(mok_ky_base)
mok_ky_discover_version = '{0:}.get_version_data'\
.format(mok_ky_discover_int)
with mock.patch(mok_ky_auth) as keystone_auth_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client,\
mock.patch(mok_ky_v2_rawtoken) as keystone_raw_token_mock,\
mock.patch(mok_ky_discover_version) as keystone_discover_ver,\
mock.patch(mok_ky_discover_client) as keystone_discover_cli:
keystone_auth_mock.return_value = True
keystone_discover_ver.return_value = \
self.keystone_discovery_version_data
keystone_discover_cli.return_value = FakeClient()
keystone_v2_client.return_value = FakeClient()
FakeAccess.raise_until = 4
FakeAccess.raise_counter = 0
keystone_raw_token_mock.return_value = FakeAccess()
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
with self.assertRaises(deuceclient.auth.AuthenticationError) \
as auth_error:
authengine.GetToken(retry=FakeAccess.raise_until - 1)
def test_get_token_success_username_password(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
# Because the mock strings are so long, we're going to store them
# in variables here to keep the mocking statements short
mok_ky_base = 'keystoneclient'
mok_ky_httpclient = '{0:}.httpclient.HTTPClient'.format(mok_ky_base)
mok_ky_auth = '{0:}.authenticate'.format(mok_ky_httpclient)
mok_ky_v2_client = '{0:}.v2_0.client.Client'.format(mok_ky_base)
mok_ky_v2_rawtoken = '{0:}.get_raw_token_from_identity_service'\
.format(mok_ky_v2_client)
mok_ky_discover = '{0:}.discover'.format(mok_ky_base)
mok_ky_discovery = '{0:}.Discover'.format(mok_ky_discover)
mok_ky_discovery_init = '{0:}.__init__'.format(mok_ky_discovery)
mok_ky_discover_client = '{0:}.create_client'.format(mok_ky_discovery)
mok_ky_discover_int = '{0:}._discover'.format(mok_ky_base)
mok_ky_discover_version = '{0:}.get_version_data'\
.format(mok_ky_discover_int)
with mock.patch(mok_ky_auth) as keystone_auth_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client,\
mock.patch(mok_ky_v2_rawtoken) as keystone_raw_token_mock,\
mock.patch(mok_ky_discover_version) as keystone_discover_ver,\
mock.patch(mok_ky_discover_client) as keystone_discover_cli:
keystone_auth_mock.return_value = True
keystone_discover_ver.return_value = \
self.keystone_discovery_version_data
keystone_discover_cli.return_value = FakeClient()
keystone_v2_client.return_value = FakeClient()
FakeAccess.raise_until = 4
FakeAccess.raise_counter = 0
keystone_raw_token_mock.return_value = FakeAccess()
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
token = authengine.GetToken(retry=FakeAccess.raise_until)
def test_get_token_success_tenantid_token(self):
usertype = 'tenant_id'
username = self.create_tenant_id()
token = self.create_token()
auth_method = 'token'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
# Because the mock strings are so long, we're going to store them
# in variables here to keep the mocking statements short
mok_ky_base = 'keystoneclient'
mok_ky_httpclient = '{0:}.httpclient.HTTPClient'.format(mok_ky_base)
mok_ky_auth = '{0:}.authenticate'.format(mok_ky_httpclient)
mok_ky_v2_client = '{0:}.v2_0.client.Client'.format(mok_ky_base)
mok_ky_v2_rawtoken = '{0:}.get_raw_token_from_identity_service'\
.format(mok_ky_v2_client)
mok_ky_discover = '{0:}.discover'.format(mok_ky_base)
mok_ky_discovery = '{0:}.Discover'.format(mok_ky_discover)
mok_ky_discovery_init = '{0:}.__init__'.format(mok_ky_discovery)
mok_ky_discover_client = '{0:}.create_client'.format(mok_ky_discovery)
mok_ky_discover_int = '{0:}._discover'.format(mok_ky_base)
mok_ky_discover_version = '{0:}.get_version_data'\
.format(mok_ky_discover_int)
with mock.patch(mok_ky_auth) as keystone_auth_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client,\
mock.patch(mok_ky_v2_rawtoken) as keystone_raw_token_mock,\
mock.patch(mok_ky_discover_version) as keystone_discover_ver,\
mock.patch(mok_ky_discover_client) as keystone_discover_cli:
keystone_auth_mock.return_value = True
keystone_discover_ver.return_value = \
self.keystone_discovery_version_data
keystone_discover_cli.return_value = FakeClient()
keystone_v2_client.return_value = FakeClient()
FakeAccess.raise_until = 4
FakeAccess.raise_counter = 0
keystone_raw_token_mock.return_value = FakeAccess()
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=token,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
token = authengine.GetToken(retry=FakeAccess.raise_until)
def test_is_expired_no_client(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
self.assertTrue(authengine.IsExpired())
def test_is_expired_result(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
# Because the mock strings are so long, we're going to store them
# in variables here to keep the mocking statements short
mok_ky_base = 'keystoneclient'
mok_ky_httpclient = '{0:}.httpclient.HTTPClient'.format(mok_ky_base)
mok_ky_auth = '{0:}.authenticate'.format(mok_ky_httpclient)
mok_ky_v2_client = '{0:}.v2_0.client.Client'.format(mok_ky_base)
mok_ky_v2_rawtoken = '{0:}.get_raw_token_from_identity_service'\
.format(mok_ky_v2_client)
mok_ky_discover = '{0:}.discover'.format(mok_ky_base)
mok_ky_discovery = '{0:}.Discover'.format(mok_ky_discover)
mok_ky_discovery_init = '{0:}.__init__'.format(mok_ky_discovery)
mok_ky_discover_client = '{0:}.create_client'.format(mok_ky_discovery)
mok_ky_discover_int = '{0:}._discover'.format(mok_ky_base)
mok_ky_discover_version = '{0:}.get_version_data'\
.format(mok_ky_discover_int)
with mock.patch(mok_ky_auth) as keystone_auth_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client,\
mock.patch(mok_ky_v2_rawtoken) as keystone_raw_token_mock,\
mock.patch(mok_ky_discover_version) as keystone_discover_ver,\
mock.patch(mok_ky_discover_client) as keystone_discover_cli:
keystone_auth_mock.return_value = True
keystone_discover_ver.return_value = \
self.keystone_discovery_version_data
keystone_discover_cli.return_value = FakeClient()
keystone_v2_client.return_value = FakeClient()
FakeAccess.raise_until = 4
FakeAccess.raise_counter = 0
keystone_raw_token_mock.return_value = FakeAccess()
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
token = authengine.GetToken(retry=FakeAccess.raise_until)
FakeAccess.expire_time = None
self.assertTrue(authengine.IsExpired())
FakeAccess.expire_time = datetime.datetime.utcnow()
self.assertFalse(authengine.IsExpired(fuzz=5))
self.assertTrue(authengine.IsExpired())
FakeAccess.expire_time = datetime.datetime.utcnow() + \
datetime.timedelta(seconds=5)
self.assertFalse(authengine.IsExpired())
self.assertTrue(authengine.IsExpired(fuzz=-10))
sleep_time = (datetime.datetime.utcnow() - FakeAccess.expire_time)\
.total_seconds()
if sleep_time > 0:
time.sleep(sleep_time + 1)
self.assertFalse(authengine.IsExpired())
# We must reset expire_time when we're done
FakeAccess.expire_time = None
def test_auth_token_expired(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
mok_isexpired = 'deuceclient.auth.openstackauth' \
'.OpenStackAuthentication.IsExpired'
mok_gettoken = 'deuceclient.auth.openstackauth' \
'.OpenStackAuthentication.GetToken'
with mock.patch(mok_isexpired) as mock_isexpired,\
mock.patch(mok_gettoken) as mock_gettoken:
mock_isexpired.return_value = True
token = self.create_token()
mock_gettoken.return_value = token
self.assertEqual(token, authengine.AuthToken)
def test_auth_token_will_expire(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
mok_isexpired = 'deuceclient.auth.openstackauth' \
'.OpenStackAuthentication.IsExpired'
mok_gettoken = 'deuceclient.auth.openstackauth' \
'.OpenStackAuthentication.GetToken'
with mock.patch(mok_isexpired) as mock_isexpired,\
mock.patch(mok_gettoken) as mock_gettoken:
mock_isexpired.side_effect = [False, True]
token = self.create_token()
mock_gettoken.return_value = token
self.assertEqual(token, authengine.AuthToken)
def test_auth_token_cached(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
mok_isexpired = 'deuceclient.auth.openstackauth' \
'.OpenStackAuthentication.IsExpired'
mok_authtoken = 'deuceclient.auth.openstackauth' \
'.OpenStackAuthentication.__access.auth_token'
# Because the mock strings are so long, we're going to store them
# in variables here to keep the mocking statements short
mok_ky_base = 'keystoneclient'
mok_ky_httpclient = '{0:}.httpclient.HTTPClient'.format(mok_ky_base)
mok_ky_auth = '{0:}.authenticate'.format(mok_ky_httpclient)
mok_ky_v2_client = '{0:}.v2_0.client.Client'.format(mok_ky_base)
mok_ky_v2_rawtoken = '{0:}.get_raw_token_from_identity_service'\
.format(mok_ky_v2_client)
mok_ky_discover = '{0:}.discover'.format(mok_ky_base)
mok_ky_discovery = '{0:}.Discover'.format(mok_ky_discover)
mok_ky_discovery_init = '{0:}.__init__'.format(mok_ky_discovery)
mok_ky_discover_client = '{0:}.create_client'.format(mok_ky_discovery)
mok_ky_discover_int = '{0:}._discover'.format(mok_ky_base)
mok_ky_discover_version = '{0:}.get_version_data'\
.format(mok_ky_discover_int)
with mock.patch(mok_ky_auth) as keystone_auth_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client,\
mock.patch(mok_ky_v2_rawtoken) as keystone_raw_token_mock,\
mock.patch(mok_ky_discover_version) as keystone_discover_ver,\
mock.patch(mok_ky_discover_client) as keystone_discover_cli, \
mock.patch(mok_isexpired) as mock_isexpired:
keystone_auth_mock.return_value = True
keystone_discover_ver.return_value = \
self.keystone_discovery_version_data
keystone_discover_cli.return_value = FakeClient()
keystone_v2_client.return_value = FakeClient()
FakeAccess.raise_until = 0
FakeAccess.raise_counter = 0
keystone_raw_token_mock.return_value = FakeAccess()
mock_isexpired.return_value = False
token = self.create_token()
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
# Setups up the __acccess node used by AuthToken for
# non-expired functions
authengine.GetToken()
authengine.AuthToken
def test_expiration_time(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
# Because the mock strings are so long, we're going to store them
# in variables here to keep the mocking statements short
mok_ky_base = 'keystoneclient'
mok_ky_httpclient = '{0:}.httpclient.HTTPClient'.format(mok_ky_base)
mok_ky_auth = '{0:}.authenticate'.format(mok_ky_httpclient)
mok_ky_v2_client = '{0:}.v2_0.client.Client'.format(mok_ky_base)
mok_ky_v2_rawtoken = '{0:}.get_raw_token_from_identity_service'\
.format(mok_ky_v2_client)
mok_ky_discover = '{0:}.discover'.format(mok_ky_base)
mok_ky_discovery = '{0:}.Discover'.format(mok_ky_discover)
mok_ky_discovery_init = '{0:}.__init__'.format(mok_ky_discovery)
mok_ky_discover_client = '{0:}.create_client'.format(mok_ky_discovery)
mok_ky_discover_int = '{0:}._discover'.format(mok_ky_base)
mok_ky_discover_version = '{0:}.get_version_data'\
.format(mok_ky_discover_int)
with mock.patch(mok_ky_auth) as keystone_auth_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client,\
mock.patch(mok_ky_v2_rawtoken) as keystone_raw_token_mock,\
mock.patch(mok_ky_discover_version) as keystone_discover_ver,\
mock.patch(mok_ky_discover_client) as keystone_discover_cli:
keystone_auth_mock.return_value = True
keystone_discover_ver.return_value = \
self.keystone_discovery_version_data
keystone_discover_cli.return_value = FakeClient()
keystone_v2_client.return_value = FakeClient()
keystone_raw_token_mock.return_value = FakeAccess()
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
token = authengine.GetToken(retry=FakeAccess.raise_until)
FakeAccess.expire_time = None
expire_time = authengine.AuthExpirationTime
self.assertIsNotNone(expire_time)
FakeAccess.expire_time = 'howdy'
expire_time = authengine.AuthExpirationTime
self.assertEqual(expire_time, FakeAccess.expire_time)
FakeAccess.expire_time = None
def test_user_data(self):
usertype = 'user_name'
username = self.create_username()
apikey = self.create_apikey()
auth_method = 'apikey'
datacenter = 'test'
auth_url = 'http://identity.api.rackspacecloud.com'
# Because the mock strings are so long, we're going to store them
# in variables here to keep the mocking statements short
mok_ky_base = 'keystoneclient'
mok_ky_httpclient = '{0:}.httpclient.HTTPClient'.format(mok_ky_base)
mok_ky_auth = '{0:}.authenticate'.format(mok_ky_httpclient)
mok_ky_v2_client = '{0:}.v2_0.client.Client'.format(mok_ky_base)
mok_ky_v2_rawtoken = '{0:}.get_raw_token_from_identity_service'\
.format(mok_ky_v2_client)
mok_ky_discover = '{0:}.discover'.format(mok_ky_base)
mok_ky_discovery = '{0:}.Discover'.format(mok_ky_discover)
mok_ky_discovery_init = '{0:}.__init__'.format(mok_ky_discovery)
mok_ky_discover_client = '{0:}.create_client'.format(mok_ky_discovery)
mok_ky_discover_int = '{0:}._discover'.format(mok_ky_base)
mok_ky_discover_version = '{0:}.get_version_data'\
.format(mok_ky_discover_int)
with mock.patch(mok_ky_auth) as keystone_auth_mock,\
mock.patch(mok_ky_v2_client) as keystone_v2_client,\
mock.patch(mok_ky_v2_rawtoken) as keystone_raw_token_mock,\
mock.patch(mok_ky_discover_version) as keystone_discover_ver,\
mock.patch(mok_ky_discover_client) as keystone_discover_cli:
keystone_auth_mock.return_value = True
keystone_discover_ver.return_value = \
self.keystone_discovery_version_data
keystone_discover_cli.return_value = FakeClient()
keystone_v2_client.return_value = FakeClient()
keystone_raw_token_mock.return_value = FakeAccess()
authengine = self.create_authengine(userid=username,
usertype=usertype,
credentials=apikey,
auth_method=auth_method,
datacenter=datacenter,
auth_url=auth_url)
token = authengine.GetToken(retry=FakeAccess.raise_until)
FakeAccess.user_data['tenant']['id'] = None
tenant_id = authengine.AuthTenantId
self.assertIsNone(tenant_id)
FakeAccess.user_data['tenant']['id'] = 1
tenant_id = authengine.AuthTenantId
self.assertIsNotNone(tenant_id)
self.assertEqual(tenant_id, FakeAccess.user_data['tenant']['id'])
FakeAccess.user_data['tenant']['name'] = None
tenant_name = authengine.AuthTenantName
self.assertIsNone(tenant_name)
FakeAccess.user_data['tenant']['name'] = '1'
tenant_name = authengine.AuthTenantName
self.assertIsNotNone(tenant_name)
self.assertEqual(tenant_name,
FakeAccess.user_data['tenant']['name'])
FakeAccess.user_data['user']['id'] = None
user_id = authengine.AuthUserId
self.assertIsNone(user_id)
FakeAccess.user_data['user']['id'] = 1
user_id = authengine.AuthUserId
self.assertIsNotNone(user_id)
self.assertEqual(user_id, FakeAccess.user_data['user']['id'])
FakeAccess.user_data['user']['name'] = None
user_name = authengine.AuthUserName
self.assertIsNone(user_name)
FakeAccess.user_data['user']['name'] = '1'
user_name = authengine.AuthUserName
self.assertIsNotNone(user_name)
self.assertEqual(user_name, FakeAccess.user_data['user']['name'])
FakeAccess.user_data['tenant']['id'] = None
FakeAccess.user_data['tenant']['name'] = None
FakeAccess.user_data['user']['id'] = None
FakeAccess.user_data['user']['name'] = None
| {
"content_hash": "4886da6a905a5c2966a014969a3a2cc3",
"timestamp": "",
"source": "github",
"line_count": 993,
"max_line_length": 79,
"avg_line_length": 39.863041289023165,
"alnum_prop": 0.5319573565076798,
"repo_name": "rackerlabs/deuce-client",
"id": "039f7a86bc489c125b18d644a86be2c2e391c558",
"size": "39584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deuceclient/tests/test_auth_openstack.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "362823"
}
],
"symlink_target": ""
} |
import inspect
import itertools
import warnings
from markupsafe import escape
from markupsafe import Markup
from wtforms import widgets
from wtforms.i18n import DummyTranslations
from wtforms.utils import unset_value
from wtforms.validators import StopValidation
from wtforms.validators import ValidationError
class Field:
"""
Field base class
"""
errors = tuple()
process_errors = tuple()
raw_data = None
validators = tuple()
widget = None
_formfield = True
_translations = DummyTranslations()
do_not_call_in_templates = True # Allow Django 1.4 traversal
def __new__(cls, *args, **kwargs):
if "_form" in kwargs:
return super().__new__(cls)
else:
return UnboundField(cls, *args, **kwargs)
def __init__(
self,
label=None,
validators=None,
filters=(),
description="",
id=None,
default=None,
widget=None,
render_kw=None,
name=None,
_form=None,
_prefix="",
_translations=None,
_meta=None,
):
"""
Construct a new field.
:param label:
The label of the field.
:param validators:
A sequence of validators to call when `validate` is called.
:param filters:
A sequence of filters which are run on input data by `process`.
:param description:
A description for the field, typically used for help text.
:param id:
An id to use for the field. A reasonable default is set by the form,
and you shouldn't need to set this manually.
:param default:
The default value to assign to the field, if no form or object
input is provided. May be a callable.
:param widget:
If provided, overrides the widget used to render the field.
:param dict render_kw:
If provided, a dictionary which provides default keywords that
will be given to the widget at render time.
:param name:
The HTML name of this field. The default value is the Python
attribute name.
:param _form:
The form holding this field. It is passed by the form itself during
construction. You should never pass this value yourself.
:param _prefix:
The prefix to prepend to the form name of this field, passed by
the enclosing form during construction.
:param _translations:
A translations object providing message translations. Usually
passed by the enclosing form during construction. See
:doc:`I18n docs <i18n>` for information on message translations.
:param _meta:
If provided, this is the 'meta' instance from the form. You usually
don't pass this yourself.
If `_form` isn't provided, an :class:`UnboundField` will be
returned instead. Call its :func:`bind` method with a form instance and
a name to construct the field.
"""
if _translations is not None:
self._translations = _translations
if _meta is not None:
self.meta = _meta
elif _form is not None:
self.meta = _form.meta
else:
raise TypeError("Must provide one of _form or _meta")
self.default = default
self.description = description
self.render_kw = render_kw
self.filters = filters
self.flags = Flags()
self.name = _prefix + name
self.short_name = name
self.type = type(self).__name__
self.check_validators(validators)
self.validators = validators or self.validators
self.id = id or self.name
self.label = Label(
self.id,
label
if label is not None
else self.gettext(name.replace("_", " ").title()),
)
if widget is not None:
self.widget = widget
for v in itertools.chain(self.validators, [self.widget]):
flags = getattr(v, "field_flags", {})
# check for legacy format, remove eventually
if isinstance(flags, tuple): # pragma: no cover
warnings.warn(
"Flags should be stored in dicts and not in tuples. "
"The next version of WTForms will abandon support "
"for flags in tuples.",
DeprecationWarning,
stacklevel=2,
)
flags = {flag_name: True for flag_name in flags}
for k, v in flags.items():
setattr(self.flags, k, v)
def __str__(self):
"""
Returns a HTML representation of the field. For more powerful rendering,
see the `__call__` method.
"""
return self()
def __html__(self):
"""
Returns a HTML representation of the field. For more powerful rendering,
see the :meth:`__call__` method.
"""
return self()
def __call__(self, **kwargs):
"""
Render this field as HTML, using keyword args as additional attributes.
This delegates rendering to
:meth:`meta.render_field <wtforms.meta.DefaultMeta.render_field>`
whose default behavior is to call the field's widget, passing any
keyword arguments from this call along to the widget.
In all of the WTForms HTML widgets, keyword arguments are turned to
HTML attributes, though in theory a widget is free to do anything it
wants with the supplied keyword arguments, and widgets don't have to
even do anything related to HTML.
"""
return self.meta.render_field(self, kwargs)
@classmethod
def check_validators(cls, validators):
if validators is not None:
for validator in validators:
if not callable(validator):
raise TypeError(
"{} is not a valid validator because it is not "
"callable".format(validator)
)
if inspect.isclass(validator):
raise TypeError(
"{} is not a valid validator because it is a class, "
"it should be an instance".format(validator)
)
def gettext(self, string):
"""
Get a translation for the given message.
This proxies for the internal translations object.
:param string: A string to be translated.
:return: A string which is the translated output.
"""
return self._translations.gettext(string)
def ngettext(self, singular, plural, n):
"""
Get a translation for a message which can be pluralized.
:param str singular: The singular form of the message.
:param str plural: The plural form of the message.
:param int n: The number of elements this message is referring to
"""
return self._translations.ngettext(singular, plural, n)
def validate(self, form, extra_validators=()):
"""
Validates the field and returns True or False. `self.errors` will
contain any errors raised during validation. This is usually only
called by `Form.validate`.
Subfields shouldn't override this, but rather override either
`pre_validate`, `post_validate` or both, depending on needs.
:param form: The form the field belongs to.
:param extra_validators: A sequence of extra validators to run.
"""
self.errors = list(self.process_errors)
stop_validation = False
# Check the type of extra_validators
self.check_validators(extra_validators)
# Call pre_validate
try:
self.pre_validate(form)
except StopValidation as e:
if e.args and e.args[0]:
self.errors.append(e.args[0])
stop_validation = True
except ValidationError as e:
self.errors.append(e.args[0])
# Run validators
if not stop_validation:
chain = itertools.chain(self.validators, extra_validators)
stop_validation = self._run_validation_chain(form, chain)
# Call post_validate
try:
self.post_validate(form, stop_validation)
except ValidationError as e:
self.errors.append(e.args[0])
return len(self.errors) == 0
def _run_validation_chain(self, form, validators):
"""
Run a validation chain, stopping if any validator raises StopValidation.
:param form: The Form instance this field belongs to.
:param validators: a sequence or iterable of validator callables.
:return: True if validation was stopped, False otherwise.
"""
for validator in validators:
try:
validator(form, self)
except StopValidation as e:
if e.args and e.args[0]:
self.errors.append(e.args[0])
return True
except ValidationError as e:
self.errors.append(e.args[0])
return False
def pre_validate(self, form):
"""
Override if you need field-level validation. Runs before any other
validators.
:param form: The form the field belongs to.
"""
pass
def post_validate(self, form, validation_stopped):
"""
Override if you need to run any field-level validation tasks after
normal validation. This shouldn't be needed in most cases.
:param form: The form the field belongs to.
:param validation_stopped:
`True` if any validator raised StopValidation.
"""
pass
def process(self, formdata, data=unset_value, extra_filters=None):
"""
Process incoming data, calling process_data, process_formdata as needed,
and run filters.
If `data` is not provided, process_data will be called on the field's
default.
Field subclasses usually won't override this, instead overriding the
process_formdata and process_data methods. Only override this for
special advanced processing, such as when a field encapsulates many
inputs.
:param extra_filters: A sequence of extra filters to run.
"""
self.process_errors = []
if data is unset_value:
try:
data = self.default()
except TypeError:
data = self.default
self.object_data = data
try:
self.process_data(data)
except ValueError as e:
self.process_errors.append(e.args[0])
if formdata is not None:
if self.name in formdata:
self.raw_data = formdata.getlist(self.name)
else:
self.raw_data = []
try:
self.process_formdata(self.raw_data)
except ValueError as e:
self.process_errors.append(e.args[0])
try:
for filter in itertools.chain(self.filters, extra_filters or []):
self.data = filter(self.data)
except ValueError as e:
self.process_errors.append(e.args[0])
def process_data(self, value):
"""
Process the Python data applied to this field and store the result.
This will be called during form construction by the form's `kwargs` or
`obj` argument.
:param value: The python object containing the value to process.
"""
self.data = value
def process_formdata(self, valuelist):
"""
Process data received over the wire from a form.
This will be called during form construction with data supplied
through the `formdata` argument.
:param valuelist: A list of strings to process.
"""
if valuelist:
self.data = valuelist[0]
def populate_obj(self, obj, name):
"""
Populates `obj.<name>` with the field's data.
:note: This is a destructive operation. If `obj.<name>` already exists,
it will be overridden. Use with caution.
"""
setattr(obj, name, self.data)
class UnboundField:
_formfield = True
creation_counter = 0
def __init__(self, field_class, *args, name=None, **kwargs):
UnboundField.creation_counter += 1
self.field_class = field_class
self.args = args
self.name = name
self.kwargs = kwargs
self.creation_counter = UnboundField.creation_counter
validators = kwargs.get("validators")
if validators:
self.field_class.check_validators(validators)
def bind(self, form, name, prefix="", translations=None, **kwargs):
kw = dict(
self.kwargs,
name=name,
_form=form,
_prefix=prefix,
_translations=translations,
**kwargs,
)
return self.field_class(*self.args, **kw)
def __repr__(self):
return "<UnboundField({}, {!r}, {!r})>".format(
self.field_class.__name__, self.args, self.kwargs
)
class Flags:
"""
Holds a set of flags as attributes.
Accessing a non-existing attribute returns None for its value.
"""
def __getattr__(self, name):
if name.startswith("_"):
return super().__getattr__(name)
return None
def __contains__(self, name):
return getattr(self, name)
def __repr__(self):
flags = (name for name in dir(self) if not name.startswith("_"))
return "<wtforms.fields.Flags: {%s}>" % ", ".join(flags)
class Label:
"""
An HTML form label.
"""
def __init__(self, field_id, text):
self.field_id = field_id
self.text = text
def __str__(self):
return self()
def __html__(self):
return self()
def __call__(self, text=None, **kwargs):
if "for_" in kwargs:
kwargs["for"] = kwargs.pop("for_")
else:
kwargs.setdefault("for", self.field_id)
attributes = widgets.html_params(**kwargs)
text = escape(text or self.text)
return Markup(f"<label {attributes}>{text}</label>")
def __repr__(self):
return f"Label({self.field_id!r}, {self.text!r})"
| {
"content_hash": "c3809439bce8e8baacc7bed601bb4cbd",
"timestamp": "",
"source": "github",
"line_count": 449,
"max_line_length": 80,
"avg_line_length": 32.4097995545657,
"alnum_prop": 0.5785459043430456,
"repo_name": "wtforms/wtforms",
"id": "59c4e955220ecfee5fdea2f016cfefd902d24bb8",
"size": "14552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/wtforms/fields/core.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "222611"
}
],
"symlink_target": ""
} |
import _plotly_utils.basevalidators
class FillValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="fill", parent_name="table.cells", **kwargs):
super(FillValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Fill"),
data_docs=kwargs.pop(
"data_docs",
"""
color
Sets the cell fill color. It accepts either a
specific color or an array of colors or a 2D
array of colors.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
""",
),
**kwargs,
)
| {
"content_hash": "e31eb969d553858e869c9ae3a3a9ce91",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 80,
"avg_line_length": 34.56521739130435,
"alnum_prop": 0.529559748427673,
"repo_name": "plotly/plotly.py",
"id": "a920b6da1e57f05883a67e578e8c7042b31265bd",
"size": "795",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/python/plotly/plotly/validators/table/cells/_fill.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "545"
},
{
"name": "JavaScript",
"bytes": "2074"
},
{
"name": "PostScript",
"bytes": "565328"
},
{
"name": "Python",
"bytes": "31506317"
},
{
"name": "TypeScript",
"bytes": "71337"
}
],
"symlink_target": ""
} |
"""Class for interacting with the Skia Gold image diffing service."""
# pylint: disable=useless-object-inheritance
import logging
import os
import platform
import shutil
import sys
import tempfile
import time
CHROMIUM_SRC = os.path.realpath(
os.path.join(os.path.dirname(__file__), '..', '..'))
GOLDCTL_BINARY = os.path.join(CHROMIUM_SRC, 'tools', 'skia_goldctl')
if sys.platform == 'win32':
GOLDCTL_BINARY = os.path.join(GOLDCTL_BINARY, 'win', 'goldctl') + '.exe'
elif sys.platform == 'darwin':
machine = platform.machine().lower()
if any(machine.startswith(m) for m in ('arm64', 'aarch64')):
GOLDCTL_BINARY = os.path.join(GOLDCTL_BINARY, 'mac_arm64', 'goldctl')
else:
GOLDCTL_BINARY = os.path.join(GOLDCTL_BINARY, 'mac_amd64', 'goldctl')
else:
GOLDCTL_BINARY = os.path.join(GOLDCTL_BINARY, 'linux', 'goldctl')
class SkiaGoldSession(object):
class StatusCodes(object):
"""Status codes for RunComparison."""
SUCCESS = 0
AUTH_FAILURE = 1
INIT_FAILURE = 2
COMPARISON_FAILURE_REMOTE = 3
COMPARISON_FAILURE_LOCAL = 4
LOCAL_DIFF_FAILURE = 5
NO_OUTPUT_MANAGER = 6
class ComparisonResults(object):
"""Struct-like object for storing results of an image comparison."""
def __init__(self):
self.public_triage_link = None
self.internal_triage_link = None
self.triage_link_omission_reason = None
self.local_diff_given_image = None
self.local_diff_closest_image = None
self.local_diff_diff_image = None
def __init__(self,
working_dir,
gold_properties,
keys_file,
corpus,
instance,
bucket=None):
"""Abstract class to handle all aspects of image comparison via Skia Gold.
A single SkiaGoldSession is valid for a single instance/corpus/keys_file
combination.
Args:
working_dir: The directory to store config files, etc.
gold_properties: A skia_gold_properties.SkiaGoldProperties instance for
the current test run.
keys_file: A path to a JSON file containing various comparison config data
such as corpus and debug information like the hardware/software
configuration the images will be produced on.
corpus: The corpus that images that will be compared belong to.
instance: The name of the Skia Gold instance to interact with.
bucket: Overrides the formulaic Google Storage bucket name generated by
goldctl
"""
self._working_dir = working_dir
self._gold_properties = gold_properties
self._corpus = corpus
self._instance = instance
self._bucket = bucket
self._local_png_directory = (self._gold_properties.local_png_directory
or tempfile.mkdtemp())
self._triage_link_file = tempfile.NamedTemporaryFile(suffix='.txt',
dir=working_dir,
delete=False).name
# A map of image name (string) to ComparisonResults for that image.
self._comparison_results = {}
self._authenticated = False
self._initialized = False
# Copy the given keys file to the working directory in case it ends up
# getting deleted before we try to use it.
self._keys_file = os.path.join(working_dir, 'gold_keys.json')
shutil.copy(keys_file, self._keys_file)
def RunComparison(self,
name,
png_file,
output_manager,
inexact_matching_args=None,
use_luci=True,
optional_keys=None,
force_dryrun=False):
"""Helper method to run all steps to compare a produced image.
Handles authentication, itnitialization, comparison, and, if necessary,
local diffing.
Args:
name: The name of the image being compared.
png_file: A path to a PNG file containing the image to be compared.
output_manager: An output manager to use to store diff links. The
argument's type depends on what type a subclasses' _StoreDiffLinks
implementation expects. Can be None even if _StoreDiffLinks expects
a valid input, but will fail if it ever actually needs to be used.
inexact_matching_args: A list of strings containing extra command line
arguments to pass to Gold for inexact matching. Can be omitted to use
exact matching.
use_luci: If true, authentication will use the service account provided by
the LUCI context. If false, will attempt to use whatever is set up in
gsutil, which is only supported for local runs.
optional_keys: A dict containing optional key/value pairs to pass to Gold
for this comparison. Optional keys are keys unrelated to the
configuration the image was produced on, e.g. a comment or whether
Gold should treat the image as ignored.
force_dryrun: A boolean denoting whether dryrun should be forced on
regardless of whether this is a local comparison or not.
Returns:
A tuple (status, error). |status| is a value from
SkiaGoldSession.StatusCodes signifying the result of the comparison.
|error| is an error message describing the status if not successful.
"""
auth_rc, auth_stdout = self.Authenticate(use_luci=use_luci)
if auth_rc:
return self.StatusCodes.AUTH_FAILURE, auth_stdout
init_rc, init_stdout = self.Initialize()
if init_rc:
return self.StatusCodes.INIT_FAILURE, init_stdout
compare_rc, compare_stdout = self.Compare(
name=name,
png_file=png_file,
inexact_matching_args=inexact_matching_args,
optional_keys=optional_keys,
force_dryrun=force_dryrun)
if not compare_rc:
return self.StatusCodes.SUCCESS, None
logging.error('Gold comparison failed: %s', compare_stdout)
if not self._gold_properties.local_pixel_tests:
return self.StatusCodes.COMPARISON_FAILURE_REMOTE, compare_stdout
if not output_manager:
return (self.StatusCodes.NO_OUTPUT_MANAGER,
'No output manager for local diff images')
diff_rc, diff_stdout = self.Diff(name=name,
png_file=png_file,
output_manager=output_manager)
if diff_rc:
return self.StatusCodes.LOCAL_DIFF_FAILURE, diff_stdout
return self.StatusCodes.COMPARISON_FAILURE_LOCAL, compare_stdout
def Authenticate(self, use_luci=True):
"""Authenticates with Skia Gold for this session.
Args:
use_luci: If true, authentication will use the service account provided
by the LUCI context. If false, will attempt to use whatever is set up
in gsutil, which is only supported for local runs.
Returns:
A tuple (return_code, output). |return_code| is the return code of the
authentication process. |output| is the stdout + stderr of the
authentication process.
"""
if self._authenticated:
return 0, None
if self._gold_properties.bypass_skia_gold_functionality:
logging.warning('Not actually authenticating with Gold due to '
'--bypass-skia-gold-functionality being present.')
return 0, None
auth_cmd = [GOLDCTL_BINARY, 'auth', '--work-dir', self._working_dir]
if use_luci:
auth_cmd.append('--luci')
elif not self._gold_properties.local_pixel_tests:
raise RuntimeError(
'Cannot authenticate to Skia Gold with use_luci=False unless running '
'local pixel tests')
rc, stdout = self._RunCmdForRcAndOutput(auth_cmd)
if rc == 0:
self._authenticated = True
return rc, stdout
def Initialize(self):
"""Initializes the working directory if necessary.
This can technically be skipped if the same information is passed to the
command used for image comparison, but that is less efficient under the
hood. Doing it that way effectively requires an initialization for every
comparison (~250 ms) instead of once at the beginning.
Returns:
A tuple (return_code, output). |return_code| is the return code of the
initialization process. |output| is the stdout + stderr of the
initialization process.
"""
if self._initialized:
return 0, None
if self._gold_properties.bypass_skia_gold_functionality:
logging.warning('Not actually initializing Gold due to '
'--bypass-skia-gold-functionality being present.')
return 0, None
init_cmd = [
GOLDCTL_BINARY,
'imgtest',
'init',
'--passfail',
'--instance',
self._instance,
'--corpus',
self._corpus,
'--keys-file',
self._keys_file,
'--work-dir',
self._working_dir,
'--failure-file',
self._triage_link_file,
'--commit',
self._gold_properties.git_revision,
]
if self._bucket:
init_cmd.extend(['--bucket', self._bucket])
if self._gold_properties.IsTryjobRun():
init_cmd.extend([
'--issue',
str(self._gold_properties.issue),
'--patchset',
str(self._gold_properties.patchset),
'--jobid',
str(self._gold_properties.job_id),
'--crs',
str(self._gold_properties.code_review_system),
'--cis',
str(self._gold_properties.continuous_integration_system),
])
rc, stdout = self._RunCmdForRcAndOutput(init_cmd)
if rc == 0:
self._initialized = True
return rc, stdout
def Compare(self,
name,
png_file,
inexact_matching_args=None,
optional_keys=None,
force_dryrun=False):
"""Compares the given image to images known to Gold.
Triage links can later be retrieved using GetTriageLinks().
Args:
name: The name of the image being compared.
png_file: A path to a PNG file containing the image to be compared.
inexact_matching_args: A list of strings containing extra command line
arguments to pass to Gold for inexact matching. Can be omitted to use
exact matching.
optional_keys: A dict containing optional key/value pairs to pass to Gold
for this comparison. Optional keys are keys unrelated to the
configuration the image was produced on, e.g. a comment or whether
Gold should treat the image as ignored.
force_dryrun: A boolean denoting whether dryrun should be forced on
regardless of whether this is a local comparison or not.
Returns:
A tuple (return_code, output). |return_code| is the return code of the
comparison process. |output| is the stdout + stderr of the comparison
process.
"""
if self._gold_properties.bypass_skia_gold_functionality:
logging.warning('Not actually comparing with Gold due to '
'--bypass-skia-gold-functionality being present.')
return 0, None
compare_cmd = [
GOLDCTL_BINARY,
'imgtest',
'add',
'--test-name',
name,
'--png-file',
png_file,
'--work-dir',
self._working_dir,
]
if self._gold_properties.local_pixel_tests or force_dryrun:
compare_cmd.append('--dryrun')
if inexact_matching_args:
logging.info('Using inexact matching arguments for image %s: %s', name,
inexact_matching_args)
compare_cmd.extend(inexact_matching_args)
optional_keys = optional_keys or {}
for k, v in optional_keys.items():
compare_cmd.extend([
'--add-test-optional-key',
'%s:%s' % (k, v),
])
self._ClearTriageLinkFile()
rc, stdout = self._RunCmdForRcAndOutput(compare_cmd)
self._comparison_results[name] = self.ComparisonResults()
if rc == 0:
self._comparison_results[name].triage_link_omission_reason = (
'Comparison succeeded, no triage link')
elif self._gold_properties.IsTryjobRun():
cl_triage_link = ('https://{instance}-gold.skia.org/cl/{crs}/{issue}')
cl_triage_link = cl_triage_link.format(
instance=self._instance,
crs=self._gold_properties.code_review_system,
issue=self._gold_properties.issue)
self._comparison_results[name].internal_triage_link = cl_triage_link
self._comparison_results[name].public_triage_link =\
self._GeneratePublicTriageLink(cl_triage_link)
else:
try:
with open(self._triage_link_file) as tlf:
triage_link = tlf.read().strip()
if not triage_link:
self._comparison_results[name].triage_link_omission_reason = (
'Gold did not provide a triage link. This is likely a bug on '
"Gold's end.")
self._comparison_results[name].internal_triage_link = None
self._comparison_results[name].public_triage_link = None
else:
self._comparison_results[name].internal_triage_link = triage_link
self._comparison_results[name].public_triage_link =\
self._GeneratePublicTriageLink(triage_link)
except IOError:
self._comparison_results[name].triage_link_omission_reason = (
'Failed to read triage link from file')
return rc, stdout
def Diff(self, name, png_file, output_manager):
"""Performs a local image diff against the closest known positive in Gold.
This is used for running tests on a workstation, where uploading data to
Gold for ingestion is not allowed, and thus the web UI is not available.
Image links can later be retrieved using Get*ImageLink().
Args:
name: The name of the image being compared.
png_file: The path to a PNG file containing the image to be diffed.
output_manager: An output manager to use to store diff links. The
argument's type depends on what type a subclasses' _StoreDiffLinks
implementation expects.
Returns:
A tuple (return_code, output). |return_code| is the return code of the
diff process. |output| is the stdout + stderr of the diff process.
"""
# Instead of returning that everything is okay and putting in dummy links,
# just fail since this should only be called when running locally and
# --bypass-skia-gold-functionality is only meant for use on the bots.
if self._gold_properties.bypass_skia_gold_functionality:
raise RuntimeError(
'--bypass-skia-gold-functionality is not supported when running '
'tests locally.')
output_dir = self._CreateDiffOutputDir(name)
# TODO(skbug.com/10611): Remove this temporary work dir and instead just use
# self._working_dir once `goldctl diff` stops clobbering the auth files in
# the provided work directory.
temp_work_dir = tempfile.mkdtemp()
# shutil.copytree() fails if the destination already exists, so use a
# subdirectory of the temporary directory.
temp_work_dir = os.path.join(temp_work_dir, 'diff_work_dir')
try:
shutil.copytree(self._working_dir, temp_work_dir)
diff_cmd = [
GOLDCTL_BINARY,
'diff',
'--corpus',
self._corpus,
'--instance',
self._GetDiffGoldInstance(),
'--input',
png_file,
'--test',
name,
'--work-dir',
temp_work_dir,
'--out-dir',
output_dir,
]
rc, stdout = self._RunCmdForRcAndOutput(diff_cmd)
self._StoreDiffLinks(name, output_manager, output_dir)
return rc, stdout
finally:
shutil.rmtree(os.path.realpath(os.path.join(temp_work_dir, '..')))
def GetTriageLinks(self, name):
"""Gets the triage links for the given image.
Args:
name: The name of the image to retrieve the triage link for.
Returns:
A tuple (public, internal). |public| is a string containing the triage
link for the public Gold instance if it is available, or None if it is not
available for some reason. |internal| is the same as |public|, but
containing a link to the internal Gold instance. The reason for links not
being available can be retrieved using GetTriageLinkOmissionReason.
"""
comparison_results = self._comparison_results.get(name,
self.ComparisonResults())
return (comparison_results.public_triage_link,
comparison_results.internal_triage_link)
def GetTriageLinkOmissionReason(self, name):
"""Gets the reason why a triage link is not available for an image.
Args:
name: The name of the image whose triage link does not exist.
Returns:
A string containing the reason why a triage link is not available.
"""
if name not in self._comparison_results:
return 'No image comparison performed for %s' % name
results = self._comparison_results[name]
# This method should not be called if there is a valid triage link.
assert results.public_triage_link is None
assert results.internal_triage_link is None
if results.triage_link_omission_reason:
return results.triage_link_omission_reason
if results.local_diff_given_image:
return 'Gold only used to do a local image diff'
raise RuntimeError(
'Somehow have a ComparisonResults instance for %s that should not '
'exist' % name)
def GetGivenImageLink(self, name):
"""Gets the link to the given image used for local diffing.
Args:
name: The name of the image that was diffed.
Returns:
A string containing the link to where the image is saved, or None if it
does not exist.
"""
assert name in self._comparison_results
return self._comparison_results[name].local_diff_given_image
def GetClosestImageLink(self, name):
"""Gets the link to the closest known image used for local diffing.
Args:
name: The name of the image that was diffed.
Returns:
A string containing the link to where the image is saved, or None if it
does not exist.
"""
assert name in self._comparison_results
return self._comparison_results[name].local_diff_closest_image
def GetDiffImageLink(self, name):
"""Gets the link to the diff between the given and closest images.
Args:
name: The name of the image that was diffed.
Returns:
A string containing the link to where the image is saved, or None if it
does not exist.
"""
assert name in self._comparison_results
return self._comparison_results[name].local_diff_diff_image
def _GeneratePublicTriageLink(self, internal_link):
"""Generates a public triage link given an internal one.
Args:
internal_link: A string containing a triage link pointing to an internal
Gold instance.
Returns:
A string containing a triage link pointing to the public mirror of the
link pointed to by |internal_link|.
"""
return internal_link.replace('%s-gold' % self._instance,
'%s-public-gold' % self._instance)
def _ClearTriageLinkFile(self):
"""Clears the contents of the triage link file.
This should be done before every comparison since goldctl appends to the
file instead of overwriting its contents, which results in multiple triage
links getting concatenated together if there are multiple failures.
"""
open(self._triage_link_file, 'w').close()
def _CreateDiffOutputDir(self, _):
# We don't use self._local_png_directory here since we want it to be
# automatically cleaned up with the working directory. Any subclasses that
# want to keep it around can override this method.
return tempfile.mkdtemp(dir=self._working_dir)
def _GetDiffGoldInstance(self):
"""Gets the Skia Gold instance to use for the Diff step.
This can differ based on how a particular instance is set up, mainly
depending on whether it is set up for internal results or not.
"""
# TODO(skbug.com/10610): Decide whether to use the public or
# non-public instance once authentication is fixed for the non-public
# instance.
return str(self._instance) + '-public'
def _StoreDiffLinks(self, image_name, output_manager, output_dir):
"""Stores the local diff files as links.
The ComparisonResults entry for |image_name| should have its *_image fields
filled after this unless corresponding images were not found on disk.
Args:
image_name: A string containing the name of the image that was diffed.
output_manager: An output manager used used to surface links to users,
if necessary. The expected argument type depends on each subclasses'
implementation of this method.
output_dir: A string containing the path to the directory where diff
output image files where saved.
"""
raise NotImplementedError()
@staticmethod
def _RunCmdForRcAndOutput(cmd):
"""Runs |cmd| and returns its returncode and output.
Args:
cmd: A list containing the command line to run.
Returns:
A tuple (rc, output), where, |rc| is the returncode of the command and
|output| is the stdout + stderr of the command.
"""
raise NotImplementedError()
| {
"content_hash": "36de94a2fbadfdaa7a00a92ee4bccbdc",
"timestamp": "",
"source": "github",
"line_count": 556,
"max_line_length": 80,
"avg_line_length": 38.47122302158273,
"alnum_prop": 0.6513791491351099,
"repo_name": "scheib/chromium",
"id": "9ec065e4c98e41b525ad6675d9363727a5db2b2f",
"size": "21552",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "build/skia_gold_common/skia_gold_session.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
generic_script = """
<script type="text/javascript">
function showGenericRelatedObjectLookupPopup(ct_select, triggering_link, url_base) {
var url = content_types[ct_select.options[ct_select.selectedIndex].value];
if (url != undefined) {
triggering_link.href = url_base + url;
return showRelatedObjectLookupPopup(triggering_link);
}
return false;
}
</script>
"""
class GenericForeignKeyRawIdWidget(ForeignKeyRawIdWidget):
def __init__(self, ct_field, cts=[], attrs=None):
self.ct_field = ct_field
self.cts = cts
forms.TextInput.__init__(self, attrs)
def render(self, name, value, attrs=None):
if attrs is None:
attrs = {}
related_url = "../../../"
params = self.url_parameters()
if params:
url = "?" + "&".join(["%s=%s" % (k, v) for k, v in params.iteritems()])
else:
url = ""
if "class" not in attrs:
attrs["class"] = "vForeignKeyRawIdAdminField"
output = [forms.TextInput.render(self, name, value, attrs)]
output.append(
"""%(generic_script)s
<a href="%(related)s%(url)s"
class="related-lookup"
id="lookup_id_%(name)s"
onclick="return showGenericRelatedObjectLookupPopup(
document.getElementById('id_%(ct_field)s'), this, '%(related)s%(url)s');">
"""
% {
"generic_script": generic_script,
"related": related_url,
"url": url,
"name": name,
"ct_field": self.ct_field,
}
)
output.append(
'<img src="%s/admin/img/selector-search.gif" width="16" height="16" alt="%s" /></a>'
% (settings.STATIC_URL, _("Lookup"))
)
from django.contrib.contenttypes.models import ContentType
content_types = """
<script type="text/javascript">
var content_types = new Array();
%s
</script>
""" % (
"\n".join(
[
"content_types[%s] = '%s/%s/';"
% (
ContentType.objects.get_for_model(ct).id,
ct._meta.app_label,
ct._meta.object_name.lower(),
)
for ct in self.cts
]
)
)
return mark_safe(u"".join(output) + content_types)
def url_parameters(self):
return {}
| {
"content_hash": "5999f8c3afd17eee6b4e3ec6e43c844f",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 98,
"avg_line_length": 33.44047619047619,
"alnum_prop": 0.5165539337842648,
"repo_name": "jazzband/django-authority",
"id": "fb5821b0a39e7bfd8616d437cf0e333b969332e2",
"size": "2809",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "authority/widgets.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "9412"
},
{
"name": "Python",
"bytes": "96947"
}
],
"symlink_target": ""
} |
import logging
import pymongo
from django.conf import settings
from django.core.management.base import BaseCommand
from crits.config.config import CRITsConfig
from crits.core.mongo_tools import mongo_update, mongo_remove, mongo_connector
from create_sectors import add_sector_objects
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Script Class.
"""
help = 'Preps MongoDB for upgrade.'
def handle(self, *args, **options):
"""
Script Execution.
"""
prep_database()
def prep_audit_log():
"""
Migrate the audit log.
"""
pass
def prep_backdoors():
"""
Migrate backdoors.
"""
pass
def prep_campaigns():
"""
Migrate campaigns.
"""
pass
def prep_comments():
"""
Migrate comments.
"""
pass
def prep_divisions():
"""
Migrate divisions.
"""
pass
def prep_events():
"""
Migrate events.
"""
pass
def prep_exploits():
"""
Migrate exploits.
"""
pass
def prep_indicator_actions():
"""
Migrate indicator actions.
"""
pass
def prep_indicators():
"""
Migrate indicators.
"""
pass
def prep_pcaps():
"""
Migrate pcaps.
"""
pass
def prep_targets():
"""
Migrate targets.
"""
pass
def prep_objects():
"""
Migrate objects.
"""
pass
def prep_relationships():
"""
Migrate relationships.
"""
pass
def prep_sources():
"""
Migrate sources.
"""
pass
def prep_user_roles():
"""
Migrate user roles.
"""
pass
def prep_yarahits():
"""
Migrate yara hits.
"""
pass
def prep_notifications():
"""
Update notifications.
"""
a1 = {"$unset": {"notifications": 1}}
a2 = {"$unset": {"unsupported_attrs.notifications": 1}}
mongo_update(settings.COL_USERS, {}, a1)
mongo_update(settings.COL_USERS, {}, a2)
query = {"type": "notification"}
mongo_remove(settings.COL_COMMENTS, query)
def prep_sectors():
add_sector_objects()
def prep_indexes():
"""
Update indexing.
"""
notifications = mongo_connector(settings.COL_NOTIFICATIONS)
# auto-expire notifications after 30 days
notifications.ensure_index("obj_id", background=True,
expireAfterSeconds=2592000)
notifications.ensure_index("users", background=True)
print "Notification indexes created."
screenshots = mongo_connector(settings.COL_SCREENSHOTS)
screenshots.ensure_index("tags", background=True)
print "Screenshot indexes created."
# check for old invalid chunk indexes and fix
for col in ("%s.chunks" % settings.COL_OBJECTS,
"%s.chunks" % settings.COL_PCAPS,
"%s.chunks" % settings.COL_SAMPLES):
c = mongo_connector(col)
d = c.index_information()
if d.get('files_id_1_n_1', False):
b = d['files_id_1_n_1'].get('background', None)
# background could be set to False or True in the DB
if b is not None:
c.drop_index("files_id_1_n_1")
c.ensure_index([("files_id", pymongo.ASCENDING),
("n", pymongo.ASCENDING)],
unique=True)
print "Found bad index for %s. Fixed it." % col
def update_database_version():
c = CRITsConfig.objects().first()
c.crits_version = "3.1.0"
c.save()
def prep_database():
"""
Migrate the appropriate collections.
"""
prep_notifications()
prep_sectors()
prep_indexes()
update_database_version()
return
| {
"content_hash": "02a81059c132090a55fad0bbbbbfe990",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 78,
"avg_line_length": 18.03921568627451,
"alnum_prop": 0.5733695652173914,
"repo_name": "davidhdz/crits",
"id": "bf1383e5e644439cf20135e9aae0c4ca60d51e48",
"size": "3680",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "crits/core/management/commands/prep.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "8694"
},
{
"name": "CSS",
"bytes": "360810"
},
{
"name": "HTML",
"bytes": "452517"
},
{
"name": "JavaScript",
"bytes": "2022328"
},
{
"name": "Perl",
"bytes": "916"
},
{
"name": "Prolog",
"bytes": "948"
},
{
"name": "Python",
"bytes": "1928789"
},
{
"name": "Shell",
"bytes": "10551"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from rest_framework import generics
from rest_framework import permissions
from api.base.views import JSONAPIBaseView
from api.base import permissions as base_permissions
from api.base.utils import get_object_or_error
from api.requests.permissions import NodeRequestPermission
from api.requests.serializers import NodeRequestSerializer
from framework.auth.oauth_scopes import CoreScopes
from osf.models import Node, NodeRequest
class NodeRequestMixin(object):
serializer_class = NodeRequestSerializer
node_lookup_url_kwarg = 'node_id'
node_request_lookup_url_kwarg = 'request_id'
def get_noderequest(self, check_object_permissions=True):
node_request = get_object_or_error(
NodeRequest,
self.kwargs[self.node_request_lookup_url_kwarg],
self.request,
display_name='node request'
)
# May raise a permission denied
if check_object_permissions:
self.check_object_permissions(self.request, node_request)
return node_request
def get_node(self, check_object_permissions=True):
node = get_object_or_error(
Node,
self.kwargs[self.node_lookup_url_kwarg],
self.request,
display_name='node'
)
# May raise a permission denied
if check_object_permissions:
self.check_object_permissions(self.request, node)
return node
class NodeRequestDetail(JSONAPIBaseView, generics.RetrieveAPIView, NodeRequestMixin):
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
NodeRequestPermission
)
required_read_scopes = [CoreScopes.NODE_REQUESTS_READ]
required_write_scopes = [CoreScopes.NULL]
serializer_class = NodeRequestSerializer
view_category = 'requests'
view_name = 'node-request-detail'
def get_object(self):
return self.get_noderequest()
| {
"content_hash": "22542515a1e7293aa6dde1f87b5a58b4",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 85,
"avg_line_length": 30.753846153846155,
"alnum_prop": 0.6953476738369184,
"repo_name": "binoculars/osf.io",
"id": "859972d8bf1cd4150b537dd8414bd7153615de00",
"size": "1999",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "api/requests/views.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "106867"
},
{
"name": "HTML",
"bytes": "236223"
},
{
"name": "JavaScript",
"bytes": "1831128"
},
{
"name": "Mako",
"bytes": "666783"
},
{
"name": "Python",
"bytes": "7866290"
},
{
"name": "VCL",
"bytes": "13885"
}
],
"symlink_target": ""
} |
"""
A driver for Bare-metal platform.
"""
import os
from nova.compute import power_state
from nova import context as nova_context
from nova import db
from nova import exception
from nova import flags
from nova.openstack.common import cfg
from nova.openstack.common import importutils
from nova.openstack.common import log as logging
from nova.virt.baremetal import baremetal_states
from nova.virt.baremetal import bmdb
from nova.virt import driver
from nova.virt.libvirt import imagecache
opts = [
cfg.BoolOpt('baremetal_inject_password',
default=True,
help='Whether baremetal compute injects password or not'),
cfg.StrOpt('baremetal_injected_network_template',
default='$pybasedir/nova/virt/baremetal/interfaces.template',
help='Template file for injected network'),
cfg.StrOpt('baremetal_vif_driver',
default='nova.virt.baremetal.vif_driver.BareMetalVIFDriver',
help='Baremetal VIF driver.'),
cfg.StrOpt('baremetal_firewall_driver',
default='nova.virt.firewall.NoopFirewallDriver',
help='Baremetal firewall driver.'),
cfg.StrOpt('baremetal_volume_driver',
default='nova.virt.baremetal.volume_driver.LibvirtVolumeDriver',
help='Baremetal volume driver.'),
cfg.ListOpt('instance_type_extra_specs',
default=[],
help='a list of additional capabilities corresponding to '
'instance_type_extra_specs for this compute '
'host to advertise. Valid entries are name=value, pairs '
'For example, "key1:val1, key2:val2"'),
cfg.StrOpt('baremetal_driver',
default='nova.virt.baremetal.tilera.TILERA',
help='Bare-metal driver runs on'),
cfg.StrOpt('power_manager',
default='nova.virt.baremetal.ipmi.Ipmi',
help='power management method'),
cfg.StrOpt('baremetal_tftp_root',
default='/tftpboot',
help='BareMetal compute nodes tftp root path'),
]
FLAGS = flags.FLAGS
FLAGS.register_opts(opts)
LOG = logging.getLogger(__name__)
class NoSuitableBareMetalNode(exception.NovaException):
message = _("Failed to find suitable BareMetalNode")
def _get_baremetal_nodes(context):
nodes = bmdb.bm_node_get_all(context, service_host=FLAGS.host)
return nodes
def _get_baremetal_node_by_instance_uuid(instance_uuid):
ctx = nova_context.get_admin_context()
node = bmdb.bm_node_get_by_instance_uuid(ctx, instance_uuid)
if not node:
return None
if node['service_host'] != FLAGS.host:
return None
return node
def _find_suitable_baremetal_node(context, instance):
result = None
for node in _get_baremetal_nodes(context):
if node['instance_uuid']:
continue
if node['registration_status'] != 'done':
continue
if node['cpus'] < instance['vcpus']:
continue
if node['memory_mb'] < instance['memory_mb']:
continue
if result == None:
result = node
else:
if node['cpus'] < result['cpus']:
result = node
elif node['cpus'] == result['cpus'] \
and node['memory_mb'] < result['memory_mb']:
result = node
return result
def _update_baremetal_state(context, node, instance, state):
instance_uuid = None
if instance:
instance_uuid = instance['uuid']
bmdb.bm_node_update(context, node['id'],
{'instance_uuid': instance_uuid,
'task_state': state,
})
def get_power_manager(node, **kwargs):
cls = importutils.import_class(FLAGS.power_manager)
return cls(node, **kwargs)
class BareMetalDriver(driver.ComputeDriver):
"""BareMetal hypervisor driver."""
def __init__(self):
super(BareMetalDriver, self).__init__()
self.baremetal_nodes = importutils.import_object(
FLAGS.baremetal_driver)
self._vif_driver = importutils.import_object(
FLAGS.baremetal_vif_driver)
self._firewall_driver = importutils.import_object(
FLAGS.baremetal_firewall_driver)
self._volume_driver = importutils.import_object(
FLAGS.baremetal_volume_driver)
self._image_cache_manager = imagecache.ImageCacheManager()
extra_specs = {}
extra_specs["hypervisor_type"] = self.get_hypervisor_type()
extra_specs["baremetal_driver"] = FLAGS.baremetal_driver
for pair in FLAGS.instance_type_extra_specs:
keyval = pair.split(':', 1)
keyval[0] = keyval[0].strip()
keyval[1] = keyval[1].strip()
extra_specs[keyval[0]] = keyval[1]
if not 'cpu_arch' in extra_specs:
LOG.warning('cpu_arch is not found in instance_type_extra_specs')
extra_specs['cpu_arch'] = ''
self._extra_specs = extra_specs
@classmethod
def instance(cls):
if not hasattr(cls, '_instance'):
cls._instance = cls()
return cls._instance
def init_host(self, host):
return
def get_hypervisor_type(self):
return 'baremetal'
def get_hypervisor_version(self):
return 1
def list_instances(self):
l = []
ctx = nova_context.get_admin_context()
for node in _get_baremetal_nodes(ctx):
if node['instance_uuid']:
inst = db.instance_get_by_uuid(ctx, node['instance_uuid'])
if inst:
l.append(inst['name'])
return l
def spawn(self, context, instance, image_meta, injected_files,
admin_password, network_info=None, block_device_info=None):
node = _find_suitable_baremetal_node(context, instance)
if not node:
LOG.info("no suitable baremetal node found")
raise NoSuitableBareMetalNode()
_update_baremetal_state(context, node, instance,
baremetal_states.BUILDING)
var = self.baremetal_nodes.define_vars(instance, network_info,
block_device_info)
# if we have bmpxeinstaller set as a image_meta properties then will
# handle the image a bit differently
pxe_tftp_build = self.check_if_tftp_boot_image(image_meta)
if pxe_tftp_build:
LOG.debug("Setting up pxe tftp boot for bare metal")
self.baremetal_nodes.create_pxe_tftp_boot_image_files(var, node,
context, instance, image_meta, admin_password,
block_device_info=block_device_info)
self.baremetal_nodes.setup_node_dnsmasq(node, var, instance)
else:
self._plug_vifs(instance, network_info, context=context)
self._firewall_driver.setup_basic_filtering(instance, network_info)
self._firewall_driver.prepare_instance_filter(instance, network_info)
self.baremetal_nodes.create_image(var, context, image_meta, node,
instance,
injected_files=injected_files,
admin_password=admin_password)
self.baremetal_nodes.activate_bootloader(var, context, node,
instance)
pm = get_power_manager(node)
if pxe_tftp_build:
state = pm.activate_tftp_node()
_update_baremetal_state(context, node, instance, state)
else:
state = pm.activate_node()
_update_baremetal_state(context, node, instance, state)
self.baremetal_nodes.activate_node(var, context, node, instance)
self._firewall_driver.apply_instance_filter(instance, network_info)
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
for vol in block_device_mapping:
connection_info = vol['connection_info']
mountpoint = vol['mount_device']
self.attach_volume(connection_info, instance['name'], mountpoint)
if node['terminal_port']:
pm.start_console(node['terminal_port'], node['id'])
def reboot(self, instance, network_info):
node = _get_baremetal_node_by_instance_uuid(instance['uuid'])
if not node:
raise exception.InstanceNotFound(instance_id=instance['uuid'])
ctx = nova_context.get_admin_context()
pm = get_power_manager(node)
state = pm.reboot_node()
_update_baremetal_state(ctx, node, instance, state)
def destroy(self, instance, network_info, block_device_info=None):
ctx = nova_context.get_admin_context()
node = _get_baremetal_node_by_instance_uuid(instance['uuid'])
if not node:
LOG.warning("Instance:id='%s' not found" % instance['uuid'])
return
var = self.baremetal_nodes.define_vars(instance, network_info,
block_device_info)
# if this is a tftp booted node (need image_meta here)
if os.path.exists(os.path.join(var['image_root'], 'mnt')):
self.baremetal_nodes.remove_node_dnsmasq(node, var, instance)
self.baremetal_nodes.deactivate_tftp_node(var, ctx, node, instance)
else:
self.baremetal_nodes.deactivate_node(var, ctx, node, instance)
## cleanup volumes
# NOTE(vish): we disconnect from volumes regardless
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
for vol in block_device_mapping:
connection_info = vol['connection_info']
mountpoint = vol['mount_device']
self.detach_volume(connection_info, instance['name'], mountpoint)
self.baremetal_nodes.deactivate_bootloader(var, ctx, node, instance)
self.baremetal_nodes.destroy_images(var, ctx, node, instance)
pm = get_power_manager(node)
pm.stop_console(node['id'])
## power off the node
state = pm.deactivate_node()
# stop firewall
self._firewall_driver.unfilter_instance(instance,
network_info=network_info)
self._unplug_vifs(instance, network_info)
_update_baremetal_state(ctx, node, None, state)
def get_volume_connector(self, instance):
return self._volume_driver.get_volume_connector(instance)
def attach_volume(self, connection_info, instance_name, mountpoint):
return self._volume_driver.attach_volume(connection_info,
instance_name, mountpoint)
@exception.wrap_exception()
def detach_volume(self, connection_info, instance_name, mountpoint):
return self._volume_driver.detach_volume(connection_info,
instance_name, mountpoint)
def get_info(self, instance):
node = _get_baremetal_node_by_instance_uuid(instance['uuid'])
if not node:
raise exception.InstanceNotFound(instance_id=instance['uuid'])
pm = get_power_manager(node)
ps = power_state.SHUTDOWN
if pm.is_power_on():
ps = power_state.RUNNING
return {'state': ps,
'max_mem': node['memory_mb'],
'mem': node['memory_mb'],
'num_cpu': node['cpus'],
'cpu_time': 0}
def refresh_security_group_rules(self, security_group_id):
self._firewall_driver.refresh_security_group_rules(security_group_id)
return True
def refresh_security_group_members(self, security_group_id):
self._firewall_driver.refresh_security_group_members(security_group_id)
return True
def refresh_provider_fw_rules(self):
self._firewall_driver.refresh_provider_fw_rules()
def _sum_baremetal_resources(self, ctxt):
vcpus = 0
vcpus_used = 0
memory_mb = 0
memory_mb_used = 0
local_gb = 0
local_gb_used = 0
for node in _get_baremetal_nodes(ctxt):
if node['registration_status'] != 'done':
continue
vcpus += node['cpus']
memory_mb += node['memory_mb']
local_gb += node['local_gb']
if node['instance_uuid']:
vcpus_used += node['cpus']
memory_mb_used += node['memory_mb']
local_gb_used += node['local_gb']
dic = {'vcpus': vcpus,
'memory_mb': memory_mb,
'local_gb': local_gb,
'vcpus_used': vcpus_used,
'memory_mb_used': memory_mb_used,
'local_gb_used': local_gb_used,
}
return dic
def _max_baremetal_resources(self, ctxt):
max_node = {'cpus': 0,
'memory_mb': 0,
'local_gb': 0,
}
for node in _get_baremetal_nodes(ctxt):
if node['registration_status'] != 'done':
continue
if node['instance_uuid']:
continue
# Put prioirty to memory size.
# You can use CPU and HDD, if you change the following lines.
if max_node['memory_mb'] < node['memory_mb']:
max_node = node
elif max_node['memory_mb'] == node['memory_mb']:
if max_node['cpus'] < node['cpus']:
max_node = node
elif max_node['cpus'] == node['cpus']:
if max_node['local_gb'] < node['local_gb']:
max_node = node
dic = {'vcpus': max_node['cpus'],
'memory_mb': max_node['memory_mb'],
'local_gb': max_node['local_gb'],
'vcpus_used': 0,
'memory_mb_used': 0,
'local_gb_used': 0,
}
return dic
def refresh_instance_security_rules(self, instance):
self._firewall_driver.refresh_instance_security_rules(instance)
def update_available_resource(self, ctxt, host):
"""Updates compute manager resource info on ComputeNode table.
This method is called when nova-coompute launches, and
whenever admin executes "nova-manage service update_resource".
:param ctxt: security context
:param host: hostname that compute manager is currently running
"""
dic = self._max_baremetal_resources(ctxt)
#dic = self._sum_baremetal_resources(ctxt)
dic['hypervisor_type'] = self.get_hypervisor_type()
dic['hypervisor_version'] = self.get_hypervisor_version()
dic['cpu_info'] = 'baremetal cpu'
try:
service_ref = db.service_get_all_compute_by_host(ctxt, host)[0]
except exception.NotFound:
raise exception.ComputeServiceUnavailable(host=host)
dic['service_id'] = service_ref['id']
compute_node_ref = service_ref['compute_node']
if not compute_node_ref:
LOG.info(_('Compute_service record created for %s ') % host)
db.compute_node_create(ctxt, dic)
else:
LOG.info(_('Compute_service record updated for %s ') % host)
db.compute_node_update(ctxt, compute_node_ref[0]['id'], dic)
def ensure_filtering_rules_for_instance(self, instance_ref, network_info):
self._firewall_driver.setup_basic_filtering(instance_ref, network_info)
self._firewall_driver.prepare_instance_filter(instance_ref,
network_info)
def unfilter_instance(self, instance_ref, network_info):
self._firewall_driver.unfilter_instance(instance_ref,
network_info=network_info)
def _get_host_stats(self):
dic = self._max_baremetal_resources(nova_context.get_admin_context())
memory_total = dic['memory_mb'] * 1024 * 1024
memory_free = (dic['memory_mb'] - dic['memory_mb_used']) * 1024 * 1024
disk_total = dic['local_gb'] * 1024 * 1024 * 1024
disk_used = dic['local_gb_used'] * 1024 * 1024 * 1024
return {
'host_name-description': 'baremetal ' + FLAGS.host,
'host_hostname': FLAGS.host,
'host_memory_total': memory_total,
'host_memory_overhead': 0,
'host_memory_free': memory_free,
'host_memory_free_computed': memory_free,
'host_other_config': {},
'disk_available': disk_total - disk_used,
'disk_total': disk_total,
'disk_used': disk_used,
'host_name_label': FLAGS.host,
'cpu_arch': self._extra_specs.get('cpu_arch'),
'instance_type_extra_specs': self._extra_specs,
}
def update_host_status(self):
return self._get_host_stats()
def get_host_stats(self, refresh=False):
return self._get_host_stats()
def plug_vifs(self, instance, network_info):
"""Plugin VIFs into networks."""
self._plug_vifs(instance, network_info)
def _plug_vifs(self, instance, network_info, context=None):
if not context:
context = nova_context.get_admin_context()
node = _get_baremetal_node_by_instance_uuid(instance['uuid'])
if node:
pifs = bmdb.bm_interface_get_all_by_bm_node_id(context, node['id'])
for pif in pifs:
if pif['vif_uuid']:
bmdb.bm_interface_set_vif_uuid(context, pif['id'], None)
for (network, mapping) in network_info:
self._vif_driver.plug(instance, (network, mapping))
def _unplug_vifs(self, instance, network_info):
for (network, mapping) in network_info:
self._vif_driver.unplug(instance, (network, mapping))
def manage_image_cache(self, context):
"""Manage the local cache of images."""
self._image_cache_manager.verify_base_images(context)
def get_console_output(self, instance):
node = _get_baremetal_node_by_instance_uuid(instance['uuid'])
return self.baremetal_nodes.get_console_output(node, instance)
def check_if_tftp_boot_image(self, image_meta):
"""
check to see if a image is a tftp boot image
"""
tftp_build = False
if 'properties' in image_meta:
if 'bmpxetftpinstaller' in image_meta['properties']:
if image_meta['properties']['bmpxetftpinstaller']:
# this is a install image for tftp pxe booting bm nodes
# so we are going to handle it differently
LOG.debug("bmpxetftpinstaller set")
tftp_build = True
else:
LOG.debug("bmpxetftpinstaller not in image_meta properties")
else:
LOG.debug("properties not in image_meta")
return tftp_build | {
"content_hash": "44b7da83468804e9194e4e34cdf55b76",
"timestamp": "",
"source": "github",
"line_count": 497,
"max_line_length": 81,
"avg_line_length": 38.503018108651915,
"alnum_prop": 0.581364966555184,
"repo_name": "NoBodyCam/TftpPxeBootBareMetal",
"id": "abe383575f6f6f454c62694f3e311479ef9fc305",
"size": "19893",
"binary": false,
"copies": "1",
"ref": "refs/heads/tftp_pxe_boot",
"path": "nova/virt/baremetal/driver.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "7403"
},
{
"name": "Python",
"bytes": "6568288"
},
{
"name": "Shell",
"bytes": "17010"
}
],
"symlink_target": ""
} |
from distutils.core import setup
from setuptools import find_packages
setup(
name='snactor',
version='0.2',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
url='https://github.com/leapp-to/snactor',
license='ASL 2.0',
author="Vinzenz 'evilissimo' Feenstra",
author_email='evilissimo@redhat.com',
description='snactor is a python library for actors',
install_requires=[],
scripts=['tools/snactor_runner'],
include_package_data=True,
zip_safe=False
)
| {
"content_hash": "79ad85a81d98315326b20500ed790f66",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 65,
"avg_line_length": 30.11764705882353,
"alnum_prop": 0.681640625,
"repo_name": "leapp-to/snactor",
"id": "7c4a74f9ed137ca08c5502617a5028ee9ac79e0d",
"size": "512",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "473"
},
{
"name": "Python",
"bytes": "38240"
}
],
"symlink_target": ""
} |
policy_data = """
{
"context_is_admin": "role:admin or role:administrator",
"os_compute_api:servers:show:host_status": "",
"os_compute_api:servers:migrations:force_complete": "",
"os_compute_api:os-admin-actions:inject_network_info": "",
"os_compute_api:os-admin-actions:reset_network": "",
"os_compute_api:os-admin-actions:reset_state": "",
"os_compute_api:os-admin-password": "",
"os_compute_api:os-agents": "",
"os_compute_api:os-attach-interfaces": "",
"os_compute_api:os-baremetal-nodes": "",
"os_compute_api:os-cells": "",
"os_compute_api:os-certificates:create": "",
"os_compute_api:os-certificates:show": "",
"os_compute_api:os-cloudpipe": "",
"os_compute_api:os-config-drive": "",
"os_compute_api:os-console-output": "",
"os_compute_api:os-remote-consoles": "",
"os_compute_api:os-consoles:create": "",
"os_compute_api:os-consoles:delete": "",
"os_compute_api:os-consoles:index": "",
"os_compute_api:os-consoles:show": "",
"os_compute_api:os-create-backup": "",
"os_compute_api:os-deferred-delete": "",
"os_compute_api:os-extended-server-attributes": "",
"os_compute_api:os-extended-status": "",
"os_compute_api:os-extended-availability-zone": "",
"os_compute_api:ips:index": "",
"os_compute_api:ips:show": "",
"os_compute_api:os-extended-volumes": "",
"os_compute_api:extensions": "",
"os_compute_api:os-fixed-ips": "",
"os_compute_api:os-flavor-access": "",
"os_compute_api:os-flavor-access:remove_tenant_access": "",
"os_compute_api:os-flavor-access:add_tenant_access": "",
"os_compute_api:os-flavor-rxtx": "",
"os_compute_api:os-flavor-extra-specs:index": "",
"os_compute_api:os-flavor-extra-specs:show": "",
"os_compute_api:os-flavor-manage": "",
"os_compute_api:os-floating-ip-dns": "",
"os_compute_api:os-floating-ip-dns:domain:update": "",
"os_compute_api:os-floating-ip-dns:domain:delete": "",
"os_compute_api:os-floating-ip-pools": "",
"os_compute_api:os-floating-ips": "",
"os_compute_api:os-floating-ips-bulk": "",
"os_compute_api:os-fping": "",
"os_compute_api:os-hide-server-addresses": "",
"os_compute_api:image-size": "",
"os_compute_api:os-instance-actions": "",
"os_compute_api:os-instance-usage-audit-log": "",
"os_compute_api:os-keypairs": "",
"os_compute_api:os-lock-server:lock": "",
"os_compute_api:os-lock-server:unlock": "",
"os_compute_api:os-migrate-server:migrate": "",
"os_compute_api:os-migrate-server:migrate_live": "",
"os_compute_api:os-multinic": "",
"os_compute_api:os-networks": "",
"os_compute_api:os-networks:view": "",
"os_compute_api:os-networks-associate": "",
"os_compute_api:os-tenant-networks": "",
"os_compute_api:os-pause-server:pause": "",
"os_compute_api:os-pause-server:unpause": "",
"os_compute_api:os-pci:pci_servers": "",
"os_compute_api:os-pci:index": "",
"os_compute_api:os-pci:detail": "",
"os_compute_api:os-pci:show": "",
"os_compute_api:os-quota-sets:show": "",
"os_compute_api:os-quota-sets:update": "",
"os_compute_api:os-quota-sets:delete": "",
"os_compute_api:os-quota-sets:detail": "",
"os_compute_api:os-quota-sets:defaults": "",
"os_compute_api:os-quota-class-sets:update": "",
"os_compute_api:os-quota-class-sets:show": "",
"os_compute_api:os-rescue": "",
"os_compute_api:os-security-group-default-rules": "",
"os_compute_api:os-security-groups": "",
"os_compute_api:os-server-diagnostics": "",
"os_compute_api:os-server-password": "",
"os_compute_api:os-server-tags:index": "",
"os_compute_api:os-server-tags:show": "",
"os_compute_api:os-server-tags:update": "",
"os_compute_api:os-server-tags:update_all": "",
"os_compute_api:os-server-tags:delete": "",
"os_compute_api:os-server-tags:delete_all": "",
"os_compute_api:os-server-usage": "",
"os_compute_api:os-server-groups": "",
"os_compute_api:os-services": "",
"os_compute_api:os-shelve:shelve": "",
"os_compute_api:os-shelve:shelve_offload": "",
"os_compute_api:os-simple-tenant-usage:show": "",
"os_compute_api:os-simple-tenant-usage:list": "",
"os_compute_api:os-shelve:unshelve": "",
"os_compute_api:os-suspend-server:suspend": "",
"os_compute_api:os-suspend-server:resume": "",
"os_compute_api:os-virtual-interfaces": "",
"os_compute_api:os-volumes": "",
"os_compute_api:os-volumes-attachments:index": "",
"os_compute_api:os-volumes-attachments:show": "",
"os_compute_api:os-volumes-attachments:create": "",
"os_compute_api:os-volumes-attachments:update": "",
"os_compute_api:os-volumes-attachments:delete": "",
"os_compute_api:os-availability-zone:list": "",
"os_compute_api:os-availability-zone:detail": "",
"os_compute_api:limits": "",
"os_compute_api:os-assisted-volume-snapshots:create": "",
"os_compute_api:os-assisted-volume-snapshots:delete": "",
"os_compute_api:server-metadata:create": "",
"os_compute_api:server-metadata:update": "",
"os_compute_api:server-metadata:update_all": "",
"os_compute_api:server-metadata:delete": "",
"os_compute_api:server-metadata:show": "",
"os_compute_api:server-metadata:index": ""
}
"""
| {
"content_hash": "f722b905b4ad0917febc118d187b421f",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 63,
"avg_line_length": 45.401709401709404,
"alnum_prop": 0.6297063253012049,
"repo_name": "cloudbase/nova",
"id": "951df19d3fea08deca3cedcfeba242cd1ac25071",
"size": "5903",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "nova/tests/unit/fake_policy.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "3325"
},
{
"name": "Python",
"bytes": "18199370"
},
{
"name": "Shell",
"bytes": "37074"
},
{
"name": "Smarty",
"bytes": "299657"
}
],
"symlink_target": ""
} |
"""Provides utility functions"""
import random
import string
def random_string(length, pool=4):
"""Generates a random string of length length
containing a variety of characters as specified by pool"""
char_pool = string.letters
if pool >= 2:
char_pool += string.digits
if pool >= 3:
char_pool += string.punctuation
if pool >= 4:
char_pool += string.whitespace
random_string_return = ''.join([random.choice(char_pool) for _ in range(length)])
return random_string_return
| {
"content_hash": "3001716d1c1ac660178c6202e5c57094",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 85,
"avg_line_length": 25.333333333333332,
"alnum_prop": 0.6578947368421053,
"repo_name": "FreakJoe/cryptolockpy",
"id": "2ee89ea632fbebddd699374de6bb6117483b69c5",
"size": "532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cryptolock/utility.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "232"
},
{
"name": "Python",
"bytes": "26204"
}
],
"symlink_target": ""
} |
from openerp.addons.mail.tests.common import TestMail
from openerp.exceptions import AccessError
from openerp.osv.orm import except_orm
from openerp.tools import mute_logger
class TestMailGroup(TestMail):
@mute_logger('openerp.addons.base.ir.ir_model', 'openerp.models')
def test_00_mail_group_access_rights(self):
""" Testing mail_group access rights and basic mail_thread features """
cr, uid, user_noone_id, user_employee_id = self.cr, self.uid, self.user_noone_id, self.user_employee_id
# Do: Bert reads Jobs -> ok, public
self.mail_group.read(cr, user_noone_id, [self.group_jobs_id])
# Do: Bert read Pigs -> ko, restricted to employees
with self.assertRaises(except_orm):
self.mail_group.read(cr, user_noone_id, [self.group_pigs_id])
# Do: Raoul read Pigs -> ok, belong to employees
self.mail_group.read(cr, user_employee_id, [self.group_pigs_id])
# Do: Bert creates a group -> ko, no access rights
with self.assertRaises(AccessError):
self.mail_group.create(cr, user_noone_id, {'name': 'Test'})
# Do: Raoul creates a restricted group -> ok
new_group_id = self.mail_group.create(cr, user_employee_id, {'name': 'Test'})
# Do: Bert added in followers, read -> ok, in followers
self.mail_group.message_subscribe_users(cr, uid, [new_group_id], [user_noone_id])
self.mail_group.read(cr, user_noone_id, [new_group_id])
# Do: Raoul reads Priv -> ko, private
with self.assertRaises(except_orm):
self.mail_group.read(cr, user_employee_id, [self.group_priv_id])
# Do: Raoul added in follower, read -> ok, in followers
self.mail_group.message_subscribe_users(cr, uid, [self.group_priv_id], [user_employee_id])
self.mail_group.read(cr, user_employee_id, [self.group_priv_id])
# Do: Raoul write on Jobs -> ok
self.mail_group.write(cr, user_employee_id, [self.group_priv_id], {'name': 'modified'})
# Do: Bert cannot write on Private -> ko (read but no write)
with self.assertRaises(AccessError):
self.mail_group.write(cr, user_noone_id, [self.group_priv_id], {'name': 're-modified'})
# Test: Bert cannot unlink the group
with self.assertRaises(except_orm):
self.mail_group.unlink(cr, user_noone_id, [self.group_priv_id])
# Do: Raoul unlinks the group, there are no followers and messages left
self.mail_group.unlink(cr, user_employee_id, [self.group_priv_id])
fol_ids = self.mail_followers.search(cr, uid, [('res_model', '=', 'mail.group'), ('res_id', '=', self.group_priv_id)])
self.assertFalse(fol_ids, 'unlinked document should not have any followers left')
msg_ids = self.mail_message.search(cr, uid, [('model', '=', 'mail.group'), ('res_id', '=', self.group_priv_id)])
self.assertFalse(msg_ids, 'unlinked document should not have any followers left')
| {
"content_hash": "1d821c2739b3875747faaa3438ce1a86",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 126,
"avg_line_length": 58.3921568627451,
"alnum_prop": 0.6474143720617864,
"repo_name": "diogocs1/comps",
"id": "c131ce0bd0b309b4a06c0258517dabed119d9ec2",
"size": "3964",
"binary": false,
"copies": "139",
"ref": "refs/heads/master",
"path": "web/addons/mail/tests/test_mail_group.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "701"
},
{
"name": "CSS",
"bytes": "856533"
},
{
"name": "HTML",
"bytes": "299671"
},
{
"name": "Java",
"bytes": "620166"
},
{
"name": "JavaScript",
"bytes": "5844302"
},
{
"name": "Makefile",
"bytes": "21002"
},
{
"name": "PHP",
"bytes": "14259"
},
{
"name": "Python",
"bytes": "10647376"
},
{
"name": "Ruby",
"bytes": "220"
},
{
"name": "Shell",
"bytes": "17746"
},
{
"name": "XSLT",
"bytes": "120278"
}
],
"symlink_target": ""
} |
import unittest
from ctypes import *
class StructFieldsTestCase(unittest.TestCase):
# Structure/Union classes must get 'finalized' sooner or
# later, when one of these things happen:
#
# 1. _fields_ is set.
# 2. An instance is created.
# 3. The type is used as field of another Structure/Union.
# 4. The type is subclassed
#
# When they are finalized, assigning _fields_ is no longer allowed.
def test_1_A(self):
class X(Structure):
pass
self.assertEqual(sizeof(X), 0) # not finalized
X._fields_ = [] # finalized
self.assertRaises(AttributeError, setattr, X, "_fields_", [])
def test_1_B(self):
class X(Structure):
_fields_ = [] # finalized
self.assertRaises(AttributeError, setattr, X, "_fields_", [])
def test_2(self):
class X(Structure):
pass
X()
self.assertRaises(AttributeError, setattr, X, "_fields_", [])
def test_3(self):
class X(Structure):
pass
class Y(Structure):
_fields_ = [("x", X)] # finalizes X
self.assertRaises(AttributeError, setattr, X, "_fields_", [])
def test_4(self):
class X(Structure):
pass
class Y(X):
pass
self.assertRaises(AttributeError, setattr, X, "_fields_", [])
Y._fields_ = []
self.assertRaises(AttributeError, setattr, X, "_fields_", [])
if __name__ == "__main__":
unittest.main()
| {
"content_hash": "95be5104e6ad67c0e198453132111502",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 71,
"avg_line_length": 31.06,
"alnum_prop": 0.5486155827430779,
"repo_name": "Jeff-Tian/mybnb",
"id": "12827e2f51b324a1728dd154257131ceda18b07e",
"size": "1553",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "Python27/Lib/ctypes/test/test_struct_fields.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "455330"
},
{
"name": "Batchfile",
"bytes": "6263"
},
{
"name": "C",
"bytes": "2304983"
},
{
"name": "C#",
"bytes": "8440"
},
{
"name": "C++",
"bytes": "31815"
},
{
"name": "CSS",
"bytes": "30628"
},
{
"name": "Cucumber",
"bytes": "248616"
},
{
"name": "F#",
"bytes": "2310"
},
{
"name": "Forth",
"bytes": "506"
},
{
"name": "GLSL",
"bytes": "1040"
},
{
"name": "Groff",
"bytes": "31983"
},
{
"name": "HTML",
"bytes": "376863"
},
{
"name": "JavaScript",
"bytes": "20239"
},
{
"name": "M4",
"bytes": "67848"
},
{
"name": "Makefile",
"bytes": "142926"
},
{
"name": "Mask",
"bytes": "969"
},
{
"name": "PLSQL",
"bytes": "22886"
},
{
"name": "Python",
"bytes": "19913027"
},
{
"name": "REXX",
"bytes": "3862"
},
{
"name": "Ruby",
"bytes": "14954382"
},
{
"name": "Shell",
"bytes": "366205"
},
{
"name": "Tcl",
"bytes": "2150972"
},
{
"name": "TeX",
"bytes": "230259"
},
{
"name": "Visual Basic",
"bytes": "494"
},
{
"name": "XSLT",
"bytes": "3736"
},
{
"name": "Yacc",
"bytes": "14342"
}
],
"symlink_target": ""
} |
import os,sys
from lxml import etree
#the em-dash before the word even was replaced with — in this constant:
default_xslt = """<?xml version="1.0" encoding="UTF-8"?>
<!-- #############################################################
# Name: UpdateMetaData-1.2.xsl
# Purpose: Update the metadata to the lastest preferrences
#
# Author: Greg Trihus <greg_trihus@sil.org>
#
# Created: 2012/06/07
# Updated: 2012/10/26 gt-removed ethnologue link and Revision
# Updated: 2013/01/10 gt-make name useful for google analytics
# use Wycliffe Bible Translators, Inc.
# Copyright: (c) 2011 SIL International
# Licence: <LPGL>
################################################################-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:param name="UseProp">false</xsl:param>
<xsl:variable name="dcds">http://purl.org/dc/xmlns/2008/09/01/dc-ds-xml/</xsl:variable>
<xsl:output encoding="UTF-8" method="xml"/>
<!-- New processing instruction format for relax network grammer validation -->
<xsl:template match="processing-instruction()"/>
<!-- New root -->
<xsl:template match="DBLScriptureProject |DBLMetadata">
<xsl:choose>
<xsl:when test="'$UseProp' = 'true'">
<xsl:processing-instruction name="xml-model">href="metadataWbt-1.2.rnc" type="application/relax-ng-compact-syntax"</xsl:processing-instruction>
</xsl:when>
<xsl:otherwise>
<xsl:processing-instruction name="xml-model">href="metadata.rnc" type="application/relax-ng-compact-syntax"</xsl:processing-instruction>
</xsl:otherwise>
</xsl:choose>
<DBLMetadata>
<!-- xsl:copy-of select="namespace::identification/scope/@*"/ -->
<xsl:attribute name="id">2880c78491b2f8ce</xsl:attribute>
<xsl:attribute name="revision">3</xsl:attribute>
<xsl:attribute name="type">text</xsl:attribute>
<xsl:attribute name="typeVersion">1.2</xsl:attribute>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="xml:base">http://purl.org/ubs/metadata/dc/terms/</xsl:attribute>
<!--xsl:attribute name="ns0:propertyURI" namespace="{$dcds}">text</xsl:attribute-->
</xsl:if>
<xsl:apply-templates/>
</DBLMetadata>
</xsl:template>
<xsl:template match="identification">
<identification>
<name>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">title</xsl:attribute>
</xsl:if>
<xsl:value-of select="//country/iso"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="//language/iso"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="//language/name"/>
</name>
<xsl:apply-templates select="nameLocal"/>
<xsl:apply-templates select="abbreviation"/>
<xsl:apply-templates select="abbreviationLocal"/>
<scope>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">title/scriptureScope</xsl:attribute>
</xsl:if>
<xsl:text>NT</xsl:text>
</scope>
<description>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">description</xsl:attribute>
</xsl:if>
<!-- xsl:value-of select="description"/ -->
<xsl:call-template name="description"/>
</description>
<dateCompleted>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">date</xsl:attribute>
<xsl:attribute name="sesURI" namespace="{$dcds}">http://purl.org/dc/terms/W3CDTF</xsl:attribute>
</xsl:if>
<xsl:value-of select="dateCompleted"/>
</dateCompleted>
<xsl:if test="systemId[@type = 'reap']">
<systemId>
<xsl:attribute name="type">reap</xsl:attribute>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">identifier/reapID</xsl:attribute>
</xsl:if>
<xsl:value-of select="systemId[@type = 'reap']"/>
</systemId>
</xsl:if>
<systemId>
<xsl:attribute name="type">paratext</xsl:attribute>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">identifier/ptxID</xsl:attribute>
</xsl:if>
<xsl:value-of select="systemId[@type = 'paratext']"/>
</systemId>
<systemId>
<xsl:attribute name="type">tms</xsl:attribute>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">identifier/tmsID</xsl:attribute>
</xsl:if>
<xsl:text>seeReap</xsl:text>
</systemId>
<xsl:apply-templates select="bundleProducer"/>
</identification>
</xsl:template>
<xsl:template name="description">
<xsl:text>New Testament in </xsl:text>
<xsl:value-of select="//language/name"/>
</xsl:template>
<xsl:template match="confidential">
<confidential>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">accessRights/confidential</xsl:attribute>
</xsl:if>
<xsl:choose>
<xsl:when test="text() = 'No'">false</xsl:when>
<xsl:when test="text() = 'Yes'">true</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
</xsl:choose>
</confidential>
</xsl:template>
<xsl:template match="agencies">
<agencies>
<xsl:apply-templates select="etenPartner" />
<creator>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">creator</xsl:attribute>
</xsl:if>
<xsl:choose>
<xsl:when test="(translation |creator)/text() = 'Wycliffe Inc.' or (translation | creator)/text() = 'Wycliffe'">
<xsl:text>Wycliffe Bible Translators, Inc.</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="translation |creator"/>
</xsl:otherwise>
</xsl:choose>
</creator>
<publisher>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">publisher</xsl:attribute>
</xsl:if>
<xsl:choose>
<xsl:when test="(publishing |publisher)/text() = 'Wycliffe Inc.' or (publishing |publisher)/text() = 'Wycliffe'">
<xsl:text>Wycliffe Bible Translators, Inc.</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="publishing |publisher"/>
</xsl:otherwise>
</xsl:choose>
</publisher>
<contributor>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">contributor</xsl:attribute>
</xsl:if>
</contributor>
</agencies>
</xsl:template>
<xsl:template match="language">
<language>
<iso>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">language/iso</xsl:attribute>
<xsl:attribute name="sesURI" namespace="{$dcds}">http://purl.org/dc/terms/ISO639-3</xsl:attribute>
</xsl:if>
<xsl:value-of select="iso"/>
</iso>
<name>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">subject/subjectLanguage</xsl:attribute>
<xsl:attribute name="sesURI" namespace="{$dcds}">http://purl.org/dc/terms/ISO639-3</xsl:attribute>
</xsl:if>
<xsl:value-of select="name"/>
</name>
<ldml>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">language/ldml</xsl:attribute>
</xsl:if>
<xsl:text>en</xsl:text>
</ldml>
<rod>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">language/rod</xsl:attribute>
</xsl:if>
</rod>
<script>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">language/script</xsl:attribute>
</xsl:if>
<xsl:value-of select="script"/>
</script>
<scriptDirection>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">language/scriptDirection</xsl:attribute>
</xsl:if>
<xsl:value-of select="scriptDirection"/>
</scriptDirection>
<numerals>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">language/numerals</xsl:attribute>
</xsl:if>
</numerals>
</language>
</xsl:template>
<xsl:template match="country">
<country>
<iso>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">coverage/spatial</xsl:attribute>
<xsl:attribute name="sesURI" namespace="{$dcds}">http://purl.org/dc/terms/ISO3166</xsl:attribute>
</xsl:if>
<xsl:value-of select="iso"/>
</iso>
<name>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">subject/subjectCountry</xsl:attribute>
</xsl:if>
<xsl:value-of select="name"/>
</name>
</country>
</xsl:template>
<xsl:template match="translation |/DBLMetadata/type">
<type>
<translationType>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">type/translationType</xsl:attribute>
</xsl:if>
<xsl:value-of select="type |translationType"/>
</translationType>
<audience>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">audience</xsl:attribute>
</xsl:if>
<xsl:value-of select="level |audience"/>
</audience>
</type>
</xsl:template>
<xsl:template match="bookNames">
<bookNames/>
</xsl:template>
<xsl:template match="contents">
<contents>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">tableOfContents</xsl:attribute>
</xsl:if>
<bookList>
<xsl:attribute name="id">default</xsl:attribute>
<name>
<xsl:value-of select="bookList/name"/>
</name>
<xsl:apply-templates select="bookList/nameLocal"/>
<xsl:apply-templates select="bookList/abbreviation"/>
<xsl:apply-templates select="bookList/abbreviationLocal"/>
<description>NT</description>
<range>Protestant New Testament (27 books)</range>
<tradition>Western Protestant order</tradition>
<xsl:apply-templates select="bookList/division"/>
</bookList>
</contents>
</xsl:template>
<!-- remove progress and checking nodes -->
<xsl:template match="progress | checking"/>
<xsl:template match="contact">
<contact>
<rightsHolder>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">rightsHolder</xsl:attribute>
</xsl:if>
<xsl:choose>
<xsl:when test="rightsHolder/text() = 'Wycliffe Inc.' or rightsHolder/text() = 'Wycliffe'">
<xsl:text>Wycliffe Bible Translators, Inc.</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="rightsHolder"/>
</xsl:otherwise>
</xsl:choose>
</rightsHolder>
<rightsHolderLocal>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">rightsHolder/contactLocal</xsl:attribute>
</xsl:if>
<xsl:choose>
<xsl:when test="rightsHolderLocal/text() = 'Wycliffe Inc.' or rightsHolderLocal/text() = 'Wycliffe'">
<xsl:text>Wycliffe Bible Translators, Inc.</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="rightsHolderLocal"/>
</xsl:otherwise>
</xsl:choose>
</rightsHolderLocal>
<rightsHolderAbbreviation>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">rightsHolder/contactAbbreviation</xsl:attribute>
</xsl:if>
<xsl:text>WBT</xsl:text>
</rightsHolderAbbreviation>
<rightsHolderURL>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">rightsHolder/contactURL</xsl:attribute>
</xsl:if>
<xsl:value-of select="rightsHolderURL"/>
</rightsHolderURL>
<rightsHolderFacebook>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">rightsHolder/contactFacebook</xsl:attribute>
</xsl:if>
<xsl:value-of select="rightsHolderFacebook"/>
</rightsHolderFacebook>
</contact>
</xsl:template>
<xsl:template match="rights |copyright">
<copyright>
<statement>
<xsl:attribute name="contentType">xhtml</xsl:attribute>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">rights</xsl:attribute>
</xsl:if>
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="rightsStatement |statement"/>
<xsl:with-param name="target">Wycliffe Inc.</xsl:with-param>
<xsl:with-param name="result">Wycliffe Bible Translators, Inc.</xsl:with-param>
</xsl:call-template>
</statement>
</copyright>
</xsl:template>
<xsl:template match="promotion">
<promotion>
<promoVersionInfo>
<xsl:attribute name="contentType">xhtml</xsl:attribute>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">description/pubPromoVersionInfo</xsl:attribute>
</xsl:if>
<xsl:apply-templates select="promoVersionInfo"/>
</promoVersionInfo>
<promoEmail>
<xsl:attribute name="contentType">xhtml</xsl:attribute>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">description/pubPromoEmail</xsl:attribute>
</xsl:if>
<p>Hi YouVersion friend,</p>
<p>
<xsl:text>Nice work downloading the </xsl:text>
<xsl:call-template name="nameDescription"/>
<xsl:text> in the Bible App! Now you'll have anytime, anywhere access to God's Word on your mobile device—even if you're outside of service coverage or not connected to the Internet. It also means faster service whenever you read that version since it's stored on your device. Enjoy!</xsl:text>
</p>
<p>
<xsl:text>This download was made possible by Wycliffe Bible Translators, Inc. We really appreciate their passion for making the Bible available to millions of people around the world. Because of their generosity, YouVersion users like you can open up the Bible and hear from God no matter where you are. You can learn more about the great things Wycliffe Bible Translators, Inc. is doing on many fronts by visiting </xsl:text>
<xsl:element name="a">
<xsl:attribute name="href">http://www.wycliffe.org</xsl:attribute>
<xsl:text>www.wycliffe.org.</xsl:text>
</xsl:element>
</p>
<p>
<xsl:text>Again, we're glad you downloaded the </xsl:text>
<xsl:call-template name="nameDescription"/>
<xsl:text> and hope it enriches your interaction with God's Word.</xsl:text>
</p>
<p>Your Friends at YouVersion</p>
</promoEmail>
</promotion>
</xsl:template>
<xsl:template name="nameDescription">
<xsl:element name="em">
<xsl:value-of select="//identification/name"/>
</xsl:element>
<xsl:text> (</xsl:text>
<xsl:call-template name="description"/>
<xsl:text>)</xsl:text>
</xsl:template>
<!-- Don't allow multiple br -->
<xsl:template match="br">
<xsl:if test="not(name(preceding-sibling::node()[1]) = 'br' or
normalize-space(preceding-sibling::node()[1]) = '' and name(preceding-sibling::node()[2]) = 'br')">
<br/>
</xsl:if>
</xsl:template>
<xsl:template match="archiveStatus">
<archiveStatus>
<archivistName>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">contributor/archivist</xsl:attribute>
</xsl:if>
<xsl:value-of select="archivistName"/>
</archivistName>
<dateArchived>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">dateSubmitted</xsl:attribute>
<xsl:attribute name="sesURI" namespace="{$dcds}">http://purl.org/dc/terms/W3CDTF</xsl:attribute>
</xsl:if>
<xsl:value-of select="dateArchived"/>
<xsl:if test="string-length(dateUpdated) = 10">
<xsl:text>T17:51:32.7907868+00:00</xsl:text>
</xsl:if>
</dateArchived>
<dateUpdated>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">modified</xsl:attribute>
<xsl:attribute name="sesURI" namespace="{$dcds}">http://purl.org/dc/terms/W3CDTF</xsl:attribute>
</xsl:if>
<xsl:value-of select="dateUpdated"/>
<xsl:if test="string-length(dateUpdated) = 10">
<xsl:text>T17:51:32.7907868+00:00</xsl:text>
</xsl:if>
</dateUpdated>
<comments>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">abstract</xsl:attribute>
</xsl:if>
<xsl:choose>
<xsl:when test="normalize-space(comments) = ''">
<xsl:text>no comment</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="comments"/>
</xsl:otherwise>
</xsl:choose>
</comments>
</archiveStatus>
</xsl:template>
<xsl:template match="format">
<format>
<xsl:if test="'$UseProp' = 'true'">
<xsl:attribute name="propertyURI" namespace="{$dcds}">format</xsl:attribute>
<xsl:attribute name="sesURI" namespace="{$dcds}">http://purl.org/dc/terms/IMT</xsl:attribute>
</xsl:if>
<xsl:text>text/xml</xsl:text>
</format>
</xsl:template>
<!-- Copy unaffected non-span elements-->
<xsl:template match="nameLocal |abbreviation |abbreviationLocal |bundleProducer |etenPartner |division |books |book |h2 |ul |li |b |em">
<xsl:element name="{name()}" namespace="{namespace-uri()}">
<xsl:for-each select="@*">
<xsl:attribute name="{name()}" namespace="{namespace-uri()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:for-each>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="p">
<xsl:choose>
<xsl:when test="text()[1] = 'Revision'">
<p>
<xsl:for-each select="* | text()">
<xsl:if test="position() > 3">
<xsl:apply-templates select="."/>
</xsl:if>
</xsl:for-each>
</p>
</xsl:when>
<xsl:otherwise>
<p>
<xsl:for-each select="* | text()">
<xsl:apply-templates select="."/>
</xsl:for-each>
</p>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="a">
<xsl:choose>
<xsl:when test="contains(.//@href, 'ethnologue')">
<xsl:value-of select="text()"/>
</xsl:when>
<xsl:otherwise>
<a>
<xsl:for-each select="* | @*">
<xsl:copy/>
</xsl:for-each>
<xsl:apply-templates/>
</a>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="text()">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="."/>
<xsl:with-param name="target">Wycliffe Inc.</xsl:with-param>
<xsl:with-param name="result">Wycliffe Bible Translators, Inc.</xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template match="comment()">
<xsl:copy/>
</xsl:template>
<xsl:template name="string-replace-all">
<xsl:param name="text"/>
<xsl:param name="target"/>
<xsl:param name="result"/>
<xsl:choose>
<xsl:when test="contains($text,$target)">
<xsl:copy-of select="substring-before($text, $target)"/>
<xsl:value-of select="$result"/>
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text, $target)"/>
<xsl:with-param name="target" select="$target"/>
<xsl:with-param name="result" select="$result"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
"""
modules ={}
def main(argv):
global default_xslt
if len(argv) > 2:
if argv[2][:1] == '"':
argv[2] = argv[2][1:-1]
xslt = open(argv[2]).read()
else:
xslt = default_xslt
xslt_root = etree.XML(xslt)
transform = etree.XSLT(xslt_root)
if argv[1][:1] == '"':
argv[1] = argv[1][1:-1]
doc = etree.parse(argv[1])
result_tree = transform(doc)
print transform.error_log
name = '%s-1.2%s' % os.path.splitext(argv[1])
f = open(name,'w')
f.write(unicode(result_tree).encode('utf-8'))
f.close()
if __name__ == '__main__':
main(sys.argv)
| {
"content_hash": "52ff9d6df36af32efe9146bcd7e02832",
"timestamp": "",
"source": "github",
"line_count": 563,
"max_line_length": 446,
"avg_line_length": 45.83658969804618,
"alnum_prop": 0.492404867085174,
"repo_name": "sillsdev/DblMetaData",
"id": "bbc16e54b1ac09204a454e470137199466f5bcd3",
"size": "26256",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ApplyUpd12/ApplyUpd12.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "159082"
},
{
"name": "CSS",
"bytes": "13522"
},
{
"name": "HTML",
"bytes": "84377"
},
{
"name": "Python",
"bytes": "71839"
},
{
"name": "Shell",
"bytes": "1183"
},
{
"name": "XSLT",
"bytes": "46530"
}
],
"symlink_target": ""
} |
"""For using the Beancount shell from Fava."""
# mypy: ignore-errors
import contextlib
import io
import textwrap
from typing import List
from typing import TYPE_CHECKING
from beancount.core.data import Entries
from beancount.core.data import Query
from beancount.parser.options import OPTIONS_DEFAULTS
from beancount.query import query_compile
from beancount.query.query import run_query
from beancount.query.query_compile import CompilationError
from beancount.query.query_execute import execute_query
from beancount.query.query_parser import ParseError
from beancount.query.query_parser import RunCustom
from beancount.query.shell import BQLShell # type: ignore
from beancount.utils import pager # type: ignore
from fava.core.module_base import FavaModule
from fava.helpers import BeancountError
from fava.helpers import FavaAPIException
from fava.util.excel import HAVE_EXCEL
from fava.util.excel import to_csv
from fava.util.excel import to_excel
if TYPE_CHECKING:
from fava.core import FavaLedger
# This is to limit the size of the history file. Fava is not using readline at
# all, but Beancount somehow still is...
try:
import readline
readline.set_history_length(1000)
except ImportError:
pass
class QueryShell(BQLShell, FavaModule):
"""A light wrapper around Beancount's shell."""
# pylint: disable=too-many-instance-attributes
def __init__(self, ledger: "FavaLedger"):
self.buffer = io.StringIO()
BQLShell.__init__(self, True, None, self.buffer)
FavaModule.__init__(self, ledger)
self.result = None
self.stdout = self.buffer
self.entries: Entries = []
self.errors: List[BeancountError] = []
self.options_map = OPTIONS_DEFAULTS
self.queries: List[Query] = []
def load_file(self) -> None:
self.queries = self.ledger.all_entries_by_type.Query
def add_help(self) -> None:
"Attach help functions for each of the parsed token handlers."
for attrname, func in BQLShell.__dict__.items():
if attrname[:3] != "on_":
continue
command_name = attrname[3:]
setattr(
self.__class__,
f"help_{command_name.lower()}",
lambda _, fun=func: print(
textwrap.dedent(fun.__doc__).strip(), file=self.outfile
),
)
def _loadfun(self) -> None:
self.entries = self.ledger.entries
self.errors = self.ledger.errors
self.options_map = self.ledger.options
def get_pager(self):
"""No real pager, just a wrapper that doesn't close self.buffer."""
return pager.flush_only(self.buffer)
def noop(self, _) -> None:
"""Doesn't do anything in Fava's query shell."""
print(self.noop.__doc__, file=self.outfile)
on_Reload = noop
do_exit = noop
do_quit = noop
do_EOF = noop
def on_Select(self, statement):
# pylint: disable=invalid-name
try:
c_query = query_compile.compile(
statement,
self.env_targets,
self.env_postings,
self.env_entries,
)
except CompilationError as exc:
print(f"ERROR: {str(exc).rstrip('.')}.", file=self.outfile)
return
rtypes, rrows = execute_query(c_query, self.entries, self.options_map)
if not rrows:
print("(empty)", file=self.outfile)
self.result = rtypes, rrows
def execute_query(self, query: str):
"""Run a query.
Arguments:
query: A query string.
Returns:
A tuple (contents, types, rows) where either the first or the last
two entries are None. If the query result is a table, it will be
contained in ``types`` and ``rows``, otherwise the result will be
contained in ``contents`` (as a string).
"""
self._loadfun()
with contextlib.redirect_stdout(self.buffer):
self.onecmd(query)
contents = self.buffer.getvalue()
self.buffer.truncate(0)
if self.result is None:
return (contents.strip().strip("\x00"), None, None)
types, rows = self.result
self.result = None
return (None, types, rows)
def on_RunCustom(self, run_stmt):
"""Run a custom query."""
name = run_stmt.query_name
if name is None:
# List the available queries.
for query in self.queries:
print(query.name)
else:
try:
query = next(
query for query in self.queries if query.name == name
)
except StopIteration:
print(f"ERROR: Query '{name}' not found")
else:
statement = self.parser.parse(query.query_string)
self.dispatch(statement)
def query_to_file(self, query_string: str, result_format: str):
"""Get query result as file.
Arguments:
query_string: A string, the query to run.
result_format: The file format to save to.
Returns:
A tuple (name, data), where name is either 'query_result' or the
name of a custom query if the query string is 'run name_of_query'.
``data`` contains the file contents.
Raises:
FavaAPIException: If the result format is not supported or the
query failed.
"""
name = "query_result"
try:
statement = self.parser.parse(query_string)
except ParseError as exception:
raise FavaAPIException(str(exception)) from exception
if isinstance(statement, RunCustom):
name = statement.query_name
try:
query = next(
query for query in self.queries if query.name == name
)
except StopIteration as exc:
raise FavaAPIException(f'Query "{name}" not found.') from exc
query_string = query.query_string
try:
types, rows = run_query(
self.ledger.entries,
self.ledger.options,
query_string,
numberify=True,
)
except (CompilationError, ParseError) as exception:
raise FavaAPIException(str(exception)) from exception
if result_format == "csv":
data = to_csv(types, rows)
else:
if not HAVE_EXCEL:
raise FavaAPIException("Result format not supported.")
data = to_excel(types, rows, result_format, query_string)
return name, data
QueryShell.on_Select.__doc__ = BQLShell.on_Select.__doc__
| {
"content_hash": "5c38fac813bb9d32986f60b3f4a1b737",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 78,
"avg_line_length": 33.204878048780486,
"alnum_prop": 0.5939474070809461,
"repo_name": "aumayr/beancount-web",
"id": "13bf7c41808ddc18ee652dbcb6a7ee952eeb8abf",
"size": "6807",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/fava/core/query_shell.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39188"
},
{
"name": "HTML",
"bytes": "80920"
},
{
"name": "JavaScript",
"bytes": "47779"
},
{
"name": "Makefile",
"bytes": "503"
},
{
"name": "Python",
"bytes": "67587"
},
{
"name": "Shell",
"bytes": "1189"
}
],
"symlink_target": ""
} |
import testtools
from tempest.api.compute import base
from tempest import config
from tempest.lib import decorators
from tempest import test
CONF = config.CONF
class ServersOnMultiNodesTest(base.BaseV2ComputeAdminTest):
@classmethod
def resource_setup(cls):
super(ServersOnMultiNodesTest, cls).resource_setup()
cls.server01 = cls.create_test_server(wait_until='ACTIVE')['id']
cls.host01 = cls._get_host(cls.server01)
@classmethod
def skip_checks(cls):
super(ServersOnMultiNodesTest, cls).skip_checks()
if CONF.compute.min_compute_nodes < 2:
raise cls.skipException(
"Less than 2 compute nodes, skipping multi-nodes test.")
@classmethod
def _get_host(cls, server_id):
return cls.os_admin.servers_client.show_server(
server_id)['server']['OS-EXT-SRV-ATTR:host']
@decorators.idempotent_id('26a9d5df-6890-45f2-abc4-a659290cb130')
@testtools.skipUnless(
test.is_scheduler_filter_enabled("SameHostFilter"),
'SameHostFilter is not available.')
def test_create_servers_on_same_host(self):
hints = {'same_host': self.server01}
server02 = self.create_test_server(scheduler_hints=hints,
wait_until='ACTIVE')['id']
host02 = self._get_host(server02)
self.assertEqual(self.host01, host02)
@decorators.idempotent_id('cc7ca884-6e3e-42a3-a92f-c522fcf25e8e')
@testtools.skipUnless(
test.is_scheduler_filter_enabled("DifferentHostFilter"),
'DifferentHostFilter is not available.')
def test_create_servers_on_different_hosts(self):
hints = {'different_host': self.server01}
server02 = self.create_test_server(scheduler_hints=hints,
wait_until='ACTIVE')['id']
host02 = self._get_host(server02)
self.assertNotEqual(self.host01, host02)
@decorators.idempotent_id('7869cc84-d661-4e14-9f00-c18cdc89cf57')
@testtools.skipUnless(
test.is_scheduler_filter_enabled("DifferentHostFilter"),
'DifferentHostFilter is not available.')
def test_create_servers_on_different_hosts_with_list_of_servers(self):
# This scheduler-hint supports list of servers also.
hints = {'different_host': [self.server01]}
server02 = self.create_test_server(scheduler_hints=hints,
wait_until='ACTIVE')['id']
host02 = self._get_host(server02)
self.assertNotEqual(self.host01, host02)
| {
"content_hash": "b9db502e25d48da9dc64d5ca9a8ab6db",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 74,
"avg_line_length": 40.140625,
"alnum_prop": 0.6516154145581938,
"repo_name": "vedujoshi/tempest",
"id": "858998af987f3b30593a800d23ef02554c592f3b",
"size": "3200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tempest/api/compute/admin/test_servers_on_multinodes.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "4036844"
},
{
"name": "Shell",
"bytes": "11449"
}
],
"symlink_target": ""
} |
from django.test import TestCase
from backend.models import Concert
from backend.tests.helpers import login, create_user, create_festival, create_concert
from backend.tests.helpers import create_client
class UpdateConcertInfoTests(TestCase):
def test_no_client_name_provided(self):
"""
update_concert_info() is to return "Client name not provided"
if no client name is provided
"""
login(self.client)
response = self.client.post('/backend/u/conc/', {'id': 3})
self.assertEqual(response.status_code, 200)
self.assertEqual('Client name not provided', response.content.decode('utf-8'))
def test_no_permissions(self):
"""
update_concert_info() should return "Permission not granted"
if the permissions necessary are not granted
"""
login(self.client)
client = create_client('test')
client.write_access = False
client.save()
response = self.client.post('/backend/u/conc/', {'client': 'test', 'id': 3})
self.assertEqual(response.status_code, 200)
self.assertEqual('Permission not granted', response.content.decode('utf-8'))
def test_not_owner(self):
"""
update_concert_info() should return "Permission not granted"
if the current user is different from the owner of the festival hosting the concert
"""
creating_user = create_user()
creating_user.save()
festival = create_festival('test', creating_user)
festival.save()
concert = create_concert(festival, 'test')
concert.save()
login(self.client)
client = create_client('test')
client.delete_access = True
client.save()
response = self.client.post('/backend/u/conc/', {'client': 'test', 'id': concert.pk})
self.assertEqual(response.status_code, 200)
self.assertEqual('Permission not granted', response.content.decode('utf-8'))
def test_no_matching_concerts(self):
"""
update_concert_info() is to return "Concert not found" if concert is not found
No concerts are to be updated
"""
user = login(self.client)
client = create_client('test')
client.write_access = True
client.save()
festival = create_festival('test', user)
festival.save()
concert1 = create_concert(festival, 'test')
concert1.save()
concert2 = create_concert(festival, 'testest')
concert2.save()
concert3 = create_concert(festival, 'testestest')
concert3.save()
response = self.client.post('/backend/u/conc/', {'client': 'test', 'id': -1})
self.assertEqual('Concert Not Found', response.content.decode('utf-8'))
def test_invalid_fields(self):
"""
update_concert_info() is to return "Incorrect input" if fields are input with wrong data
"""
user = login(self.client)
client = create_client('test')
client.write_access = True
client.save()
festival = create_festival('test', user)
festival.save()
concert = create_concert(festival, 'test')
concert.save()
response = self.client.post('/backend/u/conc/',
{'client': 'test',
'id': concert.pk,
'artist':
'testtestsetsetsetsetse\
tsetsetsetsetsetsetsetsetsetsetsetsetsetsetsetsetsetsetsetstsetsetsetset\
testsetsetsetestestsetsetsetstsetsetsetsetsetsetsetsetsetsetsetsetsetstset\
testetsetsetsettestsetsetsetsetsetsetsetsetsetsetsetsetsetsetsetsetsetsett'})
self.assertEqual(response.status_code, 200)
self.assertEqual('Incorrect input', response.content.decode('utf-8'))
self.assertEqual(1, Concert.objects.filter(festival=festival, artist='test').count())
def test_correct_input(self):
"""
update_festival_info() is to return a list of the modified fields
Festival is to be modified
"""
user = login(self.client)
client = create_client('test')
client.write_access = True
client.save()
festival = create_festival('test', user)
festival.save()
concert = create_concert(festival, 'test')
concert.save()
response = self.client.post('/backend/u/conc/',
{'client': 'test',
'id': concert.pk,
'stage': 2,
'artist': 'tset'
})
self.assertEqual(response.status_code, 200)
response_string = response.content.decode('utf-8')
self.assertTrue('artist:tset' in response_string)
self.assertTrue('stage:2' in response_string)
self.assertEqual(3, len(response_string.split('\n')))
self.assertEqual(1, Concert.objects.filter(festival=festival, artist='tset').count())
| {
"content_hash": "bf9a5f7a4b6892f0cc4a1a98c2c7e005",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 118,
"avg_line_length": 38.043795620437955,
"alnum_prop": 0.5823100537221796,
"repo_name": "amentis/FestPal-Server",
"id": "619d5376d61d15c6279a1a37b851148ba575d7dc",
"size": "5212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/tests/test_update_concert_info.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "290"
},
{
"name": "Python",
"bytes": "99612"
}
],
"symlink_target": ""
} |
from challenges.challenge import Challenge
from challenges.conf import Conf
from challenges.scaffold import Scaffold
from challenges.runner import Runner
from challenges.main import main
| {
"content_hash": "0a57e0cad7ccb524bd6e2dcdbf382bf8",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 42,
"avg_line_length": 31.333333333333332,
"alnum_prop": 0.8617021276595744,
"repo_name": "elmar-hinz/Python.Challenges",
"id": "0b37234a74f1aee8e5fc68ab2a365a434912030f",
"size": "188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "challenges/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "64"
},
{
"name": "Python",
"bytes": "57476"
}
],
"symlink_target": ""
} |
import json
from typing import Optional
import zipcodes
from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.exceptions import InvalidExpectationConfigurationError
from great_expectations.execution_engine import (
PandasExecutionEngine,
SparkDFExecutionEngine,
SqlAlchemyExecutionEngine,
)
from great_expectations.expectations.expectation import ColumnMapExpectation
from great_expectations.expectations.metrics import (
ColumnMapMetricProvider,
column_condition_partial,
)
def is_valid_pennsylvania_zip(zip: str):
list_of_dicts_of_pennsylvania_zips = zipcodes.filter_by(state="PA")
list_of_pennsylvania_zips = [
d["zip_code"] for d in list_of_dicts_of_pennsylvania_zips
]
if len(zip) > 10:
return False
elif type(zip) != str:
return False
elif zip in list_of_pennsylvania_zips:
return True
else:
return False
# This class defines a Metric to support your Expectation.
# For most ColumnMapExpectations, the main business logic for calculation will live in this class.
class ColumnValuesToBeValidPennsylvaniaZip(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_pennsylvania_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: is_valid_pennsylvania_zip(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
class ExpectColumnValuesToBeValidPennsylvaniaZip(ColumnMapExpectation):
"""Expect values in this column to be valid Pennsylvania zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"valid_pennsylvania_zip": ["17340", "18045", "18447", "19606"],
"invalid_pennsylvania_zip": ["-10000", "1234", "99999", "25487"],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "valid_pennsylvania_zip"},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "invalid_pennsylvania_zip"},
"out": {"success": False},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.valid_pennsylvania_zip"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = ("mostly",)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {}
def validate_configuration(
self, configuration: Optional[ExpectationConfiguration]
) -> None:
"""
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
None. Raises InvalidExpectationConfigurationError if the config is not validated successfully
"""
super().validate_configuration(configuration)
if configuration is None:
configuration = self.configuration
# # Check other things in configuration.kwargs and raise Exceptions if needed
# try:
# assert (
# ...
# ), "message"
# assert (
# ...
# ), "message"
# except AssertionError as e:
# raise InvalidExpectationConfigurationError(str(e))
# This object contains metadata for display in the public Gallery
library_metadata = {
"maturity": "experimental", # "experimental", "beta", or "production"
"tags": [
"hackathon",
"typed-entities",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@luismdiaz01",
"@derekma73", # Don't forget to add your github handle here!
],
"requirements": ["zipcodes"],
}
if __name__ == "__main__":
ExpectColumnValuesToBeValidPennsylvaniaZip().print_diagnostic_checklist()
| {
"content_hash": "1e9eb6b0d13e5241aa1feb507ee1712a",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 115,
"avg_line_length": 39.76027397260274,
"alnum_prop": 0.6296296296296297,
"repo_name": "great-expectations/great_expectations",
"id": "607c18645a76d3d60f23dc362b4024ee6c7326b4",
"size": "5805",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_pennsylvania_zip.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "23771"
},
{
"name": "Dockerfile",
"bytes": "2388"
},
{
"name": "HTML",
"bytes": "27311"
},
{
"name": "JavaScript",
"bytes": "45960"
},
{
"name": "Jinja",
"bytes": "66650"
},
{
"name": "Jupyter Notebook",
"bytes": "816323"
},
{
"name": "Lua",
"bytes": "3489"
},
{
"name": "Makefile",
"bytes": "657"
},
{
"name": "Python",
"bytes": "15728777"
},
{
"name": "Shell",
"bytes": "2930"
}
],
"symlink_target": ""
} |
from __future__ import division
from sklearn.neighbors import NearestNeighbors
import numpy as np
from sets import Set
import os
import os.path
import bson
import sys
import csv
import json
import math
import string
import random
import names
import operator
from collections import defaultdict
from scipy.sparse import csc_matrix
users_interests = []
users_songs = []
index_song_map = {}
user_index_map = {}
userid_index_map = {}
ommited_songs = {}
def findTriple(userHex, songHex, triples):
for i, triple in enumerate(triples):
if triple['user'] == userHex and triple['song'] == songHex:
return i
toHex = lambda x:"".join([hex(ord(c))[2:].zfill(2) for c in x])
def getUserInterestMatrix():
#XminmaxNorm = (X - min(X))/(max(X)-min(X))
songIds = []
userId = ""
newSongs = []
topUsers2_path = 'data/topUsers100/'
song_set = Set([])
users_info = []
songs = []
users = []
triples = []
#users_interests = [Set([])]
song_index_map = {}
# unique_songs = Set([])
for filename in os.listdir(topUsers2_path):
realPath = topUsers2_path + filename
with open(realPath, 'rb') as csvfile:
# each file is a user
csvreader = csv.reader(csvfile, delimiter=',')
user_heard = Set([])
songid_hex_map = {}
userHex = ''
songHex = ''
tripleHex = ''
for i, row in enumerate(csvreader):
if i != 0:
if i == 1:
userHex = ''.join([random.choice(string.hexdigits + string.digits) for n in xrange(24)])
users.append({'_id': userHex, 'username': names.get_first_name(), 'idString': userId, 'password': 'brown123', 'provider': 'local'})
userId = row[0]
songId = row[1]
songPlayCount = int(row[2])
songTitle = row[4]
songAuthor = row[9]
if songId in song_index_map:
# Triple already exists, just add to it.
if songId in user_heard:
currSongHex = songid_hex_map[songId]
currTriple = findTriple(userHex, songHex, triples)
oldCount = triples[currTriple].count
#triples[currTriple] = {user: userHex, song: songHex, count: (songPlayCount+oldCount)}
print "No debe llegar aqui nunca!!!!"
exit(1)
else:
songHex = ''.join([random.choice(string.hexdigits + string.digits) for n in xrange(24)])
songs.append({'_id': songHex, 'idString': songId, 'author': songAuthor, 'title': songTitle})
tripleHex = ''.join([random.choice(string.hexdigits + string.digits) for n in xrange(24)])
triples.append({'user': userHex, 'song': songHex, 'songTitle': songTitle, 'count': songPlayCount})
song_index_map[songId] = songHex
user_heard.add(songId)
songfile = open('Song.json', 'w')
json.dump([{'model': 'Song', 'documents': songs}], songfile);
songfile.close();
userfile = open('User.json', 'w')
json.dump([{'model': 'User', 'documents': users}], userfile);
userfile.close();
triplefile = open('Triple.json', 'w')
json.dump([{'model': 'Triple', 'documents': triples}], triplefile);
triplefile.close();
def main():
print "generating json"
getUserInterestMatrix()
print "done"
if __name__ == '__main__':
main()
| {
"content_hash": "fea27e629d4b460f97770d7d05df084e",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 155,
"avg_line_length": 30.58267716535433,
"alnum_prop": 0.5131307929969104,
"repo_name": "valentin7/shazam-datascience",
"id": "1fae28dc289f520e055d3cd97e7bfa9365f66c9a",
"size": "3884",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "generate_json_from_users100.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1141"
},
{
"name": "HTML",
"bytes": "1160"
},
{
"name": "JavaScript",
"bytes": "7510"
},
{
"name": "Python",
"bytes": "19210"
}
],
"symlink_target": ""
} |
from flask import Flask
import base64
from flask_jwt import JWT
app = Flask(__name__)
app.config.from_object('metaflask.config')
app.url_map.strict_slashes = False
jwt = JWT(app)
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
return response
import metaflask.userapi, metaflask.views
#import metaflask.msfapi | {
"content_hash": "d9f896fbd74ea2d26c3f2b49dfa93efc",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 60,
"avg_line_length": 22.294117647058822,
"alnum_prop": 0.7546174142480211,
"repo_name": "harmon25/metaflask",
"id": "30aa0243e1f2d4d43165bdd95060dae000fa77c9",
"size": "426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metaflask/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2188"
},
{
"name": "HTML",
"bytes": "6264"
},
{
"name": "JavaScript",
"bytes": "4978"
},
{
"name": "Python",
"bytes": "13233"
}
],
"symlink_target": ""
} |
from django.test import TestCase
from .. import forms, managers, models
class ManagerTest(TestCase):
manager = managers.FormManager
fixtures = [
'wizard_builder_data',
]
def _change_form_text(self, form):
question = models.FormQuestion.objects.filter(pk=form['id'])
question.update(text='this text is not persistent')
def _serialize(self, forms):
return [
form.serialized
for form in forms
]
def test_accurate_number_of_forms_present(self):
self.assertEqual(
len(self.manager.get_form_models()),
len(models.Page.objects.wizard_set(1)),
)
def test_returns_page_form(self):
for form in self.manager.get_form_models():
self.assertIsInstance(form, forms.PageForm)
def test_manager_populates_default_data(self):
text = 'kitten ipsum cottoncloud'
data = {'question_2': text}
form = self.manager.get_form_models(answer_data=data)[1]
self.assertEqual(form.cleaned_data, data)
def test_manager_persists_form_data(self):
form_data_before = self.manager.get_serialized_forms()
self._change_form_text(form_data_before[0][0])
form_data_after = self._serialize(
self.manager.get_form_models(form_data=form_data_before),
)
self.assertNotEqual(
'this text is not persistent',
form_data_after[0][0]['question_text'],
)
self.assertEqual(form_data_before, form_data_after)
| {
"content_hash": "48e81b98d2946379e10bd464cb50a5e6",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 69,
"avg_line_length": 32.229166666666664,
"alnum_prop": 0.6192630898513252,
"repo_name": "SexualHealthInnovations/django-wizard-builder",
"id": "6411743d55641437168e31775a07c25998c8d955",
"size": "1547",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wizard_builder/tests/test_managers.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "6885"
},
{
"name": "Makefile",
"bytes": "2525"
},
{
"name": "Python",
"bytes": "99398"
}
],
"symlink_target": ""
} |
"""
Command-line interface to the GBP APIs
"""
from __future__ import print_function
import argparse
import logging
import os
import sys
from keystoneclient.auth.identity import v2 as v2_auth
from keystoneclient.auth.identity import v3 as v3_auth
from keystoneclient import discover
from keystoneclient.openstack.common.apiclient import exceptions as ks_exc
from keystoneclient import session
from oslo.utils import encodeutils
import six.moves.urllib.parse as urlparse
from cliff import app
from cliff import commandmanager
from neutronclient.common import clientmanager
from neutronclient.common import exceptions as exc
from neutronclient.common import utils
from neutronclient.i18n import _
from neutronclient.version import __version__
from gbpclient.gbp.v2_0 import groupbasedpolicy as gbp
from gbpclient.gbp.v2_0 import servicechain
VERSION = '2.0'
NEUTRON_API_VERSION = '2.0'
clientmanager.neutron_client.API_VERSIONS = {
'2.0': 'gbpclient.v2_0.client.Client',
}
def run_command(cmd, cmd_parser, sub_argv):
_argv = sub_argv
index = -1
values_specs = []
if '--' in sub_argv:
index = sub_argv.index('--')
_argv = sub_argv[:index]
values_specs = sub_argv[index:]
known_args, _values_specs = cmd_parser.parse_known_args(_argv)
cmd.values_specs = (index == -1 and _values_specs or values_specs)
return cmd.run(known_args)
def env(*_vars, **kwargs):
"""Search for the first defined of possibly many env vars.
Returns the first environment variable defined in vars, or
returns the default defined in kwargs.
"""
for v in _vars:
value = os.environ.get(v, None)
if value:
return value
return kwargs.get('default', '')
def check_non_negative_int(value):
try:
value = int(value)
except ValueError:
raise argparse.ArgumentTypeError(_("invalid int value: %r") % value)
if value < 0:
raise argparse.ArgumentTypeError(_("input value %d is negative") %
value)
return value
COMMAND_V2 = {
'policy-target-create': gbp.CreatePolicyTarget,
'policy-target-delete': gbp.DeletePolicyTarget,
'policy-target-update': gbp.UpdatePolicyTarget,
'policy-target-list': gbp.ListPolicyTarget,
'policy-target-show': gbp.ShowPolicyTarget,
'policy-target-group-create': gbp.CreatePolicyTargetGroup,
'policy-target-group-delete': gbp.DeletePolicyTargetGroup,
'policy-target-group-update': gbp.UpdatePolicyTargetGroup,
'policy-target-group-list': gbp.ListPolicyTargetGroup,
'policy-target-group-show': gbp.ShowPolicyTargetGroup,
'group-create': gbp.CreatePolicyTargetGroup,
'group-delete': gbp.DeletePolicyTargetGroup,
'group-update': gbp.UpdatePolicyTargetGroup,
'group-list': gbp.ListPolicyTargetGroup,
'group-show': gbp.ShowPolicyTargetGroup,
'l2policy-create': gbp.CreateL2Policy,
'l2policy-delete': gbp.DeleteL2Policy,
'l2policy-update': gbp.UpdateL2Policy,
'l2policy-list': gbp.ListL2Policy,
'l2policy-show': gbp.ShowL2Policy,
'l3policy-create': gbp.CreateL3Policy,
'l3policy-delete': gbp.DeleteL3Policy,
'l3policy-update': gbp.UpdateL3Policy,
'l3policy-list': gbp.ListL3Policy,
'l3policy-show': gbp.ShowL3Policy,
'network-service-policy-create': gbp.CreateNetworkServicePolicy,
'network-service-policy-delete': gbp.DeleteNetworkServicePolicy,
'network-service-policy-update': gbp.UpdateNetworkServicePolicy,
'network-service-policy-list': gbp.ListNetworkServicePolicy,
'network-service-policy-show': gbp.ShowNetworkServicePolicy,
'external-policy-create': gbp.CreateExternalPolicy,
'external-policy-delete': gbp.DeleteExternalPolicy,
'external-policy-update': gbp.UpdateExternalPolicy,
'external-policy-list': gbp.ListExternalPolicy,
'external-policy-show': gbp.ShowExternalPolicy,
'external-segment-create': gbp.CreateExternalSegment,
'external-segment-delete': gbp.DeleteExternalSegment,
'external-segment-update': gbp.UpdateExternalSegment,
'external-segment-list': gbp.ListExternalSegment,
'external-segment-show': gbp.ShowExternalSegment,
'nat-pool-create': gbp.CreateNatPool,
'nat-pool-delete': gbp.DeleteNatPool,
'nat-pool-update': gbp.UpdateNatPool,
'nat-pool-list': gbp.ListNatPool,
'nat-pool-show': gbp.ShowNatPool,
'policy-classifier-create': gbp.CreatePolicyClassifier,
'policy-classifier-delete': gbp.DeletePolicyClassifier,
'policy-classifier-update': gbp.UpdatePolicyClassifier,
'policy-classifier-list': gbp.ListPolicyClassifier,
'policy-classifier-show': gbp.ShowPolicyClassifier,
'policy-action-create': gbp.CreatePolicyAction,
'policy-action-delete': gbp.DeletePolicyAction,
'policy-action-update': gbp.UpdatePolicyAction,
'policy-action-list': gbp.ListPolicyAction,
'policy-action-show': gbp.ShowPolicyAction,
'policy-rule-create': gbp.CreatePolicyRule,
'policy-rule-delete': gbp.DeletePolicyRule,
'policy-rule-update': gbp.UpdatePolicyRule,
'policy-rule-list': gbp.ListPolicyRule,
'policy-rule-show': gbp.ShowPolicyRule,
'policy-rule-set-create': gbp.CreatePolicyRuleSet,
'policy-rule-set-delete': gbp.DeletePolicyRuleSet,
'policy-rule-set-update': gbp.UpdatePolicyRuleSet,
'policy-rule-set-list': gbp.ListPolicyRuleSet,
'policy-rule-set-show': gbp.ShowPolicyRuleSet,
'service-profile-list': servicechain.ListServiceProfile,
'service-profile-show': servicechain.ShowServiceProfile,
'service-profile-create': servicechain.CreateServiceProfile,
'service-profile-delete': servicechain.DeleteServiceProfile,
'service-profile-update': servicechain.UpdateServiceProfile,
'servicechain-node-list': servicechain.ListServiceChainNode,
'servicechain-node-show': servicechain.ShowServiceChainNode,
'servicechain-node-create': servicechain.CreateServiceChainNode,
'servicechain-node-delete': servicechain.DeleteServiceChainNode,
'servicechain-node-update': servicechain.UpdateServiceChainNode,
'servicechain-spec-list': servicechain.ListServiceChainSpec,
'servicechain-spec-show': servicechain.ShowServiceChainSpec,
'servicechain-spec-create': servicechain.CreateServiceChainSpec,
'servicechain-spec-delete': servicechain.DeleteServiceChainSpec,
'servicechain-spec-update': servicechain.UpdateServiceChainSpec,
'servicechain-instance-list': (
servicechain.ListServiceChainInstance
),
'servicechain-instance-show': (
servicechain.ShowServiceChainInstance
),
'servicechain-instance-create': (
servicechain.CreateServiceChainInstance
),
'servicechain-instance-delete': (
servicechain.DeleteServiceChainInstance
),
'servicechain-instance-update': (
servicechain.UpdateServiceChainInstance
),
}
COMMANDS = {'2.0': COMMAND_V2}
class HelpAction(argparse.Action):
"""Provide a custom action so the -h and --help options
to the main app will print a list of the commands.
The commands are determined by checking the CommandManager
instance, passed in as the "default" value for the action.
"""
def __call__(self, parser, namespace, values, option_string=None):
outputs = []
max_len = 0
app = self.default
parser.print_help(app.stdout)
app.api_version = '2.0' # Check this
app.stdout.write(_('\nCommands for GBP API v%s:\n') % app.api_version)
command_manager = app.command_manager
for name, ep in sorted(command_manager):
factory = ep.load()
cmd = factory(self, None)
one_liner = cmd.get_description().split('\n')[0]
outputs.append((name, one_liner))
max_len = max(len(name), max_len)
for (name, one_liner) in outputs:
app.stdout.write(' %s %s\n' % (name.ljust(max_len), one_liner))
sys.exit(0)
class GBPShell(app.App):
# verbose logging levels
WARNING_LEVEL = 0
INFO_LEVEL = 1
DEBUG_LEVEL = 2
CONSOLE_MESSAGE_FORMAT = '%(message)s'
DEBUG_MESSAGE_FORMAT = '%(levelname)s: %(name)s %(message)s'
log = logging.getLogger(__name__)
def __init__(self, apiversion):
super(GBPShell, self).__init__(
description=__doc__.strip(),
version=VERSION,
command_manager=commandmanager.CommandManager('gbp.cli'), )
self.commands = COMMANDS
for k, v in self.commands[apiversion].items():
self.command_manager.add_command(k, v)
# This is instantiated in initialize_app() only when using
# password flow auth
self.auth_client = None
self.api_version = apiversion
def build_option_parser(self, description, version):
"""Return an argparse option parser for this application.
Subclasses may override this method to extend
the parser with more global options.
:param description: full description of the application
:paramtype description: str
:param version: version number for the application
:paramtype version: str
"""
parser = argparse.ArgumentParser(
description=description,
add_help=False, )
parser.add_argument(
'--version',
action='version',
version=__version__, )
parser.add_argument(
'-v', '--verbose', '--debug',
action='count',
dest='verbose_level',
default=self.DEFAULT_VERBOSE_LEVEL,
help=_('Increase verbosity of output and show tracebacks on'
' errors. You can repeat this option.'))
parser.add_argument(
'-q', '--quiet',
action='store_const',
dest='verbose_level',
const=0,
help=_('Suppress output except warnings and errors.'))
parser.add_argument(
'-h', '--help',
action=HelpAction,
nargs=0,
default=self, # tricky
help=_("Show this help message and exit."))
parser.add_argument(
'-r', '--retries',
metavar="NUM",
type=check_non_negative_int,
default=0,
help=_("How many times the request to the Neutron server should "
"be retried if it fails."))
# FIXME(bklei): this method should come from python-keystoneclient
self._append_global_identity_args(parser)
return parser
def _append_global_identity_args(self, parser):
# FIXME(bklei): these are global identity (Keystone) arguments which
# should be consistent and shared by all service clients. Therefore,
# they should be provided by python-keystoneclient. We will need to
# refactor this code once this functionality is available in
# python-keystoneclient.
#
# Note: At that time we'll need to decide if we can just abandon
# the deprecated args (--service-type and --endpoint-type).
parser.add_argument(
'--os-service-type', metavar='<os-service-type>',
default=env('OS_NETWORK_SERVICE_TYPE', default='network'),
help=_('Defaults to env[OS_NETWORK_SERVICE_TYPE] or network.'))
parser.add_argument(
'--os-endpoint-type', metavar='<os-endpoint-type>',
default=env('OS_ENDPOINT_TYPE', default='publicURL'),
help=_('Defaults to env[OS_ENDPOINT_TYPE] or publicURL.'))
# FIXME(bklei): --service-type is deprecated but kept in for
# backward compatibility.
parser.add_argument(
'--service-type', metavar='<service-type>',
default=env('OS_NETWORK_SERVICE_TYPE', default='network'),
help=_('DEPRECATED! Use --os-service-type.'))
# FIXME(bklei): --endpoint-type is deprecated but kept in for
# backward compatibility.
parser.add_argument(
'--endpoint-type', metavar='<endpoint-type>',
default=env('OS_ENDPOINT_TYPE', default='publicURL'),
help=_('DEPRECATED! Use --os-endpoint-type.'))
parser.add_argument(
'--os-auth-strategy', metavar='<auth-strategy>',
default=env('OS_AUTH_STRATEGY', default='keystone'),
help=_('DEPRECATED! Only keystone is supported.'))
parser.add_argument(
'--os_auth_strategy',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-auth-url', metavar='<auth-url>',
default=env('OS_AUTH_URL'),
help=_('Authentication URL, defaults to env[OS_AUTH_URL].'))
parser.add_argument(
'--os_auth_url',
help=argparse.SUPPRESS)
project_name_group = parser.add_mutually_exclusive_group()
project_name_group.add_argument(
'--os-tenant-name', metavar='<auth-tenant-name>',
default=env('OS_TENANT_NAME'),
help=_('Authentication tenant name, defaults to '
'env[OS_TENANT_NAME].'))
project_name_group.add_argument(
'--os-project-name',
metavar='<auth-project-name>',
default=utils.env('OS_PROJECT_NAME'),
help='Another way to specify tenant name. '
'This option is mutually exclusive with '
' --os-tenant-name. '
'Defaults to env[OS_PROJECT_NAME].')
parser.add_argument(
'--os_tenant_name',
help=argparse.SUPPRESS)
project_id_group = parser.add_mutually_exclusive_group()
project_id_group.add_argument(
'--os-tenant-id', metavar='<auth-tenant-id>',
default=env('OS_TENANT_ID'),
help=_('Authentication tenant ID, defaults to '
'env[OS_TENANT_ID].'))
project_id_group.add_argument(
'--os-project-id',
metavar='<auth-project-id>',
default=utils.env('OS_PROJECT_ID'),
help='Another way to specify tenant ID. '
'This option is mutually exclusive with '
' --os-tenant-id. '
'Defaults to env[OS_PROJECT_ID].')
parser.add_argument(
'--os-username', metavar='<auth-username>',
default=utils.env('OS_USERNAME'),
help=_('Authentication username, defaults to env[OS_USERNAME].'))
parser.add_argument(
'--os_username',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-user-id', metavar='<auth-user-id>',
default=env('OS_USER_ID'),
help=_('Authentication user ID (Env: OS_USER_ID)'))
parser.add_argument(
'--os_user_id',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-user-domain-id',
metavar='<auth-user-domain-id>',
default=utils.env('OS_USER_DOMAIN_ID'),
help='OpenStack user domain ID. '
'Defaults to env[OS_USER_DOMAIN_ID].')
parser.add_argument(
'--os_user_domain_id',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-user-domain-name',
metavar='<auth-user-domain-name>',
default=utils.env('OS_USER_DOMAIN_NAME'),
help='OpenStack user domain name. '
'Defaults to env[OS_USER_DOMAIN_NAME].')
parser.add_argument(
'--os_user_domain_name',
help=argparse.SUPPRESS)
parser.add_argument(
'--os_project_id',
help=argparse.SUPPRESS)
parser.add_argument(
'--os_project_name',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-project-domain-id',
metavar='<auth-project-domain-id>',
default=utils.env('OS_PROJECT_DOMAIN_ID'),
help='Defaults to env[OS_PROJECT_DOMAIN_ID].')
parser.add_argument(
'--os-project-domain-name',
metavar='<auth-project-domain-name>',
default=utils.env('OS_PROJECT_DOMAIN_NAME'),
help='Defaults to env[OS_PROJECT_DOMAIN_NAME].')
parser.add_argument(
'--os-cert',
metavar='<certificate>',
default=utils.env('OS_CERT'),
help=_("Path of certificate file to use in SSL "
"connection. This file can optionally be "
"prepended with the private key. Defaults "
"to env[OS_CERT]"))
parser.add_argument(
'--os-cacert',
metavar='<ca-certificate>',
default=env('OS_CACERT', default=None),
help=_("Specify a CA bundle file to use in "
"verifying a TLS (https) server certificate. "
"Defaults to env[OS_CACERT]"))
parser.add_argument(
'--os-key',
metavar='<key>',
default=utils.env('OS_KEY'),
help=_("Path of client key to use in SSL "
"connection. This option is not necessary "
"if your key is prepended to your certificate "
"file. Defaults to env[OS_KEY]"))
parser.add_argument(
'--os-password', metavar='<auth-password>',
default=utils.env('OS_PASSWORD'),
help=_('Authentication password, defaults to env[OS_PASSWORD].'))
parser.add_argument(
'--os_password',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-region-name', metavar='<auth-region-name>',
default=env('OS_REGION_NAME'),
help=_('Authentication region name, defaults to '
'env[OS_REGION_NAME].'))
parser.add_argument(
'--os_region_name',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-token', metavar='<token>',
default=env('OS_TOKEN'),
help=_('Authentication token, defaults to env[OS_TOKEN].'))
parser.add_argument(
'--os_token',
help=argparse.SUPPRESS)
parser.add_argument(
'--http-timeout', metavar='<seconds>',
default=env('OS_NETWORK_TIMEOUT', default=None), type=float,
help=_('Timeout in seconds to wait for an HTTP response. Defaults '
'to env[OS_NETWORK_TIMEOUT] or None if not specified.'))
parser.add_argument(
'--os-url', metavar='<url>',
default=env('OS_URL'),
help=_('Defaults to env[OS_URL].'))
parser.add_argument(
'--os_url',
help=argparse.SUPPRESS)
parser.add_argument(
'--insecure',
action='store_true',
default=env('NEUTRONCLIENT_INSECURE', default=False),
help=_("Explicitly allow neutronclient to perform \"insecure\" "
"SSL (https) requests. The server's certificate will "
"not be verified against any certificate authorities. "
"This option should be used with caution."))
def _bash_completion(self):
"""Prints all of the commands and options for bash-completion."""
commands = set()
options = set()
for option, _action in self.parser._option_string_actions.items():
options.add(option)
for command_name, command in self.command_manager:
commands.add(command_name)
cmd_factory = command.load()
cmd = cmd_factory(self, None)
cmd_parser = cmd.get_parser('')
for option, _action in cmd_parser._option_string_actions.items():
options.add(option)
print(' '.join(commands | options))
def run(self, argv):
"""Equivalent to the main program for the application.
:param argv: input arguments and options
:paramtype argv: list of str
"""
try:
index = 0
command_pos = -1
help_pos = -1
help_command_pos = -1
for arg in argv:
if arg == 'bash-completion':
self._bash_completion()
return 0
if arg in self.commands[self.api_version]:
if command_pos == -1:
command_pos = index
elif arg in ('-h', '--help'):
if help_pos == -1:
help_pos = index
elif arg == 'help':
if help_command_pos == -1:
help_command_pos = index
index = index + 1
if command_pos > -1 and help_pos > command_pos:
argv = ['help', argv[command_pos]]
if help_command_pos > -1 and command_pos == -1:
argv[help_command_pos] = '--help'
self.options, remainder = self.parser.parse_known_args(argv)
self.configure_logging()
self.interactive_mode = not remainder
self.initialize_app(remainder)
except Exception as err:
if self.options.verbose_level >= self.DEBUG_LEVEL:
self.log.exception(unicode(err))
raise
else:
self.log.error(unicode(err))
return 1
result = 1
if self.interactive_mode:
_argv = [sys.argv[0]]
sys.argv = _argv
result = self.interact()
else:
result = self.run_subcommand(remainder)
return result
def run_subcommand(self, argv):
subcommand = self.command_manager.find_command(argv)
cmd_factory, cmd_name, sub_argv = subcommand
cmd = cmd_factory(self, self.options)
err = None
result = 1
try:
self.prepare_to_run_command(cmd)
full_name = (cmd_name
if self.interactive_mode
else ' '.join([self.NAME, cmd_name])
)
cmd_parser = cmd.get_parser(full_name)
return run_command(cmd, cmd_parser, sub_argv)
except Exception as err:
if self.options.verbose_level >= self.DEBUG_LEVEL:
self.log.exception(unicode(err))
else:
self.log.error(unicode(err))
try:
self.clean_up(cmd, result, err)
except Exception as err2:
if self.options.verbose_level >= self.DEBUG_LEVEL:
self.log.exception(unicode(err2))
else:
self.log.error(_('Could not clean up: %s'), unicode(err2))
if self.options.verbose_level >= self.DEBUG_LEVEL:
raise
else:
try:
self.clean_up(cmd, result, None)
except Exception as err3:
if self.options.verbose_level >= self.DEBUG_LEVEL:
self.log.exception(unicode(err3))
else:
self.log.error(_('Could not clean up: %s'), unicode(err3))
return result
def authenticate_user(self):
"""Make sure the user has provided all of the authentication
info we need.
"""
if self.options.os_auth_strategy == 'keystone':
if self.options.os_token or self.options.os_url:
# Token flow auth takes priority
if not self.options.os_token:
raise exc.CommandError(
_("You must provide a token via"
" either --os-token or env[OS_TOKEN]"))
if not self.options.os_url:
raise exc.CommandError(
_("You must provide a service URL via"
" either --os-url or env[OS_URL]"))
else:
# Validate password flow auth
project_info = (self.options.os_tenant_name or
self.options.os_tenant_id or
(self.options.os_project_name and
(self.options.project_domain_name or
self.options.project_domain_id)) or
self.options.os_project_id)
if (not self.options.os_username
and not self.options.os_user_id):
raise exc.CommandError(
_("You must provide a username or user ID via"
" --os-username, env[OS_USERNAME] or"
" --os-user_id, env[OS_USER_ID]"))
if not self.options.os_password:
raise exc.CommandError(
_("You must provide a password via"
" either --os-password or env[OS_PASSWORD]"))
if (not project_info):
# tenent is deprecated in Keystone v3. Use the latest
# terminology instead.
raise exc.CommandError(
_("You must provide a project_id or project_name ("
"with project_domain_name or project_domain_id) "
"via "
" --os-project-id (env[OS_PROJECT_ID])"
" --os-project-name (env[OS_PROJECT_NAME]),"
" --os-project-domain-id "
"(env[OS_PROJECT_DOMAIN_ID])"
" --os-project-domain-name "
"(env[OS_PROJECT_DOMAIN_NAME])"))
if not self.options.os_auth_url:
raise exc.CommandError(
_("You must provide an auth url via"
" either --os-auth-url or via env[OS_AUTH_URL]"))
else: # not keystone
if not self.options.os_url:
raise exc.CommandError(
_("You must provide a service URL via"
" either --os-url or env[OS_URL]"))
auth_session = self._get_keystone_session()
self.client_manager = clientmanager.ClientManager(
token=self.options.os_token,
url=self.options.os_url,
auth_url=self.options.os_auth_url,
tenant_name=self.options.os_tenant_name,
tenant_id=self.options.os_tenant_id,
username=self.options.os_username,
user_id=self.options.os_user_id,
password=self.options.os_password,
region_name=self.options.os_region_name,
api_version=self.api_version,
auth_strategy=self.options.os_auth_strategy,
# FIXME (bklei) honor deprecated service_type and
# endpoint type until they are removed
service_type=self.options.os_service_type or
self.options.service_type,
endpoint_type=self.options.os_endpoint_type or self.endpoint_type,
insecure=self.options.insecure,
ca_cert=self.options.os_cacert,
timeout=self.options.http_timeout,
retries=self.options.retries,
raise_errors=False,
session=auth_session,
auth=auth_session.auth,
log_credentials=True)
return
def initialize_app(self, argv):
"""Global app init bits:
* set up API versions
* validate authentication info
"""
super(GBPShell, self).initialize_app(argv)
self.api_version = {'network': self.api_version}
# If the user is not asking for help, make sure they
# have given us auth.
cmd_name = None
if argv:
cmd_info = self.command_manager.find_command(argv)
cmd_factory, cmd_name, sub_argv = cmd_info
if self.interactive_mode or cmd_name != 'help':
self.authenticate_user()
def clean_up(self, cmd, result, err):
self.log.debug('clean_up %s', cmd.__class__.__name__)
if err:
self.log.debug('Got an error: %s', unicode(err))
def configure_logging(self):
"""Create logging handlers for any log output."""
root_logger = logging.getLogger('')
# Set up logging to a file
root_logger.setLevel(logging.DEBUG)
# Send higher-level messages to the console via stderr
console = logging.StreamHandler(self.stderr)
console_level = {self.WARNING_LEVEL: logging.WARNING,
self.INFO_LEVEL: logging.INFO,
self.DEBUG_LEVEL: logging.DEBUG,
}.get(self.options.verbose_level, logging.DEBUG)
console.setLevel(console_level)
if logging.DEBUG == console_level:
formatter = logging.Formatter(self.DEBUG_MESSAGE_FORMAT)
else:
formatter = logging.Formatter(self.CONSOLE_MESSAGE_FORMAT)
logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)
console.setFormatter(formatter)
root_logger.addHandler(console)
return
def get_v2_auth(self, v2_auth_url):
return v2_auth.Password(
v2_auth_url,
username=self.options.os_username,
password=self.options.os_password,
tenant_id=self.options.os_tenant_id,
tenant_name=self.options.os_tenant_name)
def get_v3_auth(self, v3_auth_url):
project_id = self.options.os_project_id or self.options.os_tenant_id
project_name = (self.options.os_project_name or
self.options.os_tenant_name)
return v3_auth.Password(
v3_auth_url,
username=self.options.os_username,
password=self.options.os_password,
user_id=self.options.os_user_id,
user_domain_name=self.options.os_user_domain_name,
user_domain_id=self.options.os_user_domain_id,
project_id=project_id,
project_name=project_name,
project_domain_name=self.options.os_project_domain_name,
project_domain_id=self.options.os_project_domain_id
)
def _discover_auth_versions(self, session, auth_url):
# discover the API versions the server is supporting base on the
# given URL
try:
ks_discover = discover.Discover(session=session, auth_url=auth_url)
return (ks_discover.url_for('2.0'), ks_discover.url_for('3.0'))
except ks_exc.ClientException:
# Identity service may not support discover API version.
# Lets try to figure out the API version from the original URL.
url_parts = urlparse.urlparse(auth_url)
(scheme, netloc, path, params, query, fragment) = url_parts
path = path.lower()
if path.startswith('/v3'):
return (None, auth_url)
elif path.startswith('/v2'):
return (auth_url, None)
else:
# not enough information to determine the auth version
msg = _('Unable to determine the Keystone version '
'to authenticate with using the given '
'auth_url. Identity service may not support API '
'version discovery. Please provide a versioned '
'auth_url instead.')
raise exc.CommandError(msg)
def _get_keystone_session(self):
# first create a Keystone session
cacert = self.options.os_cacert or None
cert = self.options.os_cert or None
key = self.options.os_key or None
insecure = self.options.insecure or False
ks_session = session.Session.construct(dict(cacert=cacert,
cert=cert,
key=key,
insecure=insecure))
# discover the supported keystone versions using the given url
(v2_auth_url, v3_auth_url) = self._discover_auth_versions(
session=ks_session,
auth_url=self.options.os_auth_url)
# Determine which authentication plugin to use. First inspect the
# auth_url to see the supported version. If both v3 and v2 are
# supported, then use the highest version if possible.
user_domain_name = self.options.os_user_domain_name or None
user_domain_id = self.options.os_user_domain_id or None
project_domain_name = self.options.os_project_domain_name or None
project_domain_id = self.options.os_project_domain_id or None
domain_info = (user_domain_name or user_domain_id or
project_domain_name or project_domain_id)
if (v2_auth_url and not domain_info) or not v3_auth_url:
ks_session.auth = self.get_v2_auth(v2_auth_url)
else:
ks_session.auth = self.get_v3_auth(v3_auth_url)
return ks_session
def main(argv=sys.argv[1:]):
try:
return GBPShell(NEUTRON_API_VERSION).run(map(encodeutils.safe_decode,
argv))
except exc.NeutronClientException:
return 1
except Exception as e:
print(unicode(e))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
| {
"content_hash": "b7ffdbd3b9ed7351d0ea74d5dfea731e",
"timestamp": "",
"source": "github",
"line_count": 831,
"max_line_length": 79,
"avg_line_length": 40.312876052948255,
"alnum_prop": 0.5800298507462687,
"repo_name": "tbachman/python-group-based-policy-client",
"id": "ba84f7c3c5d1428614a41a6b7922d5687fa7f244",
"size": "34075",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gbpclient/gbpshell.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "259549"
},
{
"name": "Shell",
"bytes": "8147"
}
],
"symlink_target": ""
} |
from django.conf.urls import url
from . import views, views_admin
urlpatterns = [
# views
# views_admin
url(r'^delete_possible_twitter_handles/(?P<candidate_campaign_we_vote_id>wv[\w]{2}cand[\w]+)/$',
views_admin.delete_possible_twitter_handles_view, name='delete_possible_twitter_handles',),
url(r'^retrieve_possible_twitter_handles/(?P<candidate_campaign_we_vote_id>wv[\w]{2}cand[\w]+)/$',
views_admin.retrieve_possible_twitter_handles_view, name='retrieve_possible_twitter_handles',),
url(r'^bulk_retrieve_possible_twitter_handles/$',
views_admin.bulk_retrieve_possible_twitter_handles_view, name='bulk_retrieve_possible_twitter_handles',),
]
| {
"content_hash": "84561e2c88f364be9b2dfcdbce50ff2f",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 113,
"avg_line_length": 46.2,
"alnum_prop": 0.7070707070707071,
"repo_name": "jainanisha90/WeVoteServer",
"id": "18e1a31300d2a8cc05a3c6d7df54b0bd30d96219",
"size": "815",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "twitter/urls.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3612"
},
{
"name": "HTML",
"bytes": "1003027"
},
{
"name": "Python",
"bytes": "7489854"
},
{
"name": "Shell",
"bytes": "611"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('hs_core', '0004_auto_20150721_1125'),
]
operations = [
migrations.CreateModel(
name='GroupAccess',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('active', models.BooleanField(default=True, help_text=b'whether group is currently active', editable=False)),
('discoverable', models.BooleanField(default=True, help_text=b'whether group description is discoverable by everyone', editable=False)),
('public', models.BooleanField(default=True, help_text=b'whether group members can be listed by everyone', editable=False)),
('shareable', models.BooleanField(default=True, help_text=b'whether group can be shared by non-owners', editable=False)),
('group', models.OneToOneField(related_query_name=b'gaccess', related_name='gaccess', null=True, editable=False, to='auth.Group', help_text=b'group object that this object protects')),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='GroupResourcePrivilege',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('privilege', models.IntegerField(default=3, editable=False, choices=[(1, b'Owner'), (2, b'Change'), (3, b'View')])),
('start', models.DateTimeField(auto_now=True)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='ResourceAccess',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('active', models.BooleanField(default=True, help_text=b'whether resource is currently active')),
('discoverable', models.BooleanField(default=False, help_text=b'whether resource is discoverable by everyone')),
('public', models.BooleanField(default=False, help_text=b'whether resource data can be viewed by everyone')),
('shareable', models.BooleanField(default=True, help_text=b'whether resource can be shared by non-owners')),
('published', models.BooleanField(default=False, help_text=b'whether resource has been published')),
('immutable', models.BooleanField(default=False, help_text=b'whether to prevent all changes to the resource')),
('holding_groups', models.ManyToManyField(help_text=b'groups that hold this resource', related_name='group2resource', editable=False, through='hs_access_control.GroupResourcePrivilege', to='hs_access_control.GroupAccess')),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='UserAccess',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('active', models.BooleanField(default=True, help_text=b'whether user is currently capable of action', editable=False)),
('admin', models.BooleanField(default=False, help_text=b'whether user is an administrator', editable=False)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='UserGroupPrivilege',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('privilege', models.IntegerField(default=3, editable=False, choices=[(1, b'Owner'), (2, b'Change'), (3, b'View')])),
('start', models.DateTimeField(auto_now=True)),
('grantor', models.ForeignKey(related_name='x2ugp', editable=False, to='hs_access_control.UserAccess', help_text=b'grantor of privilege', null=True)),
('group', models.ForeignKey(related_name='g2ugp', editable=False, to='hs_access_control.GroupAccess', help_text=b'group to which privilege applies', null=True)),
('user', models.ForeignKey(related_name='u2ugp', editable=False, to='hs_access_control.UserAccess', help_text=b'user to be granted privilege', null=True)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='UserResourcePrivilege',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('privilege', models.IntegerField(default=3, editable=False, choices=[(1, b'Owner'), (2, b'Change'), (3, b'View')])),
('start', models.DateTimeField(auto_now=True)),
('grantor', models.ForeignKey(related_name='x2urp', editable=False, to='hs_access_control.UserAccess', help_text=b'grantor of privilege', null=True)),
('resource', models.ForeignKey(related_name='r2urp', editable=False, to='hs_access_control.ResourceAccess', help_text=b'resource to which privilege applies', null=True)),
('user', models.ForeignKey(related_name='u2urp', editable=False, to='hs_access_control.UserAccess', help_text=b'user to be granted privilege', null=True)),
],
options={
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='userresourceprivilege',
unique_together=set([('user', 'resource', 'grantor')]),
),
migrations.AlterUniqueTogether(
name='usergroupprivilege',
unique_together=set([('user', 'group', 'grantor')]),
),
migrations.AddField(
model_name='useraccess',
name='held_groups',
field=models.ManyToManyField(help_text=b'groups held by this user', related_name='group2user', editable=False, through='hs_access_control.UserGroupPrivilege', to='hs_access_control.GroupAccess'),
preserve_default=True,
),
migrations.AddField(
model_name='useraccess',
name='held_resources',
field=models.ManyToManyField(help_text=b'resources held by this user', related_name='resource2user', editable=False, through='hs_access_control.UserResourcePrivilege', to='hs_access_control.ResourceAccess'),
preserve_default=True,
),
migrations.AddField(
model_name='useraccess',
name='user',
field=models.OneToOneField(related_query_name=b'uaccess', related_name='uaccess', null=True, editable=False, to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
migrations.AddField(
model_name='resourceaccess',
name='holding_users',
field=models.ManyToManyField(help_text=b'users who hold this resource', related_name='user2resource', editable=False, through='hs_access_control.UserResourcePrivilege', to='hs_access_control.UserAccess'),
preserve_default=True,
),
migrations.AddField(
model_name='resourceaccess',
name='resource',
field=models.OneToOneField(related_query_name=b'raccess', related_name='raccess', null=True, editable=False, to='hs_core.BaseResource'),
preserve_default=True,
),
migrations.AddField(
model_name='groupresourceprivilege',
name='grantor',
field=models.ForeignKey(related_name='x2grp', editable=False, to='hs_access_control.UserAccess', help_text=b'grantor of privilege', null=True),
preserve_default=True,
),
migrations.AddField(
model_name='groupresourceprivilege',
name='group',
field=models.ForeignKey(related_name='g2grp', editable=False, to='hs_access_control.GroupAccess', help_text=b'group to be granted privilege', null=True),
preserve_default=True,
),
migrations.AddField(
model_name='groupresourceprivilege',
name='resource',
field=models.ForeignKey(related_name='r2grp', editable=False, to='hs_access_control.ResourceAccess', help_text=b'resource to which privilege applies', null=True),
preserve_default=True,
),
migrations.AlterUniqueTogether(
name='groupresourceprivilege',
unique_together=set([('group', 'resource', 'grantor')]),
),
migrations.AddField(
model_name='groupaccess',
name='held_resources',
field=models.ManyToManyField(help_text=b'resources held by the group', related_name='resource2group', editable=False, through='hs_access_control.GroupResourcePrivilege', to='hs_access_control.ResourceAccess'),
preserve_default=True,
),
migrations.AddField(
model_name='groupaccess',
name='members',
field=models.ManyToManyField(help_text=b'members of the group', related_name='user2group', editable=False, through='hs_access_control.UserGroupPrivilege', to='hs_access_control.UserAccess'),
preserve_default=True,
),
]
| {
"content_hash": "0632f9894f500283dd678cbdf3f0ad32",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 239,
"avg_line_length": 57.31547619047619,
"alnum_prop": 0.615432547512722,
"repo_name": "RENCI/xDCIShare",
"id": "7ab4b90b57d9e1077f286ec41e50d10bbafbc76a",
"size": "9653",
"binary": false,
"copies": "3",
"ref": "refs/heads/xdci-develop",
"path": "hs_access_control/migrations/0001_initial.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "381782"
},
{
"name": "HTML",
"bytes": "964877"
},
{
"name": "JavaScript",
"bytes": "2011819"
},
{
"name": "Python",
"bytes": "4334769"
},
{
"name": "R",
"bytes": "4472"
},
{
"name": "Shell",
"bytes": "52665"
},
{
"name": "XSLT",
"bytes": "790987"
}
],
"symlink_target": ""
} |
"""
NIMH Data Archive Data Structure Client
Example:
nimh_data_archive -d demof01 child_dem01
"""
__author__ = 'Nolan Nichols <https://orcid.org/0000-0003-1099-3328>'
import os
import sys
import json
import logging
import requests
class DataDictionary(object):
"""Creates an object to retrieve NDA data dictionary.
"""
def __init__(self, url):
self.base_url = url
self.datastructures_url = None
self.request = requests.get(self.base_url)
self.json = self.request.json()
self.name = self.json.get('name')
self.version = self.json.get('version')
self.description = self.json.get('description')
self.operations = self.json.get('operations')
self.data_structures = dict()
def get_data_sructures(self):
self.datastructures_url = '{0}/datastructure'.format(self.base_url)
request = requests.get(self.datastructures_url)
data = request.json()
for ds in data:
self.data_structures.update({
ds.get('shortName'): DataStructure(ds, self.base_url)})
class DataStructure(object):
"""Parses a Data Structure and corresponding data elements."""
def __init__(self, data, url):
self.category = data.get('category')
self.data_type = data.get('dataType')
self.ndar_url = data.get('ndarURL')
self.publish_date = data.get('publishDate')
self.short_name = data.get('shortName')
self.source = data.get('source')
self.status = data.get('status')
self.title = data.get('title')
self.json = dict()
self.url = url
self.data = data
self.data_elements = None
def get_data_elements(self):
"""Parses the data elements into a well-structured dictionary."""
ds_url = '{0}/datastructure/{1}'.format(self.url, self.short_name)
request = requests.get(ds_url)
self.json.update(request.json())
result = dict()
for de in self.json.get('dataElements'):
result.update({de.get('name'): DataElement(de)})
self.data_elements = result
class DataElement(object):
"""Parses each data element including semi-structured content embedded as
json strings."""
def __init__(self, data):
self.data = data
self.required = data.get('required')
self.aliases = data.get('aliases')
self.position = data.get('position')
self.name = data.get('name')
self.type = data.get('type')
self.description = data.get('description')
self.title = data.get('title')
if self.data.get('notes'):
self.parse_notes()
if self.data.get('valueRange'):
self.value_range = self.parse_value_range()
def parse_notes(self):
"""Parses the notes field, attempting to clean up coded values by
adding a new "valueset" key to the dictionary."""
notes = self.data.get('notes')
codelist = notes.split(";")
valueset = list()
for codes in codelist:
values = codes.split("=", 1)
if (len(values) > 1) and not (self.data.get('notes') == "null"):
self.data.update({'notes': ""})
if len(values) > 1:
result = dict()
result.update({'code': values[0].strip()})
result.update({'label': values[1].strip()})
valueset.append(result)
else:
self.data.update({'notes': values[0]})
self.data.update({'valueset': valueset})
def parse_value_range(self):
return self.data.get('valueRange')
def main(args=None):
api = 'https://ndar.nih.gov/api/datadictionary/v2'
data_dict = DataDictionary(api)
data_dict.get_data_sructures()
results = []
for i in args.data_structures:
data_structure = data_dict.data_structures.get(i)
data_structure.get_data_elements()
results.append(data_structure.json)
print(json.dumps(data_structure.json))
if __name__ == "__main__":
import argparse
formatter = argparse.RawDescriptionHelpFormatter
default = 'default: %(default)s'
parser = argparse.ArgumentParser(prog="datastructure.py",
description=__doc__,
formatter_class=formatter)
parser.add_argument('-d', '--data-structures',
nargs='*',
help="List of 1 of more data structures to download.")
argv = parser.parse_args()
sys.exit(main(args=argv))
| {
"content_hash": "742d32628a5de3254f1e4b989c02989b",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 78,
"avg_line_length": 34.79545454545455,
"alnum_prop": 0.5878510777269759,
"repo_name": "sibis-platform/nimh_datadict",
"id": "2ea3c4dd3721827cb4ba6756b41c8999d7dc5187",
"size": "4615",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "datadictionary.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "2950"
}
],
"symlink_target": ""
} |
import sys
import logging
import csv
from django.core.management.base import BaseCommand, CommandError
from django.db.utils import IntegrityError
from django.db import transaction
from django.conf import settings
from mpr import models
logger = logging.getLogger(__name__)
class Command(BaseCommand):
args = '<filename>'
help = "Populate database from mediscor"
# https://www.mediscor.co.za/search-medicine-reference-price/
def add_arguments(self, parser):
parser.add_argument('formulary', type=str)
parser.add_argument('filename', type=str)
@transaction.atomic
def handle(self, *args, **options):
params = settings.PRICE_PARAMETERS
VAT = params["VAT"]
formulary_name = options["formulary"]
filename = options["filename"]
formulary, _ = models.Formulary.objects.get_or_create(name=formulary_name)
formulary.save()
models.FormularyProduct.objects.filter(formulary=formulary).delete()
for row in csv.DictReader(open(filename)):
nappi_code = f"{row['Nappi Code']}{row['Nappi Ext']}"
try:
product = models.Product.objects.get(nappi_code=nappi_code)
if product.pack_size is None:
logger.warning(f"Skipping product without a pack size: {nappi_code}")
continue
different_size = float(product.pack_size) != float(row["Pack Size"])
if (different_size):
# print(f"Different: {nappi_code} - {product.pack_size} Data: {row['Pack Size']}")
logger.warning(f"Found product with different pack size - skipping: {nappi_code}")
else:
max_price = float(row["MRP (Excl Vat)"]) * VAT * product.pack_size
models.FormularyProduct.objects.update_or_create(formulary=formulary, product=product, defaults={"price": max_price})
print(nappi_code)
except models.Product.DoesNotExist:
logger.warning(f"Could not find product with NAPPI code: {nappi_code}")
except models.Product.MultipleObjectsReturned:
logger.warning(f"Multiple products with the same NAPPI code: {nappi_code}")
| {
"content_hash": "48493d15cca6d49268a03d4709cf012f",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 137,
"avg_line_length": 42.698113207547166,
"alnum_prop": 0.6301369863013698,
"repo_name": "Code4SA/medicine-price-registry",
"id": "58c5dece5f66d30a2af8ba9528d33860c113c6e8",
"size": "2263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mpr/management/commands/mediscor.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2924"
},
{
"name": "Dockerfile",
"bytes": "1057"
},
{
"name": "HTML",
"bytes": "11939"
},
{
"name": "JavaScript",
"bytes": "42128"
},
{
"name": "Procfile",
"bytes": "48"
},
{
"name": "Python",
"bytes": "93013"
},
{
"name": "Shell",
"bytes": "1951"
}
],
"symlink_target": ""
} |
from oslo_config import cfg
CONF = cfg.CONF
rest_server_ops = [
cfg.StrOpt('bind_host',
default='0.0.0.0',
help='Address to bind the API server to'),
cfg.IntOpt('bind_port',
default=8801,
help='Port the bind the API server to'),
cfg.StrOpt('username',
default='admin',
help='Username for api server'),
cfg.StrOpt('password',
default='admin',
help='Password for api server',
secret=True)
]
keep_alive_ops = [
cfg.IntOpt(
'last_time',
default=0,
help='Last time which controller called API to check probe stat'
)
]
| {
"content_hash": "1d141db92b133bf260f903a26aea26b0",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 72,
"avg_line_length": 24.17241379310345,
"alnum_prop": 0.5249643366619116,
"repo_name": "smartbgp/yabgp",
"id": "5b476d72ceba065a2431a042195104a50f6e9457",
"size": "1336",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "yabgp/api/config.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "290"
},
{
"name": "Python",
"bytes": "663418"
},
{
"name": "Shell",
"bytes": "1741"
}
],
"symlink_target": ""
} |
import datetime
from StringIO import StringIO
try: # pragma: no cover
import Image
except ImportError: # pragma: no cover
from Pillow import Image
import colander
from kotti.views.edit import ContentSchema
from kotti.views.edit import generic_edit
from kotti.views.edit import generic_add
from kotti.views.view import view_node
from kotti.views.util import ensure_view_selector
from kotti.views.util import template_api
from kotti.views.file import AddFileFormView
from kotti.views.file import EditFileFormView
from kotti.views.file import attachment_view
from kotti.views.file import inline_view
from deform.widget import RichTextWidget
from pyramid.i18n import TranslationStringFactory
_ = TranslationStringFactory('kotti_events')
from pyramid.response import Response
from kotti_events.resources import EventFolder
from kotti_events.resources import EventPicture
from kotti_events.resources import Event
from kotti_events.util import get_upcoming_events
from kotti_events.util import get_past_events
class EventFolderSchema(ContentSchema):
pass
class EventSchema(ContentSchema):
place = colander.SchemaNode(colander.String(),
title=_("Place"))
body = colander.SchemaNode(
colander.String(),
widget=RichTextWidget(theme='advanced', width=790, height=500),
missing=u"",
title=_("Body")
)
start_date = colander.SchemaNode(
colander.Date(), title=_("Start date"),
default=datetime.datetime.now())
start_time = colander.SchemaNode(
colander.Time(), title=_("Start time"), missing=None)
end_date = colander.SchemaNode(
colander.Date(), title=_("End date"), missing=None)
end_time = colander.SchemaNode(
colander.Time(), title=_("End time"), missing=None)
@ensure_view_selector
def edit_events(context, request):
return generic_edit(context, request, EventFolderSchema())
def add_events(context, request):
return generic_add(context, request, EventFolderSchema(), EventFolder,
EventFolder.type_info.title)
@ensure_view_selector
def edit_event(context, request):
return generic_edit(context, request, EventSchema())
def add_event(context, request):
return generic_add(context, request, EventSchema(), Event,
Event.type_info.title)
def view_eventfolder(context, request):
return {
'api': template_api(context, request),
'upcoming_events': get_upcoming_events(context),
'past_events': get_past_events(context),
}
class AddEventPictureFormView(AddFileFormView):
item_type = EventPicture.type_info.title
def add(self, **appstruct):
buf = appstruct['file']['fp'].read()
img = Image.open(StringIO(buf))
if img.size[0] > 600 or img.size[1] > 600:
img_format = img.format
img.thumbnail((600, 600), Image.ANTIALIAS)
out = StringIO()
img.save(out, img_format)
out = out.getvalue()
else:
out = buf
return EventPicture(
title=appstruct['title'],
description=appstruct['description'],
data=out,
filename=appstruct['file']['filename'],
mimetype=appstruct['file']['mimetype'],
size=len(buf),
)
class EditEventPictureFormView(EditFileFormView):
pass
def thumbnail_view(context, request, size=(270, 168)):
img = Image.open(StringIO(context.data))
img_format = img.format
wanted_ratio = float(size[0]) / size[1]
img_ratio = float(img.size[0]) / img.size[1]
if wanted_ratio > img_ratio:
new_height = int(img.size[0] / wanted_ratio)
y_offset = int((img.size[1] - new_height) / 2.0)
img = img.crop((0, y_offset, img.size[0], y_offset + new_height))
elif img_ratio > wanted_ratio:
new_width = int(img.size[1] * wanted_ratio)
x_offset = int((img.size[0] - new_width) / 2.0)
img = img.crop((x_offset, 0, x_offset + new_width, img.size[1]))
img.thumbnail(size, Image.ANTIALIAS)
thumbnail = StringIO()
img.save(thumbnail, img_format)
res = Response(
headerlist=[
('Content-Length', str(len(thumbnail.getvalue()))),
('Content-Type', str(context.mimetype)),
],
app_iter=thumbnail.getvalue(),
)
return res
def icon_view(context, request):
return thumbnail_view(context, request, (90, 56))
def includeme_edit(config):
config.add_view(
edit_events,
context=EventFolder,
name='edit',
permission='edit',
renderer='kotti:templates/edit/node.pt',
)
config.add_view(
add_events,
name=EventFolder.type_info.add_view,
permission='add',
renderer='kotti:templates/edit/node.pt',
)
config.add_view(
edit_event,
context=Event,
name='edit',
permission='edit',
renderer='kotti:templates/edit/node.pt',
)
config.add_view(
add_event,
name=Event.type_info.add_view,
permission='add',
renderer='kotti:templates/edit/node.pt',
)
config.add_view(
AddEventPictureFormView,
name=EventPicture.type_info.add_view,
permission='add',
renderer='kotti:templates/edit/node.pt',
)
config.add_view(
EditEventPictureFormView,
context=EventPicture,
name='edit',
permission='edit',
renderer='kotti:templates/edit/node.pt',
)
def includeme_view(config):
config.add_view(
thumbnail_view,
context=EventPicture,
name='thumbnail-view',
permission='view',
)
config.add_view(
icon_view,
context=EventPicture,
name='icon-view',
permission='view',
)
config.add_view(
inline_view,
context=EventPicture,
name='inline-view',
permission='view',
)
config.add_view(
attachment_view,
context=EventPicture,
name='attachment-view',
permission='view',
)
config.add_view(
context=EventPicture,
name='view',
permission='view',
renderer='templates/eventpicture-view.pt',
)
config.add_view(
view_eventfolder,
context=EventFolder,
name='view',
permission='view',
renderer='templates/eventfolder-view.pt',
)
config.add_view(
view_node,
context=Event,
name='view',
permission='view',
renderer='templates/event-view.pt',
)
config.add_static_view('static-kotti_events', 'kotti_events:static')
def includeme(config):
config.add_translation_dirs('kotti_events:locale/')
includeme_edit(config)
includeme_view(config)
| {
"content_hash": "bd7e28983a6fb96d5c285cba0073a649",
"timestamp": "",
"source": "github",
"line_count": 247,
"max_line_length": 74,
"avg_line_length": 27.647773279352226,
"alnum_prop": 0.6282032508419974,
"repo_name": "chrneumann/kotti_events",
"id": "ff81d3022c58e9c0afcd954256a78ba3ecada378",
"size": "6829",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kotti_events/views.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "199951"
}
],
"symlink_target": ""
} |
"""Gluon EventHandlers for Estimators"""
import logging
import os
import time
import warnings
import numpy as np
from ....metric import EvalMetric
from ....metric import Loss as metric_loss
__all__ = ['TrainBegin', 'TrainEnd', 'EpochBegin', 'EpochEnd', 'BatchBegin', 'BatchEnd',
'StoppingHandler', 'MetricHandler', 'ValidationHandler',
'LoggingHandler', 'CheckpointHandler', 'EarlyStoppingHandler']
class TrainBegin(object):
def train_begin(self, estimator, *args, **kwargs):
pass
class TrainEnd(object):
def train_end(self, estimator, *args, **kwargs):
pass
class EpochBegin(object):
def epoch_begin(self, estimator, *args, **kwargs):
pass
class EpochEnd(object):
def epoch_end(self, estimator, *args, **kwargs):
return False
class BatchBegin(object):
def batch_begin(self, estimator, *args, **kwargs):
pass
class BatchEnd(object):
def batch_end(self, estimator, *args, **kwargs):
return False
class StoppingHandler(TrainBegin, BatchEnd, EpochEnd):
"""Stop conditions to stop training
Stop training if maximum number of batches or epochs
reached.
Parameters
----------
max_epoch : int, default None
Number of maximum epochs to train.
max_batch : int, default None
Number of maximum batches to train.
"""
def __init__(self, max_epoch=None, max_batch=None):
self.max_epoch = max_epoch
self.max_batch = max_batch
self.current_batch = 0
self.current_epoch = 0
self.stop_training = False
def train_begin(self, estimator, *args, **kwargs):
self.max_epoch = estimator.max_epoch
self.max_batch = estimator.max_batch
self.current_batch = 0
self.current_epoch = 0
def batch_end(self, estimator, *args, **kwargs):
self.current_batch += 1
if self.current_batch == self.max_batch:
self.stop_training = True
return self.stop_training
def epoch_end(self, estimator, *args, **kwargs):
self.current_epoch += 1
if self.current_epoch == self.max_epoch:
self.stop_training = True
return self.stop_training
class MetricHandler(EpochBegin, BatchEnd):
"""Metric Handler that update metric values at batch end
:py:class:`MetricHandler` takes model predictions and true labels
and update the metrics, it also update metric wrapper for loss with loss values.
Validation loss and metrics will be handled by :py:class:`ValidationHandler`
Parameters
----------
train_metrics : List of EvalMetrics
Training metrics to be updated at batch end.
"""
def __init__(self, train_metrics):
self.train_metrics = train_metrics or []
# order to be called among all callbacks
# metrics need to be calculated before other callbacks can access them
self.priority = -np.Inf
def epoch_begin(self, estimator, *args, **kwargs):
for metric in self.train_metrics:
metric.reset()
def batch_end(self, estimator, *args, **kwargs):
pred = kwargs['pred']
label = kwargs['label']
loss = kwargs['loss']
for metric in self.train_metrics:
if isinstance(metric, metric_loss):
# metric wrapper for loss values
metric.update(0, loss)
else:
metric.update(label, pred)
class ValidationHandler(TrainBegin, BatchEnd, EpochEnd):
"""Validation Handler that evaluate model on validation dataset
:py:class:`ValidationHandler` takes validation dataset, an evaluation function,
metrics to be evaluated, and how often to run the validation. You can provide custom
evaluation function or use the one provided my :py:class:`Estimator`
Parameters
----------
val_data : DataLoader
Validation data set to run evaluation.
eval_fn : function
A function defines how to run evaluation and
calculate loss and metrics.
val_metrics : List of EvalMetrics
Validation metrics to be updated.
epoch_period : int, default 1
How often to run validation at epoch end, by default
:py:class:`ValidationHandler` validate every epoch.
batch_period : int, default None
How often to run validation at batch end, by default
:py:class:`ValidationHandler` does not validate at batch end.
"""
def __init__(self,
val_data,
eval_fn,
val_metrics=None,
epoch_period=1,
batch_period=None):
self.val_data = val_data
self.eval_fn = eval_fn
self.epoch_period = epoch_period
self.batch_period = batch_period
self.val_metrics = val_metrics
self.current_batch = 0
self.current_epoch = 0
# order to be called among all callbacks
# validation metrics need to be calculated before other callbacks can access them
self.priority = -np.Inf
self.logger = logging.getLogger(__name__)
def train_begin(self, estimator, *args, **kwargs):
# reset epoch and batch counter
self.current_batch = 0
self.current_epoch = 0
def batch_end(self, estimator, *args, **kwargs):
self.current_batch += 1
if self.batch_period and self.current_batch % self.batch_period == 0:
self.eval_fn(val_data=self.val_data,
val_metrics=self.val_metrics)
msg = '[Epoch %d] ValidationHandler: %d batches reached, ' \
% (self.current_epoch, self.current_batch)
for monitor in self.val_metrics:
name, value = monitor.get()
msg += '%s: %.4f, ' % (name, value)
self.logger.info(msg.rstrip(','))
def epoch_end(self, estimator, *args, **kwargs):
self.current_epoch += 1
if self.epoch_period and self.current_epoch % self.epoch_period == 0:
self.eval_fn(val_data=self.val_data,
val_metrics=self.val_metrics)
class LoggingHandler(TrainBegin, TrainEnd, EpochBegin, EpochEnd, BatchBegin, BatchEnd):
"""Basic Logging Handler that applies to every Gluon estimator by default.
:py:class:`LoggingHandler` logs hyper-parameters, training statistics,
and other useful information during training
Parameters
----------
file_name : str
File name to save the logs.
file_location : str
File location to save the logs.
filemode : str, default 'a'
Logging file mode, default using append mode.
verbose : int, default LOG_PER_EPOCH
Limit the granularity of metrics displayed during training process.
verbose=LOG_PER_EPOCH: display metrics every epoch
verbose=LOG_PER_BATCH: display metrics every batch
train_metrics : list of EvalMetrics
Training metrics to be logged, logged at batch end, epoch end, train end.
val_metrics : list of EvalMetrics
Validation metrics to be logged, logged at epoch end, train end.
"""
LOG_PER_EPOCH = 1
LOG_PER_BATCH = 2
def __init__(self, file_name=None,
file_location=None,
filemode='a',
verbose=LOG_PER_EPOCH,
train_metrics=None,
val_metrics=None):
super(LoggingHandler, self).__init__()
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
stream_handler = logging.StreamHandler()
self.logger.addHandler(stream_handler)
# save logger to file only if file name or location is specified
if file_name or file_location:
file_name = file_name or 'estimator_log'
file_location = file_location or './'
file_handler = logging.FileHandler(os.path.join(file_location, file_name), mode=filemode)
self.logger.addHandler(file_handler)
if verbose not in [self.LOG_PER_EPOCH, self.LOG_PER_BATCH]:
raise ValueError("verbose level must be either LOG_PER_EPOCH or "
"LOG_PER_BATCH, received %s. "
"E.g: LoggingHandler(verbose=LoggingHandler.LOG_PER_EPOCH)"
% verbose)
self.verbose = verbose
self.train_metrics = train_metrics or []
self.val_metrics = val_metrics or []
self.batch_index = 0
self.current_epoch = 0
self.processed_samples = 0
# logging handler need to be called at last to make sure all states are updated
# it will also shut down logging at train end
self.priority = np.Inf
def train_begin(self, estimator, *args, **kwargs):
self.train_start = time.time()
trainer = estimator.trainer
optimizer = trainer.optimizer.__class__.__name__
lr = trainer.learning_rate
self.logger.info("Training begin: using optimizer %s "
"with current learning rate %.4f ",
optimizer, lr)
if estimator.max_epoch:
self.logger.info("Train for %d epochs.", estimator.max_epoch)
else:
self.logger.info("Train for %d batches.", estimator.max_batch)
# reset all counters
self.current_epoch = 0
self.batch_index = 0
self.processed_samples = 0
def train_end(self, estimator, *args, **kwargs):
train_time = time.time() - self.train_start
msg = 'Train finished using total %ds with %d epochs. ' % (train_time, self.current_epoch)
# log every result in train stats including train/validation loss & metrics
for metric in self.train_metrics + self.val_metrics:
name, value = metric.get()
msg += '%s: %.4f, ' % (name, value)
self.logger.info(msg.rstrip(', '))
# make a copy of handler list and remove one by one
# as removing handler will edit the handler list
for handler in self.logger.handlers[:]:
handler.close()
self.logger.removeHandler(handler)
logging.shutdown()
def batch_begin(self, estimator, *args, **kwargs):
if self.verbose == self.LOG_PER_BATCH:
self.batch_start = time.time()
def batch_end(self, estimator, *args, **kwargs):
if self.verbose == self.LOG_PER_BATCH:
batch_time = time.time() - self.batch_start
msg = '[Epoch %d][Batch %d]' % (self.current_epoch, self.batch_index)
self.processed_samples += kwargs['batch'][0].shape[0]
msg += '[Samples %s] ' % (self.processed_samples)
msg += 'time/batch: %.3fs ' % batch_time
for metric in self.train_metrics:
# only log current training loss & metric after each batch
name, value = metric.get()
msg += '%s: %.4f, ' % (name, value)
self.logger.info(msg.rstrip(', '))
self.batch_index += 1
def epoch_begin(self, estimator, *args, **kwargs):
if self.verbose >= self.LOG_PER_EPOCH:
self.epoch_start = time.time()
self.logger.info("[Epoch %d] Begin, current learning rate: %.4f",
self.current_epoch, estimator.trainer.learning_rate)
def epoch_end(self, estimator, *args, **kwargs):
if self.verbose >= self.LOG_PER_EPOCH:
epoch_time = time.time() - self.epoch_start
msg = '[Epoch %d] Finished in %.3fs, ' % (self.current_epoch, epoch_time)
for monitor in self.train_metrics + self.val_metrics:
name, value = monitor.get()
msg += '%s: %.4f, ' % (name, value)
self.logger.info(msg.rstrip(', '))
self.current_epoch += 1
self.batch_index = 0
class CheckpointHandler(TrainBegin, BatchEnd, EpochEnd):
"""Save the model after user define period
:py:class:`CheckpointHandler` saves the network architecture after first batch if the model
can be fully hybridized, saves model parameters and trainer states after user defined period,
default saves every epoch.
Parameters
----------
model_dir : str
File directory to save all the model related files including model architecture,
model parameters, and trainer states.
model_prefix : str default 'model'
Prefix to add for all checkpoint file names.
monitor: EvalMetric, default None
The metrics to monitor and determine if model has improved
verbose: int, default 0
Verbosity mode, 1 means inform user every time a checkpoint is saved
save_best: bool, default False
If True, monitor must not be None, :py:class:`CheckpointHandler` will save the
model parameters and trainer states with the best monitored value.
mode: str, default 'auto'
One of {auto, min, max}, if `save_best=True`, the comparison to make
and determine if the monitored value has improved. if 'auto' mode,
:py:class:`CheckpointHandler` will try to use min or max based on
the monitored metric name.
epoch_period: int, default 1
Epoch intervals between saving the network. By default, checkpoints are
saved every epoch.
batch_period: int, default None
Batch intervals between saving the network.
By default, checkpoints are not saved based on the number of batches.
max_checkpoints : int, default 5
Maximum number of checkpoint files to keep in the model_dir, older checkpoints
will be removed. Best checkpoint file is not counted.
resume_from_checkpoint : bool, default False
Whether to resume training from checkpoint in model_dir. If True and checkpoints
found, :py:class:`CheckpointHandler` will load net parameters and trainer states,
and train the remaining of epochs and batches.
"""
def __init__(self,
model_dir,
model_prefix='model',
monitor=None,
verbose=0,
save_best=False,
mode='auto',
epoch_period=1,
batch_period=None,
max_checkpoints=5,
resume_from_checkpoint=False):
self.monitor = monitor
self.verbose = verbose
if not os.path.exists(model_dir):
os.makedirs(model_dir)
self.model_dir = model_dir
self.model_prefix = model_prefix
self.save_best = save_best
if self.save_best and not isinstance(self.monitor, EvalMetric):
raise ValueError("To save best model only, please provide one of the metric objects as monitor, "
"You can get these objects using estimator.prepare_loss_and_metric()")
self.epoch_period = epoch_period
self.batch_period = batch_period
self.current_batch = 0
self.current_epoch = 0
self.max_checkpoints = max_checkpoints
self.resume_from_checkpoint = resume_from_checkpoint
self.saved_checkpoints = []
self.logger = logging.getLogger(__name__)
if self.save_best:
if mode not in ['auto', 'min', 'max']:
warnings.warn('ModelCheckpoint mode %s is unknown, '
'fallback to auto mode. CheckpointHandler will use'
'max mode for f1 and accuracy metric comparison and '
'use min mode other wise' % (mode),
RuntimeWarning)
mode = 'auto'
if mode == 'min':
self.monitor_op = np.less
self.best = np.Inf
elif mode == 'max':
self.monitor_op = np.greater
self.best = -np.Inf
else:
# use greater for accuracy and f1 and less otherwise
if 'acc' or 'f1' in self.monitor.get()[0].lower():
self.logger.info("`greater` operator will be used to determine "
"if %s has improved, please use `min` for mode "
"if you want otherwise", self.monitor.get()[0])
self.monitor_op = np.greater
else:
self.logger.info("`less` operator will be used to determine "
"if %s has improved, please use `max` for mode "
"if you want otherwise", self.monitor.get()[0])
self.monitor_op = np.less
def train_begin(self, estimator, *args, **kwargs):
# reset all counters
self.current_epoch = 0
self.current_batch = 0
if self.save_best:
self.best = np.Inf if self.monitor_op == np.less else -np.Inf # pylint: disable=comparison-with-callable
if self.resume_from_checkpoint:
error_msg = "To use resume from checkpoint, you must only specify " \
"the same type of period you used for training." \
"For example, if you are training based on number of epochs," \
"you must save only based on epochs, and set batch_period to None."
if estimator.max_batch:
assert self.batch_period, error_msg
assert not self.epoch_period, error_msg
if estimator.max_epoch:
assert self.epoch_period, error_msg
assert not self.batch_period, error_msg
self._resume_from_checkpoint(estimator)
def batch_end(self, estimator, *args, **kwargs):
# only save symbol once after first batch
if self.current_batch == 0:
self._save_symbol(estimator)
if self.batch_period and (self.current_batch + 1) % self.batch_period == 0:
self._save_checkpoint(estimator)
self.current_batch += 1
def epoch_end(self, estimator, *args, **kwargs):
if self.epoch_period and (self.current_epoch + 1) % self.epoch_period == 0:
self._save_checkpoint(estimator)
self.current_epoch += 1
def _save_checkpoint(self, estimator):
# if resumed from checkpoint, increment checkpoint number
if self.resume_from_checkpoint:
save_epoch_number = self.current_epoch + self.trained_epoch + 1
if estimator.max_epoch:
# checkpoint saved at epoch end, batch number already incremented
save_batch_number = self.current_batch + self.trained_batch
else:
save_batch_number = self.current_batch + self.trained_batch + 1
else:
save_epoch_number = self.current_epoch
save_batch_number = self.current_batch
prefix = "%s-epoch%dbatch%d" % (self.model_prefix, save_epoch_number, save_batch_number)
self._save_params_and_trainer(estimator, prefix)
if self.verbose > 0:
self.logger.info('[Epoch %d] CheckpointHandler: trained total %d batches, '
'saving model at %s with prefix: %s',
self.current_epoch, self.current_batch + 1, self.model_dir, prefix)
if self.save_best:
monitor_name, monitor_value = self.monitor.get()
# check if monitor exists in train stats
if np.isnan(monitor_value):
warnings.warn(RuntimeWarning('Skipping save best because %s is not updated, make sure you '
'pass one of the metric objects as monitor, '
'you can use estimator.prepare_loss_and_metrics to'
'create all metric objects', monitor_name))
else:
if self.monitor_op(monitor_value, self.best):
prefix = self.model_prefix + '-best'
self._save_params_and_trainer(estimator, prefix)
self.best = monitor_value
if self.verbose > 0:
self.logger.info('[Epoch %d] CheckpointHandler: '
'%s improved from %0.5f to %0.5f, '
'updating best model at %s with prefix: %s',
self.current_epoch, monitor_name,
self.best, monitor_value, self.model_dir, prefix)
else:
if self.verbose > 0:
self.logger.info('[Epoch %d] CheckpointHandler: '
'%s did not improve from %0.5f, '
'skipping updating best model',
self.current_batch, monitor_name,
self.best)
def _save_symbol(self, estimator):
symbol_file = os.path.join(self.model_dir, self.model_prefix + '-symbol.json')
if hasattr(estimator.net, '_cached_graph') and estimator.net._cached_graph:
sym = estimator.net._cached_graph[1]
sym.save(symbol_file)
else:
self.logger.info("Model architecture(symbol file) is not saved, please use HybridBlock "
"to construct your model, can call net.hybridize() before passing to "
"Estimator in order to save model architecture as %s.", symbol_file)
def _save_params_and_trainer(self, estimator, file_prefix):
param_file = os.path.join(self.model_dir, file_prefix + '.params')
trainer_file = os.path.join(self.model_dir, file_prefix + '.states')
estimator.net.save_parameters(param_file)
estimator.trainer.save_states(trainer_file)
# only count checkpoints with epoch or batch number in file name
if 'best' not in file_prefix:
self.saved_checkpoints.append(file_prefix)
# remove old checkpoint when max number of checkpoints reached
if len(self.saved_checkpoints) > self.max_checkpoints:
prefix = self.saved_checkpoints.pop(0)
for fname in os.listdir(self.model_dir):
if fname.startswith(prefix):
os.remove(os.path.join(self.model_dir, fname))
def _resume_from_checkpoint(self, estimator):
prefix = self.model_prefix + '-epoch'
self.trained_epoch = self._find_max_iteration(
dir=self.model_dir,
prefix=prefix,
start='epoch',
end='batch',
saved_checkpoints=self.saved_checkpoints)
prefix += str(self.trained_epoch)
self.trained_batch = self._find_max_iteration(
dir=self.model_dir,
prefix=prefix,
start='batch',
end='.params')
if self.trained_epoch == -1:
msg = "CheckpointHandler: No checkpoint found, training from scratch for "
if estimator.max_batch:
msg += "%d batches" % estimator.max_batch
else:
msg += "%d epochs" % estimator.max_epoch
self.logger.info(msg)
else:
msg = "CheckpointHandler: Checkpoint resumed from epoch %d batch %d, " \
"continue to train for " % (self.trained_epoch, self.trained_batch)
# change maximum number of epoch or batch to train if resumed from epoch checkpoint
if estimator.max_epoch:
if self.trained_epoch >= estimator.max_epoch - 1:
raise ValueError("Found checkpoint with maximum number of epoch %d reached, please specify "
"resume_from_checkpoint=False (default value) if you wan to train from scratch."
% estimator.max_epoch)
estimator.max_epoch = estimator.max_epoch - self.trained_epoch - 1
msg += "%d epochs " % estimator.max_epoch
if estimator.max_batch:
if self.trained_batch >= estimator.max_batch - 1:
raise ValueError("Found checkpoint with maximum number of batch %d reached, please specify"
"resume_from_checkpoint=False (default value) if you wan to train from scratch."
% self.trained_batch)
estimator.max_batch = estimator.max_batch - self.trained_batch - 1
msg += "%d batches " % estimator.max_batch
# load checkpoint
param_file = "%s-epoch%dbatch%d.params" % (self.model_prefix, self.trained_epoch, self.trained_batch)
param_file = os.path.join(self.model_dir, param_file)
trainer_file = "%s-epoch%dbatch%d.states" % (self.model_prefix, self.trained_epoch, self.trained_batch)
trainer_file = os.path.join(self.model_dir, trainer_file)
assert os.path.exists(param_file), "Failed to load checkpoint, %s does not exist" % param_file
assert os.path.exists(trainer_file), "Failed to load checkpoint, %s does not exist" % trainer_file
estimator.net.load_parameters(param_file, ctx=estimator.context)
estimator.trainer.load_states(trainer_file)
self.logger.warning(msg)
def _find_max_iteration(self, dir, prefix, start, end, saved_checkpoints=None):
error_msg = "Error parsing checkpoint file, please check your " \
"checkpoints have the format: " \
"{model_name}-epoch{epoch_number}batch{batch_number}.params, " \
"there should also be a .states file for each .params file "
max_iter = -1
for fname in os.listdir(dir):
if fname.startswith(prefix) and '.params' in fname:
if saved_checkpoints:
# save prefix of existing checkpoints
saved_checkpoints.append(fname[:fname.find('.params')])
try:
# find trained number of epoch
iter = int(fname[fname.find(start) + len(start): fname.find(end)])
if iter > max_iter:
max_iter = iter
except ValueError:
raise ValueError(error_msg)
return max_iter
class EarlyStoppingHandler(TrainBegin, EpochEnd, TrainEnd):
"""Early stop training if monitored value is not improving
Parameters
----------
monitor: EvalMetric
The metric to monitor, and stop training if this metric does not improve.
min_delta: float, default 0
Minimal change in monitored value to be considered as an improvement.
patience: int, default 0
Number of epochs to wait for improvement before terminate training.
mode: str, default 'auto'
One of {auto, min, max}, if `save_best_only=True`, the comparison to make
and determine if the monitored value has improved. if 'auto' mode, checkpoint
handler will try to use min or max based on the monitored metric name.
baseline: float
Baseline value to compare the monitored value with.
"""
def __init__(self,
monitor,
min_delta=0,
patience=0,
mode='auto',
baseline=None):
super(EarlyStoppingHandler, self).__init__()
if not isinstance(monitor, EvalMetric):
raise ValueError("Please provide one of the metric objects as monitor, "
"You can create these objects using estimator.prepare_loss_and_metric()")
self.monitor = monitor
self.baseline = baseline
self.patience = patience
self.min_delta = min_delta
self.wait = 0
self.stopped_epoch = 0
self.current_epoch = 0
self.stop_training = False
self.logger = logging.getLogger(__name__)
if mode not in ['auto', 'min', 'max']:
warnings.warn('EarlyStopping mode %s is unknown, '
'fallback to auto mode. CheckpointHandler will use'
'max mode for f1 and accuracy metric comparison and '
'use min mode other wise' % (mode),
RuntimeWarning)
mode = 'auto'
if mode == 'min':
self.monitor_op = np.less
elif mode == 'max':
self.monitor_op = np.greater
else:
if 'acc' or 'f1' in self.monitor.get()[0].lower():
self.logger.info("`greater` operator is used to determine "
"if %s has improved, please use `min` for mode "
"if you want otherwise", self.monitor.get()[0])
self.monitor_op = np.greater
else:
self.logger.info("`less` operator is used to determine "
"if %s has improved, please use `max` for mode "
"if you want otherwise", self.monitor.get()[0])
self.monitor_op = np.less
if self.monitor_op == np.greater: # pylint: disable=comparison-with-callable
self.min_delta *= 1
else:
self.min_delta *= -1
def train_begin(self, estimator, *args, **kwargs):
self.wait = 0
self.stopped_epoch = 0
self.current_epoch = 0
self.stop_training = False
if self.baseline is not None:
self.best = self.baseline
else:
self.best = np.Inf if self.monitor_op == np.less else -np.Inf # pylint: disable=comparison-with-callable
def epoch_end(self, estimator, *args, **kwargs):
monitor_name, monitor_value = self.monitor.get()
if np.isnan(monitor_value):
warnings.warn(RuntimeWarning('%s is not updated, make sure you pass one of the metric objects'
'as monitor, you can use estimator.prepare_loss_and_metrics to'
'create all metric objects', monitor_name))
else:
if self.monitor_op(monitor_value - self.min_delta, self.best):
self.best = monitor_value
self.wait = 0
else:
self.wait += 1
if self.wait >= self.patience:
self.stopped_epoch = self.current_epoch
self.stop_training = True
self.current_epoch += 1
return self.stop_training
def train_end(self, estimator, *args, **kwargs):
if self.stopped_epoch > 0:
self.logger.info('[Epoch %d] EarlyStoppingHanlder: early stopping due to %s not improving',
self.stopped_epoch, self.monitor.get()[0])
| {
"content_hash": "21e164c787fd1d414b8e3f4ae3790fb4",
"timestamp": "",
"source": "github",
"line_count": 691,
"max_line_length": 117,
"avg_line_length": 44.68162083936324,
"alnum_prop": 0.5789473684210527,
"repo_name": "reminisce/mxnet",
"id": "da2c84455e3517e8b45d92dcf08d12b7ade44c40",
"size": "31728",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/mxnet/gluon/contrib/estimator/event_handler.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "215572"
},
{
"name": "C++",
"bytes": "7680259"
},
{
"name": "CMake",
"bytes": "99958"
},
{
"name": "Clojure",
"bytes": "622688"
},
{
"name": "Cuda",
"bytes": "970884"
},
{
"name": "Dockerfile",
"bytes": "85151"
},
{
"name": "Groovy",
"bytes": "122800"
},
{
"name": "HTML",
"bytes": "40277"
},
{
"name": "Java",
"bytes": "205196"
},
{
"name": "Julia",
"bytes": "436326"
},
{
"name": "Jupyter Notebook",
"bytes": "3660387"
},
{
"name": "MATLAB",
"bytes": "34903"
},
{
"name": "Makefile",
"bytes": "201597"
},
{
"name": "Perl",
"bytes": "1550163"
},
{
"name": "Perl 6",
"bytes": "7280"
},
{
"name": "PowerShell",
"bytes": "13786"
},
{
"name": "Python",
"bytes": "7842403"
},
{
"name": "R",
"bytes": "357807"
},
{
"name": "Scala",
"bytes": "1305036"
},
{
"name": "Shell",
"bytes": "427407"
},
{
"name": "Smalltalk",
"bytes": "3497"
}
],
"symlink_target": ""
} |
import unittest
from unittest import mock
import gitmagic
class TestBlameParser(unittest.TestCase):
def setUp(self):
self.commit1 = ['commit1',['line 1', 'line 2', 'line 3']]
self.commit2 = ['commit2',['line 4', 'line 5', 'line 6']]
self.repo = mock.Mock()
self.repo.blame.return_value = [self.commit1, self.commit2]
def test_that_it_returns_all_commits_from_the_blame(self):
commits = self._blame(1, 2)
self.assertIn(self.commit1[0], commits)
self.assertIn(self.commit2[0], commits)
def test_that_it_puts_overlapping_commits_to_the_beginning_of_the_list(self):
commits = self._blame(4, 4)
self.assertEquals(self.commit2[0], commits[0])
def _blame(self, start, end ):
return gitmagic.blame(self.repo, 'a filename', (start, end))
class TestFixupDestinationPicker(unittest.TestCase):
def setUp(self):
self.changed_file_path = "a_file_path"
self.matching_commit = self.changed_file_path
self.another_changed_file_path = "another_file_path"
self.another_matching_commit = self.another_changed_file_path
self.repo = mock.Mock()
self.commit_range = [self.matching_commit, self.another_matching_commit]
self.destination_picker = gitmagic.FixupDestinationPicker(self.repo, self.commit_range)
def test_that_it_picks_a_commit_on_the_changed_file(self):
self.assertEquals(self._pick_commit_from([self.matching_commit]), [self.matching_commit])
def test_that_it_picks_a_commit_only_from_the_commit_range(self):
self.assertEquals(len(self._pick_commit_from(["matching commit not in the range"])), 0)
def _pick_commit_from(self, commits):
with mock.patch('gitmagic.blame') as blame_mock:
blame_mock.return_value = commits
return self.destination_picker.pick(
gitmagic.Change(
self.changed_file_path, "b name",
"a content", "b content",
(1, 2), (3, 4),
"diff"))
| {
"content_hash": "9e62715fa5523756aabe2fb099254831",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 97,
"avg_line_length": 41.78,
"alnum_prop": 0.6280516993776927,
"repo_name": "balabit/git-magic",
"id": "18298e4890f3878a7f23b952668b65179e896b9e",
"size": "2089",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gitmagic/tests/test_fixup_destination_picker.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "158"
},
{
"name": "Python",
"bytes": "14596"
},
{
"name": "Shell",
"bytes": "55"
}
],
"symlink_target": ""
} |
import six
import webob.dec
import webob.exc
from oslo_log import log as logging
from conveyor.api.wsgi import wsgi
from conveyor import exception
from conveyor.i18n import _, _LE, _LI
from conveyor import utils
from conveyor import wsgi as base_wsgi
LOG = logging.getLogger(__name__)
class FaultWrapper(base_wsgi.Middleware):
"""Calls down the middleware stack, making exceptions into faults."""
_status_to_type = {}
@staticmethod
def status_to_type(status):
if not FaultWrapper._status_to_type:
for clazz in utils.walk_class_hierarchy(webob.exc.HTTPError):
FaultWrapper._status_to_type[clazz.code] = clazz
return FaultWrapper._status_to_type.get(
status, webob.exc.HTTPInternalServerError)()
def _error(self, inner, req):
if not isinstance(inner, exception.QuotaError):
LOG.error(_LE("Caught error: %s"), inner)
safe = getattr(inner, 'safe', False)
headers = getattr(inner, 'headers', None)
status = getattr(inner, 'code', 500)
if status is None:
status = 500
msg_dict = dict(url=req.url, status=status)
LOG.info(_LI("%(url)s returned with HTTP %(status)d"), msg_dict)
outer = self.status_to_type(status)
if headers:
outer.headers = headers
# NOTE(johannes): We leave the explanation empty here on
# purpose. It could possibly have sensitive information
# that should not be returned back to the user. See
# bugs 868360 and 874472
# NOTE(eglynn): However, it would be over-conservative and
# inconsistent with the EC2 API to hide every exception,
# including those that are safe to expose, see bug 1021373
if safe:
msg = (inner.msg if isinstance(inner, exception.V2vException)
else six.text_type(inner))
params = {'exception': inner.__class__.__name__,
'explanation': msg}
outer.explanation = _('%(exception)s: %(explanation)s') % params
return wsgi.Fault(outer)
@webob.dec.wsgify(RequestClass=wsgi.Request)
def __call__(self, req):
try:
return req.get_response(self.application)
except Exception as ex:
return self._error(ex, req)
| {
"content_hash": "1e7f3aaceacb15b8fb527a35a397aefc",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 76,
"avg_line_length": 36.34375,
"alnum_prop": 0.6272570937231299,
"repo_name": "Hybrid-Cloud/conveyor",
"id": "a39f88c63281c4fbe24b334611f7718c13a9ec12",
"size": "3059",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "conveyor/api/middleware/fault.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "3789174"
},
{
"name": "Shell",
"bytes": "16567"
}
],
"symlink_target": ""
} |
import os, csv
datadir = "/Users/titlis/cogsci/projects/stanford/projects/overinformativeness/experiments/24_interactive_color_reference_game/experiment/data/"
csv_messagenames = [o for o in os.listdir("/Users/titlis/cogsci/projects/stanford/projects/overinformativeness/experiments/24_interactive_color_reference_game/experiment/data/message/") if (o.endswith('csv') & o.startswith('2016-101-22'))]
csv_trialnames = [o for o in os.listdir("/Users/titlis/cogsci/projects/stanford/projects/overinformativeness/experiments/24_interactive_color_reference_game/experiment/data/clickedObj/") if (o.endswith('csv') & o.startswith('2016-101-22'))]
# helper function to get messages associated with a particular trial
def getMessages(trial, messages):
speakermessages = []
listenermessages = []
times = []
for m in messages:
if m['roundNum'] == str(trial):
if m['sender'] == 'speaker':
speakermessages.append(m['contents'])
else:
listenermessages.append(m['contents'])
times.append(m['time'])
mess = {'nummessages': len(speakermessages) + len(listenermessages),
'numsmessages': len(speakermessages),
'numlmessages': len(listenermessages),
'listenermessages': listenermessages,
'speakermessages': speakermessages,
'times': times}
return mess
# first make sure that for every trial file there's a message file
for t in csv_trialnames:
shared = False
gameid = t[0:20]
for m in csv_messagenames:
if m.startswith(gameid):
shared = True
if shared == False:
print "corresponding message file not found: " + gameid
csv_trialnames.pop(csv_trialnames.index(t))
print csv_messagenames
print csv_trialnames
print "Number of message files: " + str(len(csv_messagenames))
print "Number of trial files: " + str(len(csv_trialnames))
finalmessagelines = []
finaltriallines = []
# the meaty bit
for k,m in enumerate(csv_messagenames):
#print m
messagelines = []
triallines = []
messagereader = csv.DictReader(open(datadir+"/message/"+m, 'rb'),delimiter=",",quotechar='\"')
messagelines.extend(list(messagereader))
trialreader = csv.DictReader(open(datadir+"/clickedObj/"+m, 'rb'),delimiter=",",quotechar='\"')
triallines.extend(list(trialreader))
headers = trialreader.fieldnames
for trial in range(1,len(triallines)+1):
mess = getMessages(trial,messagelines)
i = trial - 1
triallines[i]['numMessages'] = mess['nummessages']
triallines[i]['numSMessages'] = mess['numsmessages']
triallines[i]['numLMessages'] = mess['numlmessages']
triallines[i]['speakerMessages'] = "___".join(mess['speakermessages'])
triallines[i]['listenerMessages'] = "___".join(mess['listenermessages'])
triallines[i]['messageTimeStamps'] = "___".join(mess['times'])
# print i
# print k
# print mess['speakermessages']
try:
triallines[i][' refExp'] = mess['speakermessages'][0]
except IndexError:
triallines[i][' refExp'] = "NA"
typ,color = triallines[i]['nameClickedObj'].split("_")
triallines[i]['clickedColor'] = color
triallines[i]['clickedType'] = typ
colormentioned = False
typementioned = False
try:
refexp = [m.lower() for m in mess['speakermessages'][0].split()]
if color in refexp:
colormentioned = True
if typ in refexp:
typementioned = True
except IndexError:
print "no message on this trial"
triallines[i]['colorMentioned'] = colormentioned
triallines[i]['typeMentioned'] = typementioned
# finalmessagelines = finalmessagelines + messagelines
finaltriallines = finaltriallines + triallines
headers.append('numMessages')
headers.append('numSMessages')
headers.append('numLMessages')
headers.append('speakerMessages')
headers.append('listenerMessages')
headers.append('messageTimeStamps')
headers.append(' refExp')
headers.append('colorMentioned')
headers.append('typeMentioned')
headers.append('clickedType')
headers.append('clickedColor')
#print headers
#print triallines[0].keys()
w = csv.DictWriter(open("../data/results.csv", "wb"),fieldnames=headers,restval="NA",delimiter="\t")
w.writeheader()
w.writerows(finaltriallines)
| {
"content_hash": "d0e12c1c5d4cd764c4ec4fb9f257b1b4",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 241,
"avg_line_length": 31.415384615384614,
"alnum_prop": 0.7196376101860921,
"repo_name": "thegricean/overinformativeness",
"id": "1b82e99af006877018d81a8d938f1653473c6372",
"size": "4084",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "experiments/24_interactive_color_reference_game/results/scripts/parseMessages.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "49763"
},
{
"name": "HTML",
"bytes": "4608944"
},
{
"name": "JavaScript",
"bytes": "1742435"
},
{
"name": "PHP",
"bytes": "4116"
},
{
"name": "Python",
"bytes": "46950"
},
{
"name": "R",
"bytes": "1490886"
},
{
"name": "Rebol",
"bytes": "3918"
},
{
"name": "TeX",
"bytes": "681638"
}
],
"symlink_target": ""
} |
from setuptools import setup, find_packages
import os
import screwjack
setup(
name="screwjack",
version=screwjack.__version__,
description="ScrewJack is a tiny command line tool for manipulating modules.",
long_description="",
author="Xiaolin Zhang",
author_email="leoncamel@gmail.com",
url="https://github.com/DataCanvasIO/screwjack",
license='BSD',
install_requires=['click==0.6', 'jinja2>=2.7.2', 'requests>=2.2.1', 'python-dateutil==2.2', 'pytz>=2014.3'],
packages=['screwjack'],
include_package_data = True,
package_data = {
'': ['templates/basic/*', 'templates/hive/*', 'templates/pig/*', 'templates/emr_hive/*', 'templates/emr_pig/*']
},
scripts=[
'bin/screwjack'
],
classifiers = [
"Development Status :: 2 - Pre-Alpha",
"Environment :: Console",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.7",
"Topic :: Utilities"
]
)
| {
"content_hash": "e0e366409b7da8f89f4aa454cbf80cf5",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 119,
"avg_line_length": 33.354838709677416,
"alnum_prop": 0.6112185686653772,
"repo_name": "DataCanvasIO/screwjack",
"id": "084020afe8782f0ce11df797a9377705bf0c2bd7",
"size": "1035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "39038"
},
{
"name": "Shell",
"bytes": "976"
}
],
"symlink_target": ""
} |
"""Test the CDA method in cclib"""
import sys
import logging
import unittest
sys.path.insert(1, "..")
from ..test_data import getdatafile
from cclib.method import CDA
from cclib.parser import Gaussian
def main(log=True):
data1, logfile1 = getdatafile(Gaussian, "CDA", ["BH3CO-sp.log"])
data2, logfile2 = getdatafile(Gaussian, "CDA", ["BH3.log"])
data3, logfile3 = getdatafile(Gaussian, "CDA", ["CO.log"])
fa = CDA(data1)
if not log:
fa.logger.setLevel(logging.ERROR)
fa.calculate([data2, data3])
return fa
def printResults():
fa = main()
print(" d b r")
print("---------------------------")
spin = 0
for i in range(len(fa.donations[0])):
print(
f"{int(i):2}: {fa.donations[spin][i]:7.3f} {fa.bdonations[spin][i]:7.3f} {fa.repulsions[spin][i]:7.3f}"
)
print("---------------------------")
print(
f"T: {fa.donations[0].sum():7.3f} {fa.bdonations[0].sum():7.3f} {fa.repulsions[0].sum():7.3f}"
)
print("\n\n")
class CDATest(unittest.TestCase):
def runTest(self):
"""Testing CDA results against Frenking's code"""
fa = main(log=False)
donation = fa.donations[0].sum()
bdonation = fa.bdonations[0].sum()
repulsion = fa.repulsions[0].sum()
self.assertAlmostEqual(donation, 0.181, 3)
self.assertAlmostEqual(bdonation, 0.471, 3)
self.assertAlmostEqual(repulsion, -0.334, 3)
if __name__ == "__main__":
printResults()
unittest.TextTestRunner(verbosity=2).run(unittest.makeSuite(CDATest))
| {
"content_hash": "d569936fa5169693fccf4683745f030b",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 115,
"avg_line_length": 26,
"alnum_prop": 0.5594951923076923,
"repo_name": "cclib/cclib",
"id": "49ee47c4c4a6b0e5081454b1fc415a5590c25523",
"size": "1867",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/method/testcda.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arc",
"bytes": "18395"
},
{
"name": "C++",
"bytes": "21085"
},
{
"name": "DIGITAL Command Language",
"bytes": "31999"
},
{
"name": "Python",
"bytes": "1617128"
},
{
"name": "Roff",
"bytes": "375502"
},
{
"name": "Shell",
"bytes": "1484"
},
{
"name": "TeX",
"bytes": "29388"
}
],
"symlink_target": ""
} |
from google.cloud import aiplatform_v1
async def sample_delete_context():
# Create a client
client = aiplatform_v1.MetadataServiceAsyncClient()
# Initialize request argument(s)
request = aiplatform_v1.DeleteContextRequest(
name="name_value",
)
# Make the request
operation = client.delete_context(request=request)
print("Waiting for operation to complete...")
response = await operation.result()
# Handle the response
print(response)
# [END aiplatform_generated_aiplatform_v1_MetadataService_DeleteContext_async]
| {
"content_hash": "8a5ab49e59c970a2b79cc4f1f3267de2",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 78,
"avg_line_length": 24.91304347826087,
"alnum_prop": 0.7155322862129145,
"repo_name": "googleapis/python-aiplatform",
"id": "23c94c67caacde77960dbb9c28fd4d347fc9181e",
"size": "1592",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "samples/generated_samples/aiplatform_generated_aiplatform_v1_metadata_service_delete_context_async.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2050"
},
{
"name": "Python",
"bytes": "23977004"
},
{
"name": "Shell",
"bytes": "30668"
}
],
"symlink_target": ""
} |
import base64
import collections
import itertools
import logging
import os, lzma
import pickle
import shutil
import zipfile
from sqlalchemy import func
from sqlalchemy.sql.expression import delete, bindparam
from terroroftinytown.format import registry
from terroroftinytown.format.projectsettings import ProjectSettingsWriter
from terroroftinytown.format.urlformat import quote
from terroroftinytown.tracker.bootstrap import Bootstrap
from terroroftinytown.tracker.model import new_session, Project, Result
from terroroftinytown.util.externalsort import GNUExternalSort
logger = logging.getLogger(__name__)
ResultContainer = collections.namedtuple(
'ResultContainer',
['id', 'shortcode', 'url', 'encoding', 'datetime']
)
class Exporter:
def __init__(self, output_dir, format="beacon", settings={}):
super().__init__()
self.setup_format(format)
self.output_dir = output_dir
self.settings = settings
self.after = self.settings['after']
self.max_items = self.settings['max_items']
self.projects_count = 0
self.items_count = 0
self.last_date = None
self.lzma = True
self.extension = 'txt.xz'
# Length of directory name
self.dir_length = settings['dir_length']
# Number of characters from the right are not used in directory name
# in other words, number of _
self.max_right = settings['max_right']
# Number of characters from the left that are used in file name
# in other words, number of characters that are not in directory name and not _
self.file_length = settings['file_length']
# Example of settings:
# dir_length = 2
# max_right = 4
# file_length = 2
# output: projectname/00/01/000100____.txt, projectname/01/01__.txt
self.fp = None
self.writer = None
self.project_result_sorters = {}
self.working_set_filename = os.path.join(output_dir,
'current_working_set.txt')
def setup_format(self, format):
self.format = registry[format]
def make_output_dir(self):
if not os.path.isdir(self.output_dir):
os.makedirs(self.output_dir)
def dump(self):
self.make_output_dir()
database_busy_file = self.settings.get('database_busy_file')
if database_busy_file:
with open(database_busy_file, 'w'):
pass
self._drain_to_working_set()
if database_busy_file:
os.remove(database_busy_file)
self._feed_input_sorters()
with new_session() as session:
for project_id, sorter in self.project_result_sorters.items():
project = session.query(Project).filter_by(name=project_id).first()
if self.settings['include_settings']:
self.dump_project_settings(project)
self.dump_project(project, sorter)
if self.settings['zip']:
self.zip_project(project)
os.remove(self.working_set_filename)
def _drain_to_working_set(self, size=1000):
logger.info('Draining to working set %s', self.working_set_filename)
assert not os.path.exists(self.working_set_filename)
with new_session() as session:
query = session.query(Result)
if self.after:
query = query.filter(Result.datetime > self.after)
with open(self.working_set_filename, 'wb') as work_file:
last_id = -1
num_results = 0
running = True
while running:
# Optimized for SQLite scrolling window
rows = query.filter(Result.id > last_id).limit(size).all()
if not rows:
break
delete_ids = []
for result in rows:
line = base64.b64encode(pickle.dumps({
'id': result.id,
'project_id': result.project_id,
'shortcode': result.shortcode,
'url': result.url,
'encoding': result.encoding,
'datetime': result.datetime,
}))
work_file.write(line)
work_file.write(b'\n')
num_results += 1
self.items_count += 1
delete_ids.append(result.id)
if num_results % 10000 == 0:
logger.info('Drain progress: %d', num_results)
if num_results % 100000 == 0:
# Risky, but need to do this since WAL
# performance is low on large transactions
logger.info("Checkpoint. (Don't delete stray files if program crashes!)")
work_file.flush()
session.commit()
if self.max_items and num_results >= self.max_items:
logger.info('Reached max items %d.', self.max_items)
running = False
break
if self.settings['delete']:
delete_query = delete(Result).where(
Result.id == bindparam('id')
)
session.execute(
delete_query,
[{'id': result_id} for result_id in delete_ids]
)
def _feed_input_sorters(self):
num_results = 0
with open(self.working_set_filename, 'rb') as work_file:
for line in work_file:
result = pickle.loads(base64.b64decode(line))
if result['project_id'] not in self.project_result_sorters:
self.project_result_sorters[result['project_id']] = \
GNUExternalSort(temp_dir=self.output_dir,
temp_prefix='tott-{0}-'.format(
result['project_id']
)
)
self.projects_count += 1
sorter = self.project_result_sorters[result['project_id']]
sorter.input(
result['shortcode'],
(result['id'], result['url'], result['encoding'],
result['datetime'])
)
num_results += 1
if num_results % 10000 == 0:
logger.info('Sort progress: %d', num_results)
def dump_project(self, project, sorter):
logger.info('Looking in project %s', project.name)
if project.url_template.endswith('{shortcode}'):
site = project.url_template.replace('{shortcode}', '')
else:
site = project.url_template
last_filename = None
for i, (key, value) in enumerate(sorter.sort()):
if i % 10000 == 0:
logger.info('Format progress: %d/%d', i, sorter.rows)
id_, url, encoding, datetime_ = value
result = ResultContainer(id_, key, url, encoding, datetime_)
# we can do this as the query is sorted
# so that item that would end up together
# would returned together
filename = self.get_filename(project, result)
if filename != last_filename:
self.close_fp()
logger.info('Writing results to file %s.', filename)
assert not os.path.isfile(filename), 'Target file %s already exists' % (filename)
self.fp = self.get_fp(filename)
self.writer = self.format(self.fp)
self.writer.write_header(site)
last_filename = filename
for encoding in (result.encoding, 'latin-1', 'cp437', 'utf-8'):
try:
result.url.encode(encoding)
except UnicodeError:
logger.warning('Encoding failed %s|%s %s.',
result.shortcode, repr(result.url),
encoding,
exc_info=True)
continue
else:
self.writer.write_shortcode(
result.shortcode, result.url, encoding
)
break
else:
raise Exception(
'Unable to encode {}|{} {}'
.format(result.shortcode, repr(result.url),
result.encoding)
)
if not self.last_date or result.datetime > self.last_date:
self.last_date = result.datetime
self.close_fp()
def dump_project_settings(self, project):
path = os.path.join(self.output_dir, project.name,
'{0}.meta.json.xz'.format(project.name))
self.fp = self.get_fp(path)
self.writer = ProjectSettingsWriter(self.fp)
self.writer.write_project(project)
self.close_fp()
def zip_project(self, project):
project_path = os.path.join(self.output_dir, project.name)
filename = project.name
if self.settings.get('zip_filename_infix'):
filename += self.settings['zip_filename_infix']
zip_path = os.path.join(self.output_dir, '{0}.zip'.format(filename))
assert not os.path.isfile(zip_path), 'Target file %s already exists' % (zip_path)
with zipfile.ZipFile(zip_path, mode='w',
compression=zipfile.ZIP_STORED) as zip_file:
for root, dirs, files in os.walk(project_path):
for file in files:
file_path = os.path.join(root, file)
arc_filename = os.path.relpath(file_path, self.output_dir)
zip_file.write(file_path, arc_filename)
shutil.rmtree(project_path)
def get_fp(self, filename):
dirname = os.path.dirname(filename)
if not os.path.isdir(dirname):
os.makedirs(dirname)
if self.lzma:
return lzma.open(filename, 'wb')
else:
return open(filename, 'wb')
def close_fp(self):
if not self.fp or not self.writer:
return
self.writer.write_footer()
self.fp.close()
def get_filename(self, project, item):
path = os.path.join(self.output_dir, project.name)
dirs, prefix, underscores = self.split_shortcode(
item.shortcode, self.dir_length, self.max_right, self.file_length)
dirs = [quote(dirname.encode('ascii')) for dirname in dirs]
path = os.path.join(path, *dirs)
path = os.path.join(path, '%s%s.%s' % (
quote(prefix.encode('ascii')),
'_' * len(underscores),
self.extension
))
return path
@classmethod
def split_shortcode(cls, shortcode, dir_length=2, max_right=4,
file_length=2):
assert dir_length >= 0
assert max_right >= 0
assert file_length >= 0
# 0001asdf
# dir_length max_right file_length
dirs = []
# create directories until we left only max_right or less characters
length = 0
shortcode_temp = shortcode
while dir_length and len(shortcode_temp) > max_right + file_length:
dirname = shortcode_temp[:dir_length]
dirs.append(dirname)
length += len(dirname)
shortcode_temp = shortcode_temp[dir_length:]
# name the file
code_length = len(shortcode)
length_left = code_length - length
underscores = min(length_left, max_right)
return dirs, shortcode[:code_length - underscores], shortcode[code_length - underscores:]
class ExporterBootstrap(Bootstrap):
def start(self, args=None):
super().start(args=args)
logging.basicConfig(level=logging.INFO)
self.exporter = Exporter(self.args.output_dir, self.args.format, vars(self.args))
self.exporter.dump()
self.write_stats()
def setup_args(self):
super().setup_args()
self.arg_parser.add_argument(
'--format', default='beacon',
choices=registry.keys(), help='Output file format')
self.arg_parser.add_argument(
'--after',
help='Only export items submitted after specified time. '
'(ISO8601 format YYYY-MM-DDTHH:MM:SS.mmmmmm)')
self.arg_parser.add_argument(
'--include-settings',
help='Include project settings', action='store_true')
self.arg_parser.add_argument(
'--zip', help='Zip the projects after exporting',
action='store_true')
self.arg_parser.add_argument(
'--dir-length', type=int, default=2,
help='Number of characters per directory name'
)
self.arg_parser.add_argument(
'--file-length', type=int, default=2,
help='Number of characters per filename prefix (excluding directory names)'
)
self.arg_parser.add_argument(
'--max-right', type=int, default=4,
help='Number of characters used inside the file (excluding directory and file prefix names)'
)
self.arg_parser.add_argument(
'--delete', action='store_true',
help='Delete the exported rows after export'
)
self.arg_parser.add_argument(
'--max-items', type=int, metavar='N',
help='Export a maximum of N items.')
self.arg_parser.add_argument(
'--zip-filename-infix',
help='Insert string in filename in final zip filename.'
)
self.arg_parser.add_argument(
'--database-busy-file',
help='A sentinel file to indicate the database is likely busy and locked'
)
self.arg_parser.add_argument(
'output_dir', help='Output directory (will be created)')
def write_stats(self):
logger.info(
'Written %d items in %d projects',
self.exporter.items_count, self.exporter.projects_count
)
if self.exporter.last_date:
logger.info('Last item timestamp (use --after to dump after this item):')
logger.info(self.exporter.last_date.isoformat())
if __name__ == '__main__':
ExporterBootstrap().start()
| {
"content_hash": "cb3438ca7ea19e62a11ae387b2e5d977",
"timestamp": "",
"source": "github",
"line_count": 415,
"max_line_length": 104,
"avg_line_length": 35.81927710843374,
"alnum_prop": 0.5332660612176253,
"repo_name": "hugovk/terroroftinytown",
"id": "241f7597bf878e42eced8b798e9d9513d804646a",
"size": "14883",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "terroroftinytown/tracker/export.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2558"
},
{
"name": "HTML",
"bytes": "27247"
},
{
"name": "JavaScript",
"bytes": "4211"
},
{
"name": "Python",
"bytes": "234754"
}
],
"symlink_target": ""
} |
def get_key(data, keys, default=None):
keys = keys.split('.')
try:
for k in keys:
data = data[k]
return data
except KeyError:
return default
def delete_key(data, keys):
keys = keys.split('.')
for k in keys[:-1]:
data = data[k]
del data[keys[-1]]
def patch(data):
for s in get_key(data, 'services', []):
links = get_key(s, 'tests.docker_links_names')
if links is not None:
s['needed_links'] = links
delete_key(s, 'tests.docker_links_names')
return data
| {
"content_hash": "28740025e22e8c52b14fb162db9eb448",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 54,
"avg_line_length": 25.90909090909091,
"alnum_prop": 0.5403508771929825,
"repo_name": "Deepomatic/dmake",
"id": "814d51272d87e02455d78a6b6a9aeab31748fb6a",
"size": "570",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dmake/migrations/0001_docker_links_names_to_needed_links.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "11924"
},
{
"name": "Dockerfile",
"bytes": "1201"
},
{
"name": "HTML",
"bytes": "5396"
},
{
"name": "Makefile",
"bytes": "4007"
},
{
"name": "Python",
"bytes": "282256"
},
{
"name": "Shell",
"bytes": "56982"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='sites',
old_name='site_id',
new_name='name',
),
migrations.RemoveField(
model_name='sites',
name='a_value',
),
migrations.RemoveField(
model_name='sites',
name='b_value',
),
migrations.RemoveField(
model_name='sites',
name='date',
),
migrations.RemoveField(
model_name='sites',
name='site_name',
),
]
| {
"content_hash": "844a20945ba39d9ad15fb9b01e33eb7c",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 39,
"avg_line_length": 22.08823529411765,
"alnum_prop": 0.49134487350199735,
"repo_name": "ZhibinCH/my3MW",
"id": "d8b6e94dae376e28c4200e61be677d360ea41861",
"size": "824",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sites/migrations/0002_auto_20170806_0833.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "HTML",
"bytes": "4119"
},
{
"name": "Python",
"bytes": "15872"
}
],
"symlink_target": ""
} |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from ironicclient import client
import six
from congress.datasources import constants
from congress.datasources import datasource_driver
from congress.datasources import datasource_utils as ds_utils
class IronicDriver(datasource_driver.PollingDataSourceDriver,
datasource_driver.ExecutionDriver):
CHASSISES = "chassises"
NODES = "nodes"
NODE_PROPERTIES = "node_properties"
PORTS = "ports"
DRIVERS = "drivers"
ACTIVE_HOSTS = "active_hosts"
# This is the most common per-value translator, so define it once here.
value_trans = {'translation-type': 'VALUE'}
def safe_id(x):
if isinstance(x, six.string_types):
return x
try:
return x['id']
except KeyError:
return str(x)
def safe_port_extra(x):
try:
return x['vif_port_id']
except KeyError:
return ""
chassises_translator = {
'translation-type': 'HDICT',
'table-name': CHASSISES,
'selector-type': 'DOT_SELECTOR',
'field-translators':
({'fieldname': 'uuid', 'col': 'id', 'translator': value_trans},
{'fieldname': 'created_at', 'translator': value_trans},
{'fieldname': 'updated_at', 'translator': value_trans})}
nodes_translator = {
'translation-type': 'HDICT',
'table-name': NODES,
'selector-type': 'DOT_SELECTOR',
'field-translators':
({'fieldname': 'uuid', 'col': 'id',
'desc': '', 'translator': value_trans},
{'fieldname': 'chassis_uuid', 'desc': '',
'col': 'owner_chassis', 'translator': value_trans},
{'fieldname': 'power_state', 'desc': '',
'translator': value_trans},
{'fieldname': 'maintenance', 'desc': '',
'translator': value_trans},
{'fieldname': 'properties', 'desc': '',
'translator':
{'translation-type': 'HDICT',
'table-name': NODE_PROPERTIES,
'parent-key': 'id',
'parent-col-name': 'properties',
'selector-type': 'DICT_SELECTOR',
'in-list': False,
'field-translators':
({'fieldname': 'memory_mb',
'translator': value_trans},
{'fieldname': 'cpu_arch',
'translator': value_trans},
{'fieldname': 'local_gb',
'translator': value_trans},
{'fieldname': 'cpus',
'translator': value_trans})}},
{'fieldname': 'driver', 'translator': value_trans},
{'fieldname': 'instance_uuid', 'col': 'running_instance',
'translator': value_trans},
{'fieldname': 'created_at', 'translator': value_trans},
{'fieldname': 'provision_updated_at', 'translator': value_trans},
{'fieldname': 'updated_at', 'translator': value_trans})}
ports_translator = {
'translation-type': 'HDICT',
'table-name': PORTS,
'selector-type': 'DOT_SELECTOR',
'field-translators':
({'fieldname': 'uuid', 'col': 'id', 'translator': value_trans},
{'fieldname': 'node_uuid', 'col': 'owner_node',
'translator': value_trans},
{'fieldname': 'address', 'col': 'mac_address',
'translator': value_trans},
{'fieldname': 'extra', 'col': 'vif_port_id', 'translator':
{'translation-type': 'VALUE',
'extract-fn': safe_port_extra}},
{'fieldname': 'created_at', 'translator': value_trans},
{'fieldname': 'updated_at', 'translator': value_trans})}
drivers_translator = {
'translation-type': 'HDICT',
'table-name': DRIVERS,
'selector-type': 'DOT_SELECTOR',
'field-translators':
({'fieldname': 'name', 'translator': value_trans},
{'fieldname': 'hosts', 'translator':
{'translation-type': 'LIST',
'table-name': ACTIVE_HOSTS,
'parent-key': 'name',
'parent-col-name': 'name',
'val-col': 'hosts',
'translator':
{'translation-type': 'VALUE'}}})}
TRANSLATORS = [chassises_translator, nodes_translator, ports_translator,
drivers_translator]
def __init__(self, name='', args=None):
super(IronicDriver, self).__init__(name, args)
datasource_driver.ExecutionDriver.__init__(self)
self.creds = self.get_ironic_credentials(args)
session = ds_utils.get_keystone_session(self.creds)
self.ironic_client = client.get_client(
api_version=self.creds.get('api_version', '1'), session=session)
self.add_executable_client_methods(self.ironic_client,
'ironicclient.v1.')
self.initialize_update_methods()
self._init_end_start_poll()
@staticmethod
def get_datasource_info():
result = {}
result['id'] = 'ironic'
result['description'] = ('Datasource driver that interfaces with '
'OpenStack bare metal aka ironic.')
result['config'] = ds_utils.get_openstack_required_config()
result['config']['lazy_tables'] = constants.OPTIONAL
result['secret'] = ['password']
return result
def get_ironic_credentials(self, creds):
d = {}
d['api_version'] = '1'
d['insecure'] = False
# save a copy to renew auth token
d['username'] = creds['username']
d['password'] = creds['password']
d['auth_url'] = creds['auth_url']
d['tenant_name'] = creds['tenant_name']
# ironicclient.get_client() uses different names
d['os_username'] = creds['username']
d['os_password'] = creds['password']
d['os_auth_url'] = creds['auth_url']
d['os_tenant_name'] = creds['tenant_name']
return d
def initialize_update_methods(self):
chassises_method = lambda: self._translate_chassises(
self.ironic_client.chassis.list(detail=True, limit=0))
self.add_update_method(chassises_method, self.chassises_translator)
nodes_method = lambda: self._translate_nodes(
self.ironic_client.node.list(detail=True, limit=0))
self.add_update_method(nodes_method, self.nodes_translator)
ports_method = lambda: self._translate_ports(
self.ironic_client.port.list(detail=True, limit=0))
self.add_update_method(ports_method, self.ports_translator)
drivers_method = lambda: self._translate_drivers(
self.ironic_client.driver.list())
self.add_update_method(drivers_method, self.drivers_translator)
@ds_utils.update_state_on_changed(CHASSISES)
def _translate_chassises(self, obj):
row_data = IronicDriver.convert_objs(obj,
IronicDriver.chassises_translator)
return row_data
@ds_utils.update_state_on_changed(NODES)
def _translate_nodes(self, obj):
row_data = IronicDriver.convert_objs(obj,
IronicDriver.nodes_translator)
return row_data
@ds_utils.update_state_on_changed(PORTS)
def _translate_ports(self, obj):
row_data = IronicDriver.convert_objs(obj,
IronicDriver.ports_translator)
return row_data
@ds_utils.update_state_on_changed(DRIVERS)
def _translate_drivers(self, obj):
row_data = IronicDriver.convert_objs(obj,
IronicDriver.drivers_translator)
return row_data
def execute(self, action, action_args):
"""Overwrite ExecutionDriver.execute()."""
# action can be written as a method or an API call.
func = getattr(self, action, None)
if func and self.is_executable(func):
func(action_args)
else:
self._execute_api(self.ironic_client, action, action_args)
| {
"content_hash": "c6703fa189bcd29378d5219670b27791",
"timestamp": "",
"source": "github",
"line_count": 206,
"max_line_length": 79,
"avg_line_length": 41.907766990291265,
"alnum_prop": 0.532607436580563,
"repo_name": "openstack/congress",
"id": "866b2a04273fe5f8139ac1550f083474a7198138",
"size": "9271",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "congress/datasources/ironic_driver.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GAP",
"bytes": "7778"
},
{
"name": "Makefile",
"bytes": "228"
},
{
"name": "Mako",
"bytes": "1043"
},
{
"name": "Python",
"bytes": "2614028"
},
{
"name": "Shell",
"bytes": "45786"
}
],
"symlink_target": ""
} |
import os
import sys
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import and_
from sqlalchemy.orm import load_only
from models import Advertisement, Municipality
import numpy as np
from osgeo import gdal
class GeoData():
def __init__(self, filename):
driver = gdal.GetDriverByName('GTiff')
dataset = gdal.Open(filename)
band = dataset.GetRasterBand(1)
self.ndval = band.GetNoDataValue()
transform = dataset.GetGeoTransform()
self.xOrigin = transform[0]
self.yOrigin = transform[3]
self.pixelWidth = transform[1]
self.pixelHeight = -transform[5]
cols = dataset.RasterXSize
rows = dataset.RasterYSize
self.geodata = band.ReadAsArray(0, 0, cols, rows)
# lv03 coordinates
def mean_by_coord(self, easting, northing):
num_pix = 15
all_values = []
for x in range(-num_pix, num_pix+1):
for y in range(-num_pix, num_pix+1):
col = int((easting - self.xOrigin) / self.pixelWidth) + x
row = int((self.yOrigin - northing) / self.pixelHeight) + y
all_values.append(self.geodata[row][col])
all_values = np.array(all_values)
return np.mean(all_values[np.where(all_values != self.ndval)])
def noise_level_ad():
try:
ads = session.query(Advertisement) \
.options(load_only("id", "lv03_easting", "lv03_northing", "noise_level", 'latitude', 'longitude', 'street', 'municipality_unparsed')) \
.filter(and_(Advertisement.lv03_easting != None, Advertisement.lv03_easting != 0)) \
.filter(Advertisement.longitude < 1000) \
.filter(Advertisement.noise_level == None) \
.all()
count = len(ads)
print("Found {} entries to do.".format(count))
i = 0
for ad in ads:
try:
ad.noise_level = geodata.mean_by_coord(ad.lv03_easting, ad.lv03_northing)
except:
print("Exception on row id: {}, E {} N {} lat {} long {} address {} {}".format(ad.id, ad.lv03_easting, ad.lv03_northing, ad.latitude, ad.longitude, ad.street, ad.municipality_unparsed))
session.add(ad)
if i % 100 == 0:
print("Progress: {}/{} Saving...".format(i+1, count), end="")
session.commit()
print("Saved")
i += 1
print("Progress: {}/{}".format(count, count))
#session.bulk_update_mappings(Advertisement, [{'id': x.id, 'noise_level': x.noise_level} for x in ads])
session.commit()
except:
session.rollback()
raise
def noise_level_municipality():
try:
municipalities = session.query(Municipality) \
.options(load_only("id", "lv03_easting", "lv03_northing", "noise_level", 'lat', 'long')) \
.filter(and_(Municipality.lv03_easting != None, Municipality.lv03_easting != 0)) \
.filter(Municipality.long < 1000) \
.filter(Municipality.noise_level == None) \
.all()
count = len(municipalities)
print("Found {} entries to do.".format(count))
for i, mun in enumerate(municipalities):
try:
mun.noise_level = geodata.mean_by_coord(mun.lv03_easting, mun.lv03_northing)
except:
print("Exception on row id: {}, E {} N {} lat {} long {} address {} {}".format(mun.id, mun.lv03_easting, mun.lv03_northing, mun.lat, mun.long))
session.add(mun)
if i % 100 == 0:
print("Progress: {}/{} Saving...".format(i+1, count), end="")
session.commit()
print("Saved")
i += 1
print("Progress: {}/{}".format(count, count))
session.commit()
except:
session.rollback()
raise
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Please specify option: [ad, mun]")
sys.exit(1)
print("Loading tiff file...")
# this file is not checked in, get it here (GeoTiff): https://opendata.swiss/dataset/larmbelastung-durch-strassenverkehr-tag
geodata = GeoData("Strassenlaerm_Tag.tif")
print("Open DB connection")
engine = create_engine(os.environ.get('DATABASE_URL'), connect_args={"application_name":"GDAL data"})
Session = sessionmaker(bind=engine)
# start transaction
session = Session()
arg = sys.argv[1]
if arg == "ad":
print("Get data for advertisements")
noise_level_ad()
if arg == 'mun':
print("Get data for municipalities")
noise_level_municipality()
print()
print("Finished.")
| {
"content_hash": "c2f6302f25713de4ade463e2c6909191",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 201,
"avg_line_length": 33.73571428571429,
"alnum_prop": 0.5763286047004023,
"repo_name": "bhzunami/Immo",
"id": "3cf07771c8711705c2182270f2f2557b1542cad0",
"size": "4723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "immo/crawler/crawler/scripts/gdaldata.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4084"
},
{
"name": "Jupyter Notebook",
"bytes": "894963"
},
{
"name": "PostScript",
"bytes": "736084"
},
{
"name": "Python",
"bytes": "235278"
},
{
"name": "Shell",
"bytes": "1283"
},
{
"name": "TeX",
"bytes": "171788"
}
],
"symlink_target": ""
} |
class YarhBase:
def __init__(self, parent):
self.parent = parent
def html(self):
raise NotImplementedError()
def yarh(self):
raise NotImplementedError()
def findparent(self, **kwargs):
keys = ["type"]
findable = False
for kwarg in kwargs:
if kwarg in keys:
findable = True
break
if not findable:
return self.parent
# type
if isinstance(self.parent, kwargs["type"]):
return self.parent
elif self.parent:
return self.parent.findparent(**kwargs)
# i have no parent...
return None
| {
"content_hash": "4e02ce551291cb4a494dede52769c25b",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 51,
"avg_line_length": 24.925925925925927,
"alnum_prop": 0.5289747399702823,
"repo_name": "minacle/yarh",
"id": "621a34615835ede211e3f56d2be53bfd970231a9",
"size": "673",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "yarh/base.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "18155"
}
],
"symlink_target": ""
} |
import warnings
from unittest import skipUnless
from django.conf import settings as django_settings
from django.utils.encoding import force_str
from mezzanine.conf import register_setting, registry, settings
from mezzanine.conf.context_processors import TemplateSettings
from mezzanine.conf.models import Setting
from mezzanine.utils.tests import TestCase
class ConfTests(TestCase):
@skipUnless(False, "Only run manually - see Github issue #1126")
def test_threading_race(self):
import multiprocessing.pool
import random
from django.db import connections
type_modifiers = {
int: lambda s: s + 1,
float: lambda s: s + 1.0,
bool: lambda s: not s,
str: lambda s: s + "test",
bytes: lambda s: s + b"test",
}
# Store a non-default value for every editable setting in the database
editable_settings = {}
for setting in registry.values():
if setting["editable"]:
modified = type_modifiers[setting["type"]](setting["default"])
Setting.objects.create(name=setting["name"], value=modified)
editable_settings[setting["name"]] = modified
# Make our child threads use this thread's connections. Recent SQLite
# do support access from multiple threads for in-memory databases, but
# Django doesn't support it currently - so we have to resort to this
# workaround, taken from Django's LiveServerTestCase.
# See Django ticket #12118 for discussion.
connections_override = {}
for conn in connections.all():
# If using in-memory sqlite databases, pass the connections to
# the server thread.
if conn.vendor == "sqlite" and conn.settings_dict["NAME"] == ":memory:":
# Explicitly enable thread-shareability for this connection
conn._old_allow_thread_sharing = conn.allow_thread_sharing
conn.allow_thread_sharing = True
connections_override[conn.alias] = conn
def initialise_thread():
for alias, connection in connections_override.items():
connections[alias] = connection
thread_pool = multiprocessing.pool.ThreadPool(8, initialise_thread)
def retrieve_setting(setting_name):
return setting_name, getattr(settings, setting_name)
def choose_random_setting(length=5000):
choices = list(editable_settings)
for _ in range(length):
yield random.choice(choices)
try:
for setting in thread_pool.imap_unordered(
retrieve_setting, choose_random_setting()
):
name, retrieved_value = setting
self.assertEqual(retrieved_value, editable_settings[name])
finally:
for conn in connections_override.values():
conn.allow_thread_sharing = conn._old_allow_thread_sharing
del conn._old_allow_thread_sharing
Setting.objects.all().delete()
def test_settings(self):
"""
Test that an editable setting can be overridden with a DB
value and that the data type is preserved when the value is
returned back out of the DB. Also checks to ensure no
unsupported types are defined for editable settings.
"""
settings.clear_cache()
# Find an editable setting for each supported type.
names_by_type = {}
for setting in registry.values():
if setting["editable"] and setting["type"] not in names_by_type:
names_by_type[setting["type"]] = setting["name"]
# Create a modified value for each setting and save it.
values_by_name = {}
for (setting_type, setting_name) in names_by_type.items():
setting_value = registry[setting_name]["default"]
if setting_type in (int, float):
setting_value += 1
elif setting_type is bool:
setting_value = not setting_value
elif setting_type is str:
setting_value += "test"
elif setting_type is bytes:
setting_value += b"test"
else:
setting = f"{setting_name}: {setting_type}"
self.fail("Unsupported setting type for %s" % setting)
values_by_name[setting_name] = setting_value
Setting.objects.create(name=setting_name, value=setting_value)
# Load the settings and make sure the DB values have persisted.
for (name, value) in values_by_name.items():
self.assertEqual(getattr(settings, name), value)
def test_editable_override(self):
"""
Test that an editable setting is always overridden by a settings.py
setting of the same name.
"""
settings.clear_cache()
Setting.objects.all().delete()
django_settings.FOO = "Set in settings.py"
Setting.objects.create(name="FOO", value="Set in database")
first_value = settings.FOO
settings.SITE_TITLE # Triggers access?
second_value = settings.FOO
self.assertEqual(first_value, second_value)
def test_invalid_value_warning(self):
"""
Test that a warning is raised when a database setting has an invalid
value, i.e. one that can't be converted to the correct Python type.
"""
settings.clear_cache()
register_setting(name="INVALID_INT_SETTING", editable=True, default=0)
Setting.objects.create(name="INVALID_INT_SETTING", value="zero")
with warnings.catch_warnings():
warning_re = r"The setting \w+ should be of type"
warnings.filterwarnings("error", warning_re, UserWarning)
with self.assertRaises(UserWarning):
settings.INVALID_INT_SETTING
self.assertEqual(settings.INVALID_INT_SETTING, 0)
def test_unregistered_setting(self):
"""
Test that accessing any editable setting will delete all Settings
with no corresponding registered setting from the database.
"""
settings.clear_cache()
register_setting(name="REGISTERED_SETTING", editable=True, default="")
Setting.objects.create(name="UNREGISTERED_SETTING", value="")
with self.assertRaises(AttributeError):
settings.UNREGISTERED_SETTING
qs = Setting.objects.filter(name="UNREGISTERED_SETTING")
self.assertEqual(qs.count(), 1)
# This triggers Settings._load(), which deletes unregistered Settings
settings.REGISTERED_SETTING
self.assertEqual(qs.count(), 0)
def test_conflicting_setting(self):
"""
Test that conflicting settings raise a warning and use the settings.py
value instead of the value from the database.
"""
settings.clear_cache()
register_setting(name="CONFLICTING_SETTING", editable=True, default=1)
Setting.objects.create(name="CONFLICTING_SETTING", value=2)
settings.CONFLICTING_SETTING = 3
with warnings.catch_warnings():
warning_re = (
"These settings are defined in both " r"settings\.py and the database"
)
warnings.filterwarnings("error", warning_re, UserWarning)
with self.assertRaises(UserWarning):
settings.CONFLICTING_SETTING
self.assertEqual(settings.CONFLICTING_SETTING, 3)
del settings.CONFLICTING_SETTING
def test_modeltranslation_configuration(self):
"""
Test that modeltranslation is properly configured in settings.
"""
if settings.USE_MODELTRANSLATION:
self.assertTrue(settings.USE_I18N)
def test_editable_caching(self):
"""
Test the editable setting caching behavior.
"""
# Ensure usage with no current request does not break caching
from mezzanine.core.request import _thread_local
try:
del _thread_local.request
except AttributeError:
pass
setting = Setting.objects.create(name="SITE_TITLE", value="Mezzanine")
original_site_title = settings.SITE_TITLE
setting.value = "Foobar"
setting.save()
new_site_title = settings.SITE_TITLE
setting.delete()
self.assertNotEqual(original_site_title, new_site_title)
class TemplateSettingsTests(TestCase):
def test_allowed(self):
# We choose a setting that will definitely exist:
ts = TemplateSettings(settings, ["INSTALLED_APPS"])
self.assertEqual(ts.INSTALLED_APPS, settings.INSTALLED_APPS)
self.assertEqual(ts["INSTALLED_APPS"], settings.INSTALLED_APPS)
def test_not_allowed(self):
ts = TemplateSettings(settings, [])
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.assertRaises(AttributeError, lambda: ts.INSTALLED_APPS)
self.assertRaises(KeyError, lambda: ts["INSTALLED_APPS"])
def test_add(self):
ts = TemplateSettings(settings, ["INSTALLED_APPS"])
ts["EXTRA_THING"] = "foo"
self.assertEqual(ts.EXTRA_THING, "foo")
self.assertEqual(ts["EXTRA_THING"], "foo")
def test_repr(self):
ts = TemplateSettings(settings, [])
self.assertEqual(repr(ts), "{}")
ts2 = TemplateSettings(settings, ["DEBUG", "SOME_NON_EXISTANT_SETTING"])
self.assertIn("'DEBUG': False", repr(ts2))
ts3 = TemplateSettings(settings, [])
ts3["EXTRA_THING"] = "foo"
self.assertIn("'EXTRA_THING'", repr(ts3))
self.assertIn("'foo'", repr(ts3))
def test_force_str(self):
ts = TemplateSettings(settings, [])
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
self.assertEqual(force_str(ts), "{}")
self.assertEqual(len(w), 0)
| {
"content_hash": "61b2103ee3fc3b03c563de98f95b0af1",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 86,
"avg_line_length": 38.58461538461538,
"alnum_prop": 0.6218102073365231,
"repo_name": "jerivas/mezzanine",
"id": "177ebe5eb503079eaf0f01a150c891e72a8028d3",
"size": "10032",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tests/test_conf.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "59995"
},
{
"name": "HTML",
"bytes": "79264"
},
{
"name": "JavaScript",
"bytes": "453209"
},
{
"name": "Python",
"bytes": "700821"
}
],
"symlink_target": ""
} |
from cloudkitty import transformer
class GnocchiTransformer(transformer.BaseTransformer):
def __init__(self):
pass
def _generic_strip(self, data):
res_data = {
'resource_id': data['id'],
'project_id': data['project_id'],
'user_id': data['user_id'],
'metrics': data['metrics']}
return res_data
def _strip_compute(self, data):
res_data = self._generic_strip(data)
res_data.update({
'instance_id': data['id'],
'project_id': data['project_id'],
'user_id': data['user_id'],
'name': data['display_name'],
'flavor_id': data['flavor_id']})
if 'image_ref' in data:
res_data['image_id'] = data.rpartition['image_ref'][-1]
return res_data
def _strip_image(self, data):
res_data = self._generic_strip(data)
res_data.update({
'container_format': data['container_format'],
'disk_format': data['disk_format']})
return res_data
def _strip_volume(self, data):
res_data = self._generic_strip(data)
res_data.update({
'name': data['display_name']})
return res_data
def _strip_network(self, data):
res_data = self._generic_strip(data)
res_data.update({
'name': data['name']})
return res_data
def strip_resource_data(self, res_type, res_data):
if res_type == 'compute':
return self._strip_compute(res_data)
elif res_type == 'image':
return self._strip_image(res_data)
elif res_type == 'volume':
return self._strip_volume(res_data)
elif res_type.startswith('network.'):
return self._strip_network(res_data)
else:
return self._generic_strip(res_data)
| {
"content_hash": "d19234f0f5668c9bfe2269f5cffb3f7b",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 67,
"avg_line_length": 32.6140350877193,
"alnum_prop": 0.5416890801506186,
"repo_name": "muraliselva10/cloudkitty",
"id": "3445db52581c69a237ee7e4be53ba60af1e76aef",
"size": "2491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cloudkitty/transformer/gnocchi.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Python",
"bytes": "526205"
},
{
"name": "Shell",
"bytes": "12562"
}
],
"symlink_target": ""
} |
from django.apps import AppConfig
class ArticlesAppConfig(AppConfig):
name = 'articles'
label = 'articles'
verbose_name = "Articles"
| {
"content_hash": "e3a9e4848eb9413730cd24b7eaee4395",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 35,
"avg_line_length": 21,
"alnum_prop": 0.7074829931972789,
"repo_name": "albertoconnor/website",
"id": "c851ece3758574f6feb837c44557091f8ef4823d",
"size": "147",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "articles/apps.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26874"
},
{
"name": "HTML",
"bytes": "90495"
},
{
"name": "JavaScript",
"bytes": "13768"
},
{
"name": "Python",
"bytes": "254428"
},
{
"name": "Shell",
"bytes": "985"
}
],
"symlink_target": ""
} |
"""Policy Engine For Heat"""
from oslo.config import cfg
from heat.common import exception
from heat.openstack.common import policy
CONF = cfg.CONF
DEFAULT_RULES = {
'default': policy.FalseCheck(),
}
class Enforcer(object):
"""Responsible for loading and enforcing rules."""
def __init__(self, scope='heat', exc=exception.Forbidden,
default_rule=DEFAULT_RULES['default']):
self.scope = scope
self.exc = exc
self.default_rule = default_rule
self.enforcer = policy.Enforcer(default_rule=default_rule)
def set_rules(self, rules, overwrite=True):
"""Create a new Rules object based on the provided dict of rules."""
rules_obj = policy.Rules(rules, self.default_rule)
self.enforcer.set_rules(rules_obj, overwrite)
def load_rules(self, force_reload=False):
"""Set the rules found in the json file on disk."""
self.enforcer.load_rules(force_reload)
def _check(self, context, rule, target, exc, *args, **kwargs):
"""Verifies that the action is valid on the target in this context.
:param context: Heat request context
:param rule: String representing the action to be checked
:param target: Dictionary representing the object of the action.
:raises: self.exc (defaults to heat.common.exception.Forbidden)
:returns: A non-False value if access is allowed.
"""
do_raise = False if not exc else True
credentials = context.to_dict()
return self.enforcer.enforce(rule, target, credentials,
do_raise, exc=exc, *args, **kwargs)
def enforce(self, context, action, scope=None, target=None):
"""Verifies that the action is valid on the target in this context.
:param context: Heat request context
:param action: String representing the action to be checked
:param target: Dictionary representing the object of the action.
:raises: self.exc (defaults to heat.common.exception.Forbidden)
:returns: A non-False value if access is allowed.
"""
_action = '%s:%s' % (scope or self.scope, action)
_target = target or {}
return self._check(context, _action, _target, self.exc, action=action)
def check_is_admin(self, context):
"""Whether or not roles contains 'admin' role according to policy.json
:param context: Heat request context
:returns: A non-False value if the user is admin according to policy
"""
return self._check(context, 'context_is_admin', target={}, exc=None)
| {
"content_hash": "55d98c65ee878ff04072105b635de946",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 79,
"avg_line_length": 39.13235294117647,
"alnum_prop": 0.6388575723412251,
"repo_name": "redhat-openstack/heat",
"id": "01a4338c76707245b2bef02fb32a8a9aaab523e1",
"size": "3335",
"binary": false,
"copies": "1",
"ref": "refs/heads/f22-patches",
"path": "heat/common/policy.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "4827027"
},
{
"name": "Shell",
"bytes": "26720"
}
],
"symlink_target": ""
} |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes import generic
from taggit.models import ItemBase as TaggitItemBase
from autoslug import AutoSlugField
from openbudget.settings.base import AUTH_USER_MODEL
from openbudget.apps.sheets.models import Template, TemplateNode
from openbudget.commons.mixins.models import TimeStampedModel, UUIDModel
from openbudget.commons.data import OBJECT_STATES
# Our models need to implement tags like so:
# labels = TaggableManager(through=TaggedNode)
class Taxonomy(TimeStampedModel, UUIDModel):
user = models.ForeignKey(
AUTH_USER_MODEL,
related_name='taxonomies'
)
template = models.ForeignKey(
Template,
related_name='taxonomies'
)
name = models.CharField(
max_length=255,
unique=True,
help_text=_('The name of this taxonomy.')
)
description = models.TextField(
_('Taxonomy description'),
blank=True,
help_text=_('Describe the purpose and goals of this taxonomy.')
)
status = models.IntegerField(
_('Publication status'),
choices=OBJECT_STATES,
default=1,
help_text=_('Determines whether the taxonomy is publically viewable.')
)
slug = AutoSlugField(
populate_from='name',
unique=True
)
@property
def count(self):
value = self.tags.count()
return value
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('taxonomy_detail', [self.slug])
@classmethod
def get_class_name(cls):
value = cls.__name__.lower()
return value
class Meta:
verbose_name = _("Taxonomy")
verbose_name_plural = _("Taxonomies")
unique_together = (
('user', 'name', 'template'),
)
class TagManager(models.Manager):
def get_queryset(self):
taxonomy = Taxonomy.objects.get(
slug=self.kwargs['taxonomy_slug']
)
return super(TagManager, self).get_queryset().filter(
taxonomy=taxonomy,
slug=self.kwargs['taxonomy_slug']
)
class Tag(models.Model):
"""A tag with full unicode support."""
taxonomy = models.ForeignKey(
Taxonomy,
related_name='tags'
)
name = models.CharField(
_('Name'),
max_length=100
)
slug = AutoSlugField(
populate_from='name',
unique=False
)
@models.permalink
def get_absolute_url(self):
return ('tag_detail', [self.taxonomy.slug, self.slug])
def __unicode__(self):
return self.name
class Meta:
verbose_name = _("Tag")
verbose_name_plural = _("Tags")
unique_together = (
('name', 'taxonomy'),
)
class TaggedNode(TaggitItemBase):
tag = models.ForeignKey(
Tag,
related_name='nodetags'
)
content_object = models.ForeignKey(
TemplateNode,
related_name='nodetags'
)
@classmethod
def tags_for(cls, model, instance=None):
ct = generic.ContentType.objects.get_for_model(model)
kwargs = {
"%s__content_type" % cls.tag_relname(): ct
}
if instance is not None:
kwargs["%s__object_id" % cls.tag_relname()] = instance.pk
return cls.tag_model().objects.filter(**kwargs).distinct()
class Meta:
verbose_name = _("Tagged node")
verbose_name_plural = _("Tagged nodes")
unique_together = (
('tag', 'content_object'),
)
| {
"content_hash": "f8955dc50862f823d3b02eaeeed2acc5",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 78,
"avg_line_length": 24.66891891891892,
"alnum_prop": 0.6020268419611066,
"repo_name": "zbyufei/open-budgets",
"id": "3f8d10db23042c935db90f0a28087e51b6a5fae7",
"size": "3651",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "openbudget/apps/taxonomies/models.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
from py4j.java_gateway import get_method
from typing import Union
from pyflink.java_gateway import get_gateway
from pyflink.table import ExplainDetail
from pyflink.table.expression import Expression, _get_java_expression
from pyflink.table.expressions import col, with_columns, without_columns
from pyflink.table.serializers import ArrowSerializer
from pyflink.table.table_descriptor import TableDescriptor
from pyflink.table.table_result import TableResult
from pyflink.table.table_schema import TableSchema
from pyflink.table.types import create_arrow_schema
from pyflink.table.udf import UserDefinedScalarFunctionWrapper, \
UserDefinedAggregateFunctionWrapper, UserDefinedTableFunctionWrapper
from pyflink.table.utils import tz_convert_from_internal, to_expression_jarray
from pyflink.table.window import OverWindow, GroupWindow
from pyflink.util.java_utils import to_jarray
from pyflink.util.java_utils import to_j_explain_detail_arr
__all__ = ['Table', 'GroupedTable', 'GroupWindowedTable', 'OverWindowedTable', 'WindowGroupedTable']
class Table(object):
"""
A :class:`~pyflink.table.Table` is the core component of the Table API.
Similar to how the DataStream API has DataStream,
the Table API is built around :class:`~pyflink.table.Table`.
Use the methods of :class:`~pyflink.table.Table` to transform data.
Example:
::
>>> env = StreamExecutionEnvironment.get_execution_environment()
>>> env.set_parallelism(1)
>>> t_env = StreamTableEnvironment.create(env)
>>> ...
>>> t_env.register_table_source("source", ...)
>>> t = t_env.from_path("source")
>>> t.select(...)
>>> ...
>>> t_env.register_table_sink("result", ...)
>>> t.execute_insert("result")
Operations such as :func:`~pyflink.table.Table.join`, :func:`~pyflink.table.Table.select`,
:func:`~pyflink.table.Table.where` and :func:`~pyflink.table.Table.group_by`
take arguments in an expression string. Please refer to the documentation for
the expression syntax.
"""
def __init__(self, j_table, t_env):
self._j_table = j_table
self._t_env = t_env
def __str__(self):
return self._j_table.toString()
def __getattr__(self, name) -> Expression:
"""
Returns the :class:`Expression` of the column `name`.
Example:
::
>>> tab.select(tab.a)
"""
if name not in self.get_schema().get_field_names():
raise AttributeError(
"The current table has no column named '%s', available columns: [%s]"
% (name, ', '.join(self.get_schema().get_field_names())))
return col(name)
def select(self, *fields: Union[str, Expression]) -> 'Table':
"""
Performs a selection operation. Similar to a SQL SELECT statement. The field expressions
can contain complex expressions.
Example:
::
>>> from pyflink.table import expressions as expr
>>> tab.select(tab.key, expr.concat(tab.value, 'hello'))
>>> tab.select(expr.col('key'), expr.concat(expr.col('value'), 'hello'))
>>> tab.select("key, value + 'hello'")
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.select(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.select(fields[0]), self._t_env)
def alias(self, field: str, *fields: str) -> 'Table':
"""
Renames the fields of the expression result. Use this to disambiguate fields before
joining two tables.
Example:
::
>>> tab.alias("a", "b", "c")
>>> tab.alias("a, b, c")
:param field: Field alias.
:param fields: Additional field aliases.
:return: The result table.
"""
gateway = get_gateway()
extra_fields = to_jarray(gateway.jvm.String, fields)
return Table(get_method(self._j_table, "as")(field, extra_fields), self._t_env)
def filter(self, predicate: Union[str, Expression[bool]]) -> 'Table':
"""
Filters out elements that don't pass the filter predicate. Similar to a SQL WHERE
clause.
Example:
::
>>> tab.filter(tab.name == 'Fred')
>>> tab.filter("name = 'Fred'")
:param predicate: Predicate expression string.
:return: The result table.
"""
return Table(self._j_table.filter(_get_java_expression(predicate)), self._t_env)
def where(self, predicate: Union[str, Expression[bool]]) -> 'Table':
"""
Filters out elements that don't pass the filter predicate. Similar to a SQL WHERE
clause.
Example:
::
>>> tab.where(tab.name == 'Fred')
>>> tab.where("name = 'Fred'")
:param predicate: Predicate expression string.
:return: The result table.
"""
return Table(self._j_table.where(_get_java_expression(predicate)), self._t_env)
def group_by(self, *fields: Union[str, Expression]) -> 'GroupedTable':
"""
Groups the elements on some grouping keys. Use this before a selection with aggregations
to perform the aggregation on a per-group basis. Similar to a SQL GROUP BY statement.
Example:
::
>>> tab.group_by(tab.key).select(tab.key, tab.value.avg)
>>> tab.group_by("key").select("key, value.avg")
:param fields: Group keys.
:return: The grouped table.
"""
if all(isinstance(f, Expression) for f in fields):
return GroupedTable(self._j_table.groupBy(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return GroupedTable(self._j_table.groupBy(fields[0]), self._t_env)
def distinct(self) -> 'Table':
"""
Removes duplicate values and returns only distinct (different) values.
Example:
::
>>> tab.select(tab.key, tab.value).distinct()
:return: The result table.
"""
return Table(self._j_table.distinct(), self._t_env)
def join(self, right: 'Table', join_predicate: Union[str, Expression[bool]] = None):
"""
Joins two :class:`~pyflink.table.Table`. Similar to a SQL join. The fields of the two joined
operations must not overlap, use :func:`~pyflink.table.Table.alias` to rename fields if
necessary. You can use where and select clauses after a join to further specify the
behaviour of the join.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment` .
Example:
::
>>> left.join(right).where((left.a == right.b) && (left.c > 3))
>>> left.join(right).where("a = b && c > 3")
>>> left.join(right, left.a == right.b)
:param right: Right table.
:param join_predicate: Optional, the join predicate expression string.
:return: The result table.
"""
if join_predicate is not None:
return Table(self._j_table.join(
right._j_table, _get_java_expression(join_predicate)), self._t_env)
else:
return Table(self._j_table.join(right._j_table), self._t_env)
def left_outer_join(self,
right: 'Table',
join_predicate: Union[str, Expression[bool]] = None) -> 'Table':
"""
Joins two :class:`~pyflink.table.Table`. Similar to a SQL left outer join. The fields of
the two joined operations must not overlap, use :func:`~pyflink.table.Table.alias` to
rename fields if necessary.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment` and its
:class:`~pyflink.table.TableConfig` must have null check enabled (default).
Example:
::
>>> left.left_outer_join(right)
>>> left.left_outer_join(right, left.a == right.b)
>>> left.left_outer_join(right, "a = b")
:param right: Right table.
:param join_predicate: Optional, the join predicate expression string.
:return: The result table.
"""
if join_predicate is None:
return Table(self._j_table.leftOuterJoin(right._j_table), self._t_env)
else:
return Table(self._j_table.leftOuterJoin(
right._j_table, _get_java_expression(join_predicate)), self._t_env)
def right_outer_join(self,
right: 'Table',
join_predicate: Union[str, Expression[bool]]) -> 'Table':
"""
Joins two :class:`~pyflink.table.Table`. Similar to a SQL right outer join. The fields of
the two joined operations must not overlap, use :func:`~pyflink.table.Table.alias` to
rename fields if necessary.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment` and its
:class:`~pyflink.table.TableConfig` must have null check enabled (default).
Example:
::
>>> left.right_outer_join(right, left.a == right.b)
>>> left.right_outer_join(right, "a = b")
:param right: Right table.
:param join_predicate: The join predicate expression string.
:return: The result table.
"""
return Table(self._j_table.rightOuterJoin(
right._j_table, _get_java_expression(join_predicate)), self._t_env)
def full_outer_join(self,
right: 'Table',
join_predicate: Union[str, Expression[bool]]) -> 'Table':
"""
Joins two :class:`~pyflink.table.Table`. Similar to a SQL full outer join. The fields of
the two joined operations must not overlap, use :func:`~pyflink.table.Table.alias` to
rename fields if necessary.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment` and its
:class:`~pyflink.table.TableConfig` must have null check enabled (default).
Example:
::
>>> left.full_outer_join(right, left.a == right.b)
>>> left.full_outer_join(right, "a = b")
:param right: Right table.
:param join_predicate: The join predicate expression string.
:return: The result table.
"""
return Table(self._j_table.fullOuterJoin(
right._j_table, _get_java_expression(join_predicate)), self._t_env)
def join_lateral(self,
table_function_call: Union[str, Expression, UserDefinedTableFunctionWrapper],
join_predicate: Union[str, Expression[bool]] = None) -> 'Table':
"""
Joins this Table with an user-defined TableFunction. This join is similar to a SQL inner
join but works with a table function. Each row of the table is joined with the rows
produced by the table function.
Example:
::
>>> t_env.create_java_temporary_system_function("split",
... "java.table.function.class.name")
>>> tab.join_lateral("split(text, ' ') as (b)", "a = b")
>>> from pyflink.table import expressions as expr
>>> tab.join_lateral(expr.call('split', ' ').alias('b'), expr.col('a') == expr.col('b'))
>>> # take all the columns as inputs
>>> @udtf(result_types=[DataTypes.INT(), DataTypes.STRING()])
... def split_row(row: Row):
... for s in row[1].split(","):
... yield row[0], s
>>> tab.join_lateral(split_row.alias("a", "b"))
:param table_function_call: An expression representing a table function call.
:param join_predicate: Optional, The join predicate expression string, join ON TRUE if not
exist.
:return: The result Table.
"""
if isinstance(table_function_call, UserDefinedTableFunctionWrapper):
table_function_call._set_takes_row_as_input()
if hasattr(table_function_call, "_alias_names"):
alias_names = getattr(table_function_call, "_alias_names")
table_function_call = table_function_call(with_columns(col("*"))) \
.alias(*alias_names)
else:
raise AttributeError('table_function_call must be followed by a alias function'
'e.g. table_function.alias("a", "b")')
if join_predicate is None:
return Table(self._j_table.joinLateral(
_get_java_expression(table_function_call)), self._t_env)
else:
return Table(self._j_table.joinLateral(
_get_java_expression(table_function_call),
_get_java_expression(join_predicate)),
self._t_env)
def left_outer_join_lateral(self,
table_function_call: Union[str, Expression,
UserDefinedTableFunctionWrapper],
join_predicate: Union[str, Expression[bool]] = None) -> 'Table':
"""
Joins this Table with an user-defined TableFunction. This join is similar to
a SQL left outer join but works with a table function. Each row of the table is joined
with all rows produced by the table function. If the join does not produce any row, the
outer row is padded with nulls.
Example:
::
>>> t_env.create_java_temporary_system_function("split",
... "java.table.function.class.name")
>>> tab.left_outer_join_lateral("split(text, ' ') as (b)")
>>> from pyflink.table import expressions as expr
>>> tab.left_outer_join_lateral(expr.call('split', ' ').alias('b'))
>>> # take all the columns as inputs
>>> @udtf(result_types=[DataTypes.INT(), DataTypes.STRING()])
... def split_row(row: Row):
... for s in row[1].split(","):
... yield row[0], s
>>> tab.left_outer_join_lateral(split_row.alias("a", "b"))
:param table_function_call: An expression representing a table function call.
:param join_predicate: Optional, The join predicate expression string, join ON TRUE if not
exist.
:return: The result Table.
"""
if isinstance(table_function_call, UserDefinedTableFunctionWrapper):
table_function_call._set_takes_row_as_input()
if hasattr(table_function_call, "_alias_names"):
alias_names = getattr(table_function_call, "_alias_names")
table_function_call = table_function_call(with_columns(col("*"))) \
.alias(*alias_names)
else:
raise AttributeError('table_function_call must be followed by a alias function'
'e.g. table_function.alias("a", "b")')
if join_predicate is None:
return Table(self._j_table.leftOuterJoinLateral(
_get_java_expression(table_function_call)), self._t_env)
else:
return Table(self._j_table.leftOuterJoinLateral(
_get_java_expression(table_function_call),
_get_java_expression(join_predicate)),
self._t_env)
def minus(self, right: 'Table') -> 'Table':
"""
Minus of two :class:`~pyflink.table.Table` with duplicate records removed.
Similar to a SQL EXCEPT clause. Minus returns records from the left table that do not
exist in the right table. Duplicate records in the left table are returned
exactly once, i.e., duplicates are removed. Both tables must have identical field types.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment`.
Example:
::
>>> left.minus(right)
:param right: Right table.
:return: The result table.
"""
return Table(self._j_table.minus(right._j_table), self._t_env)
def minus_all(self, right: 'Table') -> 'Table':
"""
Minus of two :class:`~pyflink.table.Table`. Similar to a SQL EXCEPT ALL.
Similar to a SQL EXCEPT ALL clause. MinusAll returns the records that do not exist in
the right table. A record that is present n times in the left table and m times
in the right table is returned (n - m) times, i.e., as many duplicates as are present
in the right table are removed. Both tables must have identical field types.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment`.
Example:
::
>>> left.minus_all(right)
:param right: Right table.
:return: The result table.
"""
return Table(self._j_table.minusAll(right._j_table), self._t_env)
def union(self, right: 'Table') -> 'Table':
"""
Unions two :class:`~pyflink.table.Table` with duplicate records removed.
Similar to a SQL UNION. The fields of the two union operations must fully overlap.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment`.
Example:
::
>>> left.union(right)
:param right: Right table.
:return: The result table.
"""
return Table(self._j_table.union(right._j_table), self._t_env)
def union_all(self, right: 'Table') -> 'Table':
"""
Unions two :class:`~pyflink.table.Table`. Similar to a SQL UNION ALL. The fields of the
two union operations must fully overlap.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment`.
Example:
::
>>> left.union_all(right)
:param right: Right table.
:return: The result table.
"""
return Table(self._j_table.unionAll(right._j_table), self._t_env)
def intersect(self, right: 'Table') -> 'Table':
"""
Intersects two :class:`~pyflink.table.Table` with duplicate records removed. Intersect
returns records that exist in both tables. If a record is present in one or both tables
more than once, it is returned just once, i.e., the resulting table has no duplicate
records. Similar to a SQL INTERSECT. The fields of the two intersect operations must fully
overlap.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment`.
Example:
::
>>> left.intersect(right)
:param right: Right table.
:return: The result table.
"""
return Table(self._j_table.intersect(right._j_table), self._t_env)
def intersect_all(self, right: 'Table') -> 'Table':
"""
Intersects two :class:`~pyflink.table.Table`. IntersectAll returns records that exist in
both tables. If a record is present in both tables more than once, it is returned as many
times as it is present in both tables, i.e., the resulting table might have duplicate
records. Similar to an SQL INTERSECT ALL. The fields of the two intersect operations must
fully overlap.
.. note::
Both tables must be bound to the same :class:`~pyflink.table.TableEnvironment`.
Example:
::
>>> left.intersect_all(right)
:param right: Right table.
:return: The result table.
"""
return Table(self._j_table.intersectAll(right._j_table), self._t_env)
def order_by(self, *fields: Union[str, Expression]) -> 'Table':
"""
Sorts the given :class:`~pyflink.table.Table`. Similar to SQL ORDER BY.
The resulting Table is sorted globally sorted across all parallel partitions.
Example:
::
>>> tab.order_by(tab.name.desc)
>>> tab.order_by("name.desc")
For unbounded tables, this operation requires a sorting on a time attribute or a subsequent
fetch operation.
:param fields: Order fields expression string.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.orderBy(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.orderBy(fields[0]), self._t_env)
def offset(self, offset: int) -> 'Table':
"""
Limits a (possibly sorted) result from an offset position.
This method can be combined with a preceding :func:`~pyflink.table.Table.order_by` call for
a deterministic order and a subsequent :func:`~pyflink.table.Table.fetch` call to return n
rows after skipping the first o rows.
Example:
::
# skips the first 3 rows and returns all following rows.
>>> tab.order_by(tab.name.desc).offset(3)
>>> tab.order_by("name.desc").offset(3)
# skips the first 10 rows and returns the next 5 rows.
>>> tab.order_by(tab.name.desc).offset(10).fetch(5)
For unbounded tables, this operation requires a subsequent fetch operation.
:param offset: Number of records to skip.
:return: The result table.
"""
return Table(self._j_table.offset(offset), self._t_env)
def fetch(self, fetch: int) -> 'Table':
"""
Limits a (possibly sorted) result to the first n rows.
This method can be combined with a preceding :func:`~pyflink.table.Table.order_by` call for
a deterministic order and :func:`~pyflink.table.Table.offset` call to return n rows after
skipping the first o rows.
Example:
Returns the first 3 records.
::
>>> tab.order_by(tab.name.desc).fetch(3)
>>> tab.order_by("name.desc").fetch(3)
Skips the first 10 rows and returns the next 5 rows.
::
>>> tab.order_by(tab.name.desc).offset(10).fetch(5)
:param fetch: The number of records to return. Fetch must be >= 0.
:return: The result table.
"""
return Table(self._j_table.fetch(fetch), self._t_env)
def limit(self, fetch: int, offset: int = 0) -> 'Table':
"""
Limits a (possibly sorted) result to the first n rows.
This method is a synonym for :func:`~pyflink.table.Table.offset` followed by
:func:`~pyflink.table.Table.fetch`.
Example:
Returns the first 3 records.
::
>>> tab.limit(3)
Skips the first 10 rows and returns the next 5 rows.
::
>>> tab.limit(5, 10)
:param fetch: the first number of rows to fetch.
:param offset: the number of records to skip, default 0.
:return: The result table.
"""
return self.offset(offset).fetch(fetch)
def window(self, window: GroupWindow) -> 'GroupWindowedTable':
"""
Defines group window on the records of a table.
A group window groups the records of a table by assigning them to windows defined by a time
or row interval.
For streaming tables of infinite size, grouping into windows is required to define finite
groups on which group-based aggregates can be computed.
For batch tables of finite size, windowing essentially provides shortcuts for time-based
groupBy.
.. note::
Computing windowed aggregates on a streaming table is only a parallel operation
if additional grouping attributes are added to the
:func:`~pyflink.table.GroupWindowedTable.group_by` clause.
If the :func:`~pyflink.table.GroupWindowedTable.group_by` only references a GroupWindow
alias, the streamed table will be processed by a single task, i.e., with parallelism 1.
Example:
::
>>> from pyflink.table import expressions as expr
>>> tab.window(Tumble.over(expr.lit(10).minutes).on(tab.rowtime).alias('w')) \\
... .group_by(col('w')) \\
... .select(tab.a.sum.alias('a'),
... col('w').start.alias('b'),
... col('w').end.alias('c'),
... col('w').rowtime.alias('d'))
:param window: A :class:`~pyflink.table.window.GroupWindow` created from
:class:`~pyflink.table.window.Tumble`, :class:`~pyflink.table.window.Session`
or :class:`~pyflink.table.window.Slide`.
:return: A group windowed table.
"""
return GroupWindowedTable(self._j_table.window(window._java_window), self._t_env)
def over_window(self, *over_windows: OverWindow) -> 'OverWindowedTable':
"""
Defines over-windows on the records of a table.
An over-window defines for each record an interval of records over which aggregation
functions can be computed.
Example:
::
>>> from pyflink.table import expressions as expr
>>> tab.over_window(Over.partition_by(tab.c).order_by(tab.rowtime) \\
... .preceding(lit(10).seconds).alias("ow")) \\
... .select(tab.c, tab.b.count.over(col('ow'), tab.e.sum.over(col('ow'))))
.. note::
Computing over window aggregates on a streaming table is only a parallel
operation if the window is partitioned. Otherwise, the whole stream will be processed
by a single task, i.e., with parallelism 1.
.. note::
Over-windows for batch tables are currently not supported.
:param over_windows: over windows created from :class:`~pyflink.table.window.Over`.
:return: A over windowed table.
"""
gateway = get_gateway()
window_array = to_jarray(gateway.jvm.OverWindow,
[item._java_over_window for item in over_windows])
return OverWindowedTable(self._j_table.window(window_array), self._t_env)
def add_columns(self, *fields: Union[str, Expression]) -> 'Table':
"""
Adds additional columns. Similar to a SQL SELECT statement. The field expressions
can contain complex expressions, but can not contain aggregations. It will throw an
exception if the added fields already exist.
Example:
::
>>> from pyflink.table import expressions as expr
>>> tab.add_columns((tab.a + 1).alias('a1'), expr.concat(tab.b, 'sunny').alias('b1'))
>>> tab.add_columns("a + 1 as a1, concat(b, 'sunny') as b1")
:param fields: Column list string.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.addColumns(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.addColumns(fields[0]), self._t_env)
def add_or_replace_columns(self, *fields: Union[str, Expression]) -> 'Table':
"""
Adds additional columns. Similar to a SQL SELECT statement. The field expressions
can contain complex expressions, but can not contain aggregations. Existing fields will be
replaced if add columns name is the same as the existing column name. Moreover, if the added
fields have duplicate field name, then the last one is used.
Example:
::
>>> from pyflink.table import expressions as expr
>>> tab.add_or_replace_columns((tab.a + 1).alias('a1'),
... expr.concat(tab.b, 'sunny').alias('b1'))
>>> tab.add_or_replace_columns("a + 1 as a1, concat(b, 'sunny') as b1")
:param fields: Column list string.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.addOrReplaceColumns(to_expression_jarray(fields)),
self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.addOrReplaceColumns(fields[0]), self._t_env)
def rename_columns(self, *fields: Union[str, Expression]) -> 'Table':
"""
Renames existing columns. Similar to a field alias statement. The field expressions
should be alias expressions, and only the existing fields can be renamed.
Example:
::
>>> tab.rename_columns(tab.a.alias('a1'), tab.b.alias('b1'))
>>> tab.rename_columns("a as a1, b as b1")
:param fields: Column list string.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.renameColumns(to_expression_jarray(fields)),
self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.renameColumns(fields[0]), self._t_env)
def drop_columns(self, *fields: Union[str, Expression]) -> 'Table':
"""
Drops existing columns. The field expressions should be field reference expressions.
Example:
::
>>> tab.drop_columns(tab.a, tab.b)
>>> tab.drop_columns("a, b")
:param fields: Column list string.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.dropColumns(to_expression_jarray(fields)),
self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.dropColumns(fields[0]), self._t_env)
def map(self, func: Union[str, Expression, UserDefinedScalarFunctionWrapper]) -> 'Table':
"""
Performs a map operation with a user-defined scalar function.
Example:
::
>>> add = udf(lambda x: Row(x + 1, x * x), result_type=DataTypes.Row(
... [DataTypes.FIELD("a", DataTypes.INT()), DataTypes.FIELD("b", DataTypes.INT())]))
>>> tab.map(add(tab.a)).alias("a, b")
>>> # take all the columns as inputs
>>> identity = udf(lambda row: row, result_type=DataTypes.Row(
... [DataTypes.FIELD("a", DataTypes.INT()), DataTypes.FIELD("b", DataTypes.INT())]))
>>> tab.map(identity)
:param func: user-defined scalar function.
:return: The result table.
.. versionadded:: 1.13.0
"""
if isinstance(func, str):
return Table(self._j_table.map(func), self._t_env)
elif isinstance(func, Expression):
return Table(self._j_table.map(func._j_expr), self._t_env)
else:
func._set_takes_row_as_input()
return Table(self._j_table.map(func(with_columns(col("*")))._j_expr), self._t_env)
def flat_map(self, func: Union[str, Expression, UserDefinedTableFunctionWrapper]) -> 'Table':
"""
Performs a flatMap operation with a user-defined table function.
Example:
::
>>> @udtf(result_types=[DataTypes.INT(), DataTypes.STRING()])
... def split(x, string):
... for s in string.split(","):
... yield x, s
>>> tab.flat_map(split(tab.a, table.b))
>>> # take all the columns as inputs
>>> @udtf(result_types=[DataTypes.INT(), DataTypes.STRING()])
... def split_row(row: Row):
... for s in row[1].split(","):
... yield row[0], s
>>> tab.flat_map(split_row)
:param func: user-defined table function.
:return: The result table.
.. versionadded:: 1.13.0
"""
if isinstance(func, str):
return Table(self._j_table.flatMap(func), self._t_env)
elif isinstance(func, Expression):
return Table(self._j_table.flatMap(func._j_expr), self._t_env)
else:
func._set_takes_row_as_input()
return Table(self._j_table.flatMap(func(with_columns(col("*")))._j_expr), self._t_env)
def aggregate(self, func: Union[str, Expression, UserDefinedAggregateFunctionWrapper]) \
-> 'AggregatedTable':
"""
Performs a global aggregate operation with an aggregate function. You have to close the
aggregate with a select statement.
Example:
::
>>> agg = udaf(lambda a: (a.mean(), a.max()),
... result_type=DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.FLOAT()),
... DataTypes.FIELD("b", DataTypes.INT())]),
... func_type="pandas")
>>> tab.aggregate(agg(tab.a).alias("a", "b")).select("a, b")
>>> # take all the columns as inputs
>>> # pd is a Pandas.DataFrame
>>> agg_row = udaf(lambda pd: (pd.a.mean(), pd.a.max()),
... result_type=DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.FLOAT()),
... DataTypes.FIELD("b", DataTypes.INT())]),
... func_type="pandas")
>>> tab.aggregate(agg.alias("a, b")).select("a, b")
:param func: user-defined aggregate function.
:return: The result table.
.. versionadded:: 1.13.0
"""
if isinstance(func, str):
return AggregatedTable(self._j_table.aggregate(func), self._t_env)
elif isinstance(func, Expression):
return AggregatedTable(self._j_table.aggregate(func._j_expr), self._t_env)
else:
func._set_takes_row_as_input()
if hasattr(func, "_alias_names"):
alias_names = getattr(func, "_alias_names")
func = func(with_columns(col("*"))).alias(*alias_names)
else:
func = func(with_columns(col("*")))
return AggregatedTable(self._j_table.aggregate(func._j_expr), self._t_env)
def flat_aggregate(self, func: Union[str, Expression, UserDefinedAggregateFunctionWrapper]) \
-> 'FlatAggregateTable':
"""
Perform a global flat_aggregate without group_by. flat_aggregate takes a
:class:`~pyflink.table.TableAggregateFunction` which returns multiple rows. Use a selection
after the flat_aggregate.
Example:
::
>>> table_agg = udtaf(MyTableAggregateFunction())
>>> tab.flat_aggregate(table_agg(tab.a).alias("a", "b")).select("a, b")
>>> # take all the columns as inputs
>>> class Top2(TableAggregateFunction):
... def emit_value(self, accumulator):
... yield Row(accumulator[0])
... yield Row(accumulator[1])
...
... def create_accumulator(self):
... return [None, None]
...
... def accumulate(self, accumulator, *args):
... args[0] # type: Row
... if args[0][0] is not None:
... if accumulator[0] is None or args[0][0] > accumulator[0]:
... accumulator[1] = accumulator[0]
... accumulator[0] = args[0][0]
... elif accumulator[1] is None or args[0][0] > accumulator[1]:
... accumulator[1] = args[0][0]
...
... def get_accumulator_type(self):
... return DataTypes.ARRAY(DataTypes.BIGINT())
...
... def get_result_type(self):
... return DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.BIGINT())])
>>> top2 = udtaf(Top2())
>>> tab.flat_aggregate(top2.alias("a", "b")).select("a, b")
:param func: user-defined table aggregate function.
:return: The result table.
.. versionadded:: 1.13.0
"""
if isinstance(func, str):
return FlatAggregateTable(self._j_table.flatAggregate(func), self._t_env)
elif isinstance(func, Expression):
return FlatAggregateTable(self._j_table.flatAggregate(func._j_expr), self._t_env)
else:
func._set_takes_row_as_input()
if hasattr(func, "_alias_names"):
alias_names = getattr(func, "_alias_names")
func = func(with_columns(col("*"))).alias(*alias_names)
else:
func = func(with_columns(col("*")))
return FlatAggregateTable(self._j_table.flatAggregate(func._j_expr), self._t_env)
def to_pandas(self):
"""
Converts the table to a pandas DataFrame. It will collect the content of the table to
the client side and so please make sure that the content of the table could fit in memory
before calling this method.
Example:
::
>>> pdf = pd.DataFrame(np.random.rand(1000, 2))
>>> table = table_env.from_pandas(pdf, ["a", "b"])
>>> table.filter(table.a > 0.5).to_pandas()
:return: the result pandas DataFrame.
.. versionadded:: 1.11.0
"""
self._t_env._before_execute()
gateway = get_gateway()
max_arrow_batch_size = self._j_table.getTableEnvironment().getConfig().getConfiguration()\
.getInteger(gateway.jvm.org.apache.flink.python.PythonOptions.MAX_ARROW_BATCH_SIZE)
batches_iterator = gateway.jvm.org.apache.flink.table.runtime.arrow.ArrowUtils\
.collectAsPandasDataFrame(self._j_table, max_arrow_batch_size)
if batches_iterator.hasNext():
import pytz
timezone = pytz.timezone(
self._j_table.getTableEnvironment().getConfig().getLocalTimeZone().getId())
serializer = ArrowSerializer(
create_arrow_schema(self.get_schema().get_field_names(),
self.get_schema().get_field_data_types()),
self.get_schema().to_row_data_type(),
timezone)
import pyarrow as pa
table = pa.Table.from_batches(serializer.load_from_iterator(batches_iterator))
pdf = table.to_pandas()
schema = self.get_schema()
for field_name in schema.get_field_names():
pdf[field_name] = tz_convert_from_internal(
pdf[field_name], schema.get_field_data_type(field_name), timezone)
return pdf
else:
import pandas as pd
return pd.DataFrame.from_records([], columns=self.get_schema().get_field_names())
def get_schema(self) -> TableSchema:
"""
Returns the :class:`~pyflink.table.TableSchema` of this table.
:return: The schema of this table.
"""
return TableSchema(j_table_schema=self._j_table.getSchema())
def print_schema(self):
"""
Prints the schema of this table to the console in a tree format.
"""
self._j_table.printSchema()
def execute_insert(self,
table_path_or_descriptor: Union[str, TableDescriptor],
overwrite: bool = False) -> TableResult:
"""
1. When target_path_or_descriptor is a tale path:
Writes the :class:`~pyflink.table.Table` to a :class:`~pyflink.table.TableSink` that was
registered under the specified name, and then execute the insert operation. For the path
resolution algorithm see :func:`~TableEnvironment.use_database`.
Example:
::
>>> tab.execute_insert("sink")
2. When target_path_or_descriptor is a table descriptor:
Declares that the pipeline defined by the given Table object should be written to a
table (backed by a DynamicTableSink) expressed via the given TableDescriptor. It
executes the insert operation.
TableDescriptor is registered as an inline (i.e. anonymous) temporary catalog table
(see :func:`~TableEnvironment.create_temporary_table`) using a unique identifier.
Note that calling this method multiple times, even with the same descriptor, results
in multiple sink tables being registered.
This method allows to declare a :class:`~pyflink.table.Schema` for the sink descriptor.
The declaration is similar to a {@code CREATE TABLE} DDL in SQL and allows to:
1. overwrite automatically derived columns with a custom DataType
2. add metadata columns next to the physical columns
3. declare a primary key
It is possible to declare a schema without physical/regular columns. In this case, those
columns will be automatically derived and implicitly put at the beginning of the schema
declaration.
Examples:
::
>>> schema = Schema.new_builder()
... .column("f0", DataTypes.STRING())
... .build()
>>> table = table_env.from_descriptor(TableDescriptor.for_connector("datagen")
... .schema(schema)
... .build())
>>> table.execute_insert(TableDescriptor.for_connector("blackhole")
... .schema(schema)
... .build())
If multiple pipelines should insert data into one or more sink tables as part of a
single execution, use a :class:`~pyflink.table.StatementSet`
(see :func:`~TableEnvironment.create_statement_set`).
By default, all insertion operations are executed asynchronously. Use
:func:`~TableResult.await` or :func:`~TableResult.get_job_client` to monitor the
execution.
.. note:: execute_insert for a table descriptor (case 2.) was added from
flink 1.14.0.
:param table_path_or_descriptor: The path of the registered
:class:`~pyflink.table.TableSink` or the descriptor describing the sink table into which
data should be inserted to which the :class:`~pyflink.table.Table` is written.
:param overwrite: Indicates whether the insert should overwrite existing data or not.
:return: The table result.
.. versionadded:: 1.11.0
"""
self._t_env._before_execute()
if isinstance(table_path_or_descriptor, str):
return TableResult(self._j_table.executeInsert(table_path_or_descriptor, overwrite))
else:
return TableResult(self._j_table.executeInsert(
table_path_or_descriptor._j_table_descriptor, overwrite))
def execute(self) -> TableResult:
"""
Collects the contents of the current table local client.
Example:
::
>>> tab.execute()
:return: The content of the table.
.. versionadded:: 1.11.0
"""
self._t_env._before_execute()
return TableResult(self._j_table.execute())
def explain(self, *extra_details: ExplainDetail) -> str:
"""
Returns the AST of this table and the execution plan.
:param extra_details: The extra explain details which the explain result should include,
e.g. estimated cost, changelog mode for streaming
:return: The statement for which the AST and execution plan will be returned.
.. versionadded:: 1.11.0
"""
j_extra_details = to_j_explain_detail_arr(extra_details)
return self._j_table.explain(j_extra_details)
class GroupedTable(object):
"""
A table that has been grouped on a set of grouping keys.
"""
def __init__(self, java_table, t_env):
self._j_table = java_table
self._t_env = t_env
def select(self, *fields: Union[str, Expression]) -> 'Table':
"""
Performs a selection operation on a grouped table. Similar to an SQL SELECT statement.
The field expressions can contain complex expressions and aggregations.
Example:
::
>>> tab.group_by(tab.key).select(tab.key, tab.value.avg.alias('average'))
>>> tab.group_by("key").select("key, value.avg as average")
:param fields: Expression string that contains group keys and aggregate function calls.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.select(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.select(fields[0]), self._t_env)
def aggregate(self, func: Union[str, Expression, UserDefinedAggregateFunctionWrapper]) \
-> 'AggregatedTable':
"""
Performs a aggregate operation with an aggregate function. You have to close the
aggregate with a select statement.
Example:
::
>>> agg = udaf(lambda a: (a.mean(), a.max()),
... result_type=DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.FLOAT()),
... DataTypes.FIELD("b", DataTypes.INT())]),
... func_type="pandas")
>>> tab.group_by(tab.a).aggregate(agg(tab.b).alias("c", "d")).select("a, c, d")
>>> # take all the columns as inputs
>>> # pd is a Pandas.DataFrame
>>> agg_row = udaf(lambda pd: (pd.a.mean(), pd.b.max()),
... result_type=DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.FLOAT()),
... DataTypes.FIELD("b", DataTypes.INT())]),
... func_type="pandas")
>>> tab.group_by(tab.a).aggregate(agg.alias("a, b")).select("a, b")
:param func: user-defined aggregate function.
:return: The result table.
.. versionadded:: 1.13.0
"""
if isinstance(func, str):
return AggregatedTable(self._j_table.aggregate(func), self._t_env)
elif isinstance(func, Expression):
return AggregatedTable(self._j_table.aggregate(func._j_expr), self._t_env)
else:
func._set_takes_row_as_input()
if hasattr(func, "_alias_names"):
alias_names = getattr(func, "_alias_names")
func = func(with_columns(col("*"))).alias(*alias_names)
else:
func = func(with_columns(col("*")))
return AggregatedTable(self._j_table.aggregate(func._j_expr), self._t_env)
def flat_aggregate(self, func: Union[str, Expression, UserDefinedAggregateFunctionWrapper]) \
-> 'FlatAggregateTable':
"""
Performs a flat_aggregate operation on a grouped table. flat_aggregate takes a
:class:`~pyflink.table.TableAggregateFunction` which returns multiple rows. Use a selection
after flatAggregate.
Example:
::
>>> table_agg = udtaf(MyTableAggregateFunction())
>>> tab.group_by(tab.c).flat_aggregate(table_agg(tab.a).alias("a")).select("c, a")
>>> # take all the columns as inputs
>>> class Top2(TableAggregateFunction):
... def emit_value(self, accumulator):
... yield Row(accumulator[0])
... yield Row(accumulator[1])
...
... def create_accumulator(self):
... return [None, None]
...
... def accumulate(self, accumulator, *args):
... args[0] # type: Row
... if args[0][0] is not None:
... if accumulator[0] is None or args[0][0] > accumulator[0]:
... accumulator[1] = accumulator[0]
... accumulator[0] = args[0][0]
... elif accumulator[1] is None or args[0][0] > accumulator[1]:
... accumulator[1] = args[0][0]
...
... def get_accumulator_type(self):
... return DataTypes.ARRAY(DataTypes.BIGINT())
...
... def get_result_type(self):
... return DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.BIGINT())])
>>> top2 = udtaf(Top2())
>>> tab.group_by(tab.c).flat_aggregate(top2.alias("a", "b")).select("a, b")
:param func: user-defined table aggregate function.
:return: The result table.
.. versionadded:: 1.13.0
"""
if isinstance(func, str):
return FlatAggregateTable(self._j_table.flatAggregate(func), self._t_env)
elif isinstance(func, Expression):
return FlatAggregateTable(self._j_table.flatAggregate(func._j_expr), self._t_env)
else:
func._set_takes_row_as_input()
if hasattr(func, "_alias_names"):
alias_names = getattr(func, "_alias_names")
func = func(with_columns(col("*"))).alias(*alias_names)
else:
func = func(with_columns(col("*")))
return FlatAggregateTable(self._j_table.flatAggregate(func._j_expr), self._t_env)
class GroupWindowedTable(object):
"""
A table that has been windowed for :class:`~pyflink.table.GroupWindow`.
"""
def __init__(self, java_group_windowed_table, t_env):
self._j_table = java_group_windowed_table
self._t_env = t_env
def group_by(self, *fields: Union[str, Expression]) -> 'WindowGroupedTable':
"""
Groups the elements by a mandatory window and one or more optional grouping attributes.
The window is specified by referring to its alias.
If no additional grouping attribute is specified and if the input is a streaming table,
the aggregation will be performed by a single task, i.e., with parallelism 1.
Aggregations are performed per group and defined by a subsequent
:func:`~pyflink.table.WindowGroupedTable.select` clause similar to SQL SELECT-GROUP-BY
query.
Example:
::
>>> from pyflink.table import expressions as expr
>>> tab.window(Tumble.over(expr.lit(10).minutes).on(tab.rowtime).alias('w')) \\
... .group_by(col('w')) \\
... .select(tab.a.sum.alias('a'),
... col('w').start.alias('b'),
... col('w').end.alias('c'),
... col('w').rowtime.alias('d'))
:param fields: Group keys.
:return: A window grouped table.
"""
if all(isinstance(f, Expression) for f in fields):
return WindowGroupedTable(
self._j_table.groupBy(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return WindowGroupedTable(self._j_table.groupBy(fields[0]), self._t_env)
class WindowGroupedTable(object):
"""
A table that has been windowed and grouped for :class:`~pyflink.table.window.GroupWindow`.
"""
def __init__(self, java_window_grouped_table, t_env):
self._j_table = java_window_grouped_table
self._t_env = t_env
def select(self, *fields: Union[str, Expression]) -> 'Table':
"""
Performs a selection operation on a window grouped table. Similar to an SQL SELECT
statement.
The field expressions can contain complex expressions and aggregations.
Example:
::
>>> window_grouped_table.select(col('key'),
... col('window').start,
... col('value').avg.alias('valavg'))
>>> window_grouped_table.select("key, window.start, value.avg as valavg")
:param fields: Expression string.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.select(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.select(fields[0]), self._t_env)
def aggregate(self, func: Union[str, Expression, UserDefinedAggregateFunctionWrapper]) \
-> 'AggregatedTable':
"""
Performs an aggregate operation on a window grouped table. You have to close the
aggregate with a select statement.
Example:
::
>>> agg = udaf(lambda a: (a.mean(), a.max()),
... result_type=DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.FLOAT()),
... DataTypes.FIELD("b", DataTypes.INT())]),
... func_type="pandas")
>>> window_grouped_table.group_by("w") \
... .aggregate(agg(window_grouped_table.b) \
... .alias("c", "d")) \
... .select("c, d")
>>> # take all the columns as inputs
>>> # pd is a Pandas.DataFrame
>>> agg_row = udaf(lambda pd: (pd.a.mean(), pd.b.max()),
... result_type=DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.FLOAT()),
... DataTypes.FIELD("b", DataTypes.INT())]),
... func_type="pandas")
>>> window_grouped_table.group_by("w, a").aggregate(agg_row)
:param func: user-defined aggregate function.
:return: The result table.
.. versionadded:: 1.13.0
"""
if isinstance(func, str):
return AggregatedTable(self._j_table.aggregate(func), self._t_env)
elif isinstance(func, Expression):
return AggregatedTable(self._j_table.aggregate(func._j_expr), self._t_env)
else:
func._set_takes_row_as_input()
func = self._to_expr(func)
return AggregatedTable(self._j_table.aggregate(func._j_expr), self._t_env)
def _to_expr(self, func: UserDefinedAggregateFunctionWrapper) -> Expression:
group_window_field = self._j_table.getClass().getDeclaredField("window")
group_window_field.setAccessible(True)
j_group_window = group_window_field.get(self._j_table)
j_time_field = j_group_window.getTimeField()
fields_without_window = without_columns(j_time_field)
if hasattr(func, "_alias_names"):
alias_names = getattr(func, "_alias_names")
func_expression = func(fields_without_window).alias(*alias_names)
else:
func_expression = func(fields_without_window)
return func_expression
class OverWindowedTable(object):
"""
A table that has been windowed for :class:`~pyflink.table.window.OverWindow`.
Unlike group windows, which are specified in the GROUP BY clause, over windows do not collapse
rows. Instead over window aggregates compute an aggregate for each input row over a range of
its neighboring rows.
"""
def __init__(self, java_over_windowed_table, t_env):
self._j_table = java_over_windowed_table
self._t_env = t_env
def select(self, *fields: Union[str, Expression]) -> 'Table':
"""
Performs a selection operation on a over windowed table. Similar to an SQL SELECT
statement.
The field expressions can contain complex expressions and aggregations.
Example:
::
>>> over_windowed_table.select(col('c'),
... col('b').count.over(col('ow')),
... col('e').sum.over(col('ow')))
>>> over_windowed_table.select("c, b.count over ow, e.sum over ow")
:param fields: Expression string.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.select(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.select(fields[0]), self._t_env)
class AggregatedTable(object):
"""
A table that has been performed on the aggregate function.
"""
def __init__(self, java_table, t_env):
self._j_table = java_table
self._t_env = t_env
def select(self, *fields: Union[str, Expression]) -> 'Table':
"""
Performs a selection operation after an aggregate operation. The field expressions
cannot contain table functions and aggregations.
Example:
""
>>> agg = udaf(lambda a: (a.mean(), a.max()),
... result_type=DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.FLOAT()),
... DataTypes.FIELD("b", DataTypes.INT())]),
... func_type="pandas")
>>> tab.aggregate(agg(tab.a).alias("a", "b")).select("a, b")
>>> # take all the columns as inputs
>>> # pd is a Pandas.DataFrame
>>> agg_row = udaf(lambda pd: (pd.a.mean(), pd.b.max()),
... result_type=DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.FLOAT()),
... DataTypes.FIELD("b", DataTypes.INT())]),
... func_type="pandas")
>>> tab.group_by(tab.a).aggregate(agg.alias("a, b")).select("a, b")
:param fields: Expression string.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.select(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.select(fields[0]), self._t_env)
class FlatAggregateTable(object):
"""
A table that performs flatAggregate on a :class:`~pyflink.table.Table`, a
:class:`~pyflink.table.GroupedTable` or a :class:`~pyflink.table.WindowGroupedTable`
"""
def __init__(self, java_table, t_env):
self._j_table = java_table
self._t_env = t_env
def select(self, *fields: Union[str, Expression]) -> 'Table':
"""
Performs a selection operation on a FlatAggregateTable. Similar to a SQL SELECT statement.
The field expressions can contain complex expressions.
Example:
::
>>> table_agg = udtaf(MyTableAggregateFunction())
>>> tab.flat_aggregate(table_agg(tab.a).alias("a", "b")).select("a, b")
>>> # take all the columns as inputs
>>> class Top2(TableAggregateFunction):
... def emit_value(self, accumulator):
... yield Row(accumulator[0])
... yield Row(accumulator[1])
...
... def create_accumulator(self):
... return [None, None]
...
... def accumulate(self, accumulator, *args):
... args[0] # type: Row
... if args[0][0] is not None:
... if accumulator[0] is None or args[0][0] > accumulator[0]:
... accumulator[1] = accumulator[0]
... accumulator[0] = args[0][0]
... elif accumulator[1] is None or args[0][0] > accumulator[1]:
... accumulator[1] = args[0][0]
...
... def get_accumulator_type(self):
... return DataTypes.ARRAY(DataTypes.BIGINT())
...
... def get_result_type(self):
... return DataTypes.ROW(
... [DataTypes.FIELD("a", DataTypes.BIGINT())])
>>> top2 = udtaf(Top2())
>>> tab.group_by(tab.c).flat_aggregate(top2.alias("a", "b")).select("a, b")
:param fields: Expression string.
:return: The result table.
"""
if all(isinstance(f, Expression) for f in fields):
return Table(self._j_table.select(to_expression_jarray(fields)), self._t_env)
else:
assert len(fields) == 1
assert isinstance(fields[0], str)
return Table(self._j_table.select(fields[0]), self._t_env)
| {
"content_hash": "c36401210d2db7f9dc0ff053fd592a08",
"timestamp": "",
"source": "github",
"line_count": 1499,
"max_line_length": 100,
"avg_line_length": 41.19546364242829,
"alnum_prop": 0.5659411840912035,
"repo_name": "twalthr/flink",
"id": "484d7583a72f6f6cf5e3f08565d8e851abb74e1d",
"size": "62711",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "flink-python/pyflink/table/table.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "20596"
},
{
"name": "Batchfile",
"bytes": "1863"
},
{
"name": "C",
"bytes": "847"
},
{
"name": "Clojure",
"bytes": "84752"
},
{
"name": "Cython",
"bytes": "130650"
},
{
"name": "Dockerfile",
"bytes": "5563"
},
{
"name": "FreeMarker",
"bytes": "92068"
},
{
"name": "GAP",
"bytes": "139514"
},
{
"name": "HTML",
"bytes": "154937"
},
{
"name": "HiveQL",
"bytes": "119074"
},
{
"name": "Java",
"bytes": "91868014"
},
{
"name": "JavaScript",
"bytes": "7038"
},
{
"name": "Less",
"bytes": "68979"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "2518003"
},
{
"name": "Scala",
"bytes": "10732536"
},
{
"name": "Shell",
"bytes": "525376"
},
{
"name": "TypeScript",
"bytes": "311274"
},
{
"name": "q",
"bytes": "9630"
}
],
"symlink_target": ""
} |
from flask import Flask, redirect, url_for, request, jsonify, abort
import sqlite3
import nmap
import time
import storage
app = Flask(__name__)
@app.route('/')
def index():
return redirect(url_for('static', filename='index.html'))
@app.route('/getActiveNames')
def getActiveNames():
activeUsers = storage.getActiveUsers(30*60)
return jsonify(activeUsers)
@app.route('/saveName')
def saveName():
remoteIp = request.remote_addr;
name = request.args.get('userName')
if not remoteIp.startswith("192.168"):
abort(400)
store(name, remoteIp)
return ''
def store(name, ip):
ip2mac = getIp2Mac()
if not ip in ip2mac:
return
storage.saveUsername(name, ip2mac[ip])
def getIp2Mac():
ip2mac = {}
f = open('/proc/net/arp', 'r')
for line in f:
parts = line.split()
if parts[0] == 'IP':
continue
ip2mac[parts[0]] = parts[3]
f.close()
return ip2mac
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True)
| {
"content_hash": "1a2f87fc12560e74c8629a32b1cdd193",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 67,
"avg_line_length": 20.127659574468087,
"alnum_prop": 0.6775898520084567,
"repo_name": "m-philipp/mac-disco",
"id": "ec60964ce31fe789174f6e7b2a8fce8571762677",
"size": "962",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flaskServer.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "677"
},
{
"name": "HTML",
"bytes": "5391"
},
{
"name": "JavaScript",
"bytes": "452504"
},
{
"name": "Python",
"bytes": "3744"
},
{
"name": "Shell",
"bytes": "71"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from datetime import timedelta
from sqlalchemy import DDL
from sqlalchemy.event import listens_for
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm.base import NEVER_SET, NO_VALUE
from indico.core.db import db
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.core.db.sqlalchemy.util.models import populate_one_to_one_backrefs
from indico.util.date_time import overlaps
from indico.util.i18n import _
from indico.util.locators import locator_property
from indico.util.string import format_repr, return_ascii
from indico.util.struct.enum import RichIntEnum
class TimetableEntryType(RichIntEnum):
__titles__ = [None, _("Session Block"), _("Contribution"), _("Break")]
# entries are uppercase since `break` is a keyword...
SESSION_BLOCK = 1
CONTRIBUTION = 2
BREAK = 3
def _make_check(type_, *cols):
all_cols = {'session_block_id', 'contribution_id', 'break_id'}
required_cols = all_cols & set(cols)
forbidden_cols = all_cols - required_cols
criteria = ['{} IS NULL'.format(col) for col in sorted(forbidden_cols)]
criteria += ['{} IS NOT NULL'.format(col) for col in sorted(required_cols)]
condition = 'type != {} OR ({})'.format(type_, ' AND '.join(criteria))
return db.CheckConstraint(condition, 'valid_{}'.format(type_.name.lower()))
class TimetableEntry(db.Model):
__tablename__ = 'timetable_entries'
@declared_attr
def __table_args__(cls):
return (db.Index('ix_timetable_entries_start_dt_desc', cls.start_dt.desc()),
_make_check(TimetableEntryType.SESSION_BLOCK, 'session_block_id'),
_make_check(TimetableEntryType.CONTRIBUTION, 'contribution_id'),
_make_check(TimetableEntryType.BREAK, 'break_id'),
db.CheckConstraint("type != {} OR parent_id IS NULL".format(TimetableEntryType.SESSION_BLOCK),
'valid_parent'),
{'schema': 'events'})
id = db.Column(
db.Integer,
primary_key=True
)
event_id = db.Column(
db.Integer,
db.ForeignKey('events.events.id'),
index=True,
nullable=False
)
parent_id = db.Column(
db.Integer,
db.ForeignKey('events.timetable_entries.id'),
index=True,
nullable=True,
)
session_block_id = db.Column(
db.Integer,
db.ForeignKey('events.session_blocks.id'),
index=True,
unique=True,
nullable=True
)
contribution_id = db.Column(
db.Integer,
db.ForeignKey('events.contributions.id'),
index=True,
unique=True,
nullable=True
)
break_id = db.Column(
db.Integer,
db.ForeignKey('events.breaks.id'),
index=True,
unique=True,
nullable=True
)
type = db.Column(
PyIntEnum(TimetableEntryType),
nullable=False
)
start_dt = db.Column(
UTCDateTime,
nullable=False
)
event = db.relationship(
'Event',
lazy=True,
backref=db.backref(
'timetable_entries',
order_by=lambda: TimetableEntry.start_dt,
cascade='all, delete-orphan',
lazy='dynamic'
)
)
session_block = db.relationship(
'SessionBlock',
lazy=False,
backref=db.backref(
'timetable_entry',
cascade='all, delete-orphan',
uselist=False,
lazy=True
)
)
contribution = db.relationship(
'Contribution',
lazy=False,
backref=db.backref(
'timetable_entry',
cascade='all, delete-orphan',
uselist=False,
lazy=True
)
)
break_ = db.relationship(
'Break',
cascade='all, delete-orphan',
single_parent=True,
lazy=False,
backref=db.backref(
'timetable_entry',
cascade='all, delete-orphan',
uselist=False,
lazy=True
)
)
children = db.relationship(
'TimetableEntry',
order_by='TimetableEntry.start_dt',
lazy=True,
backref=db.backref(
'parent',
remote_side=[id],
lazy=True
)
)
# relationship backrefs:
# - parent (TimetableEntry.children)
@property
def object(self):
if self.type == TimetableEntryType.SESSION_BLOCK:
return self.session_block
elif self.type == TimetableEntryType.CONTRIBUTION:
return self.contribution
elif self.type == TimetableEntryType.BREAK:
return self.break_
@object.setter
def object(self, value):
from indico.modules.events.contributions import Contribution
from indico.modules.events.sessions.models.blocks import SessionBlock
from indico.modules.events.timetable.models.breaks import Break
self.session_block = self.contribution = self.break_ = None
if isinstance(value, SessionBlock):
self.session_block = value
elif isinstance(value, Contribution):
self.contribution = value
elif isinstance(value, Break):
self.break_ = value
elif value is not None:
raise TypeError('Unexpected object: {}'.format(value))
@hybrid_property
def duration(self):
return self.object.duration if self.object is not None else None
@duration.setter
def duration(self, value):
self.object.duration = value
@duration.expression
def duration(cls):
from indico.modules.events.contributions import Contribution
from indico.modules.events.sessions.models.blocks import SessionBlock
from indico.modules.events.timetable.models.breaks import Break
return db.case({
TimetableEntryType.SESSION_BLOCK.value:
db.select([SessionBlock.duration])
.where(SessionBlock.id == cls.session_block_id)
.correlate_except(SessionBlock)
.as_scalar(),
TimetableEntryType.CONTRIBUTION.value:
db.select([Contribution.duration])
.where(Contribution.id == cls.contribution_id)
.correlate_except(Contribution)
.as_scalar(),
TimetableEntryType.BREAK.value:
db.select([Break.duration])
.where(Break.id == cls.break_id)
.correlate_except(Break)
.as_scalar(),
}, value=cls.type)
@hybrid_property
def end_dt(self):
if self.start_dt is None or self.duration is None:
return None
return self.start_dt + self.duration
@end_dt.expression
def end_dt(cls):
return cls.start_dt + cls.duration
@property
def session_siblings(self):
if self.type == TimetableEntryType.SESSION_BLOCK:
return [x for x in self.siblings
if x.session_block and x.session_block.session == self.session_block.session]
elif self.parent:
return self.siblings
else:
return []
@property
def siblings(self):
from indico.modules.events.timetable.util import get_top_level_entries, get_nested_entries
tzinfo = self.event.tzinfo
day = self.start_dt.astimezone(tzinfo).date()
siblings = (get_nested_entries(self.event)[self.parent_id]
if self.parent_id else
get_top_level_entries(self.event))
return [x for x in siblings if x.start_dt.astimezone(tzinfo).date() == day and x.id != self.id]
@property
def siblings_query(self):
tzinfo = self.event.tzinfo
day = self.start_dt.astimezone(tzinfo).date()
criteria = (TimetableEntry.id != self.id,
TimetableEntry.parent == self.parent,
db.cast(TimetableEntry.start_dt.astimezone(tzinfo), db.Date) == day)
return TimetableEntry.query.with_parent(self.event).filter(*criteria)
@locator_property
def locator(self):
return dict(self.event.locator, entry_id=self.id)
@return_ascii
def __repr__(self):
return format_repr(self, 'id', 'type', 'start_dt', 'end_dt', _repr=self.object)
def can_view(self, user):
"""Checks whether the user will see this entry in the timetable."""
if self.type in (TimetableEntryType.CONTRIBUTION, TimetableEntryType.BREAK):
return self.object.can_access(user)
elif self.type == TimetableEntryType.SESSION_BLOCK:
if self.object.can_access(user):
return True
return any(x.can_access(user) for x in self.object.contributions)
def extend_start_dt(self, start_dt):
assert start_dt < self.start_dt
extension = self.start_dt - start_dt
self.start_dt = start_dt
self.duration = self.duration + extension
def extend_end_dt(self, end_dt):
diff = end_dt - self.end_dt
if diff < timedelta(0):
raise ValueError("New end_dt is before current end_dt.")
self.duration += diff
def extend_parent(self, by_start=True, by_end=True):
"""Extend start/end of parent objects if needed.
No extension if performed for entries crossing a day boundary in the
event timezone.
:param by_start: Extend parent by start datetime.
:param by_end: Extend parent by end datetime.
"""
tzinfo = self.event.tzinfo
if self.start_dt.astimezone(tzinfo).date() != self.end_dt.astimezone(tzinfo).date():
return
if self.parent is None:
if by_start and self.start_dt < self.event.start_dt:
self.event.start_dt = self.start_dt
if by_end and self.end_dt > self.event.end_dt:
self.event.end_dt = self.end_dt
else:
extended = False
if by_start and self.start_dt < self.parent.start_dt:
self.parent.extend_start_dt(self.start_dt)
extended = True
if by_end and self.end_dt > self.parent.end_dt:
self.parent.extend_end_dt(self.end_dt)
extended = True
if extended:
self.parent.extend_parent(by_start=by_start, by_end=by_end)
def is_parallel(self, in_session=False):
siblings = self.siblings if not in_session else self.session_siblings
for sibling in siblings:
if overlaps((self.start_dt, self.end_dt), (sibling.start_dt, sibling.end_dt)):
return True
return False
def move(self, start_dt):
"""Move the entry to start at a different time.
This method automatically moves children of the entry to
preserve their start time relative to the parent's start time.
"""
if self.type == TimetableEntryType.SESSION_BLOCK:
diff = start_dt - self.start_dt
for child in self.children:
child.start_dt += diff
self.start_dt = start_dt
def move_next_to(self, sibling, position='before'):
if sibling not in self.siblings:
raise ValueError("Not a sibling")
if position not in ('before', 'after'):
raise ValueError("Invalid position")
if position == 'before':
start_dt = sibling.start_dt - self.duration
else:
start_dt = sibling.end_dt
self.move(start_dt)
@listens_for(TimetableEntry.__table__, 'after_create')
def _add_timetable_consistency_trigger(target, conn, **kw):
sql = """
CREATE CONSTRAINT TRIGGER consistent_timetable
AFTER INSERT OR UPDATE
ON {}
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW
EXECUTE PROCEDURE events.check_timetable_consistency('timetable_entry');
""".format(target.fullname)
DDL(sql).execute(conn)
@listens_for(TimetableEntry.session_block, 'set')
def _set_session_block(target, value, *unused):
target.type = TimetableEntryType.SESSION_BLOCK
@listens_for(TimetableEntry.contribution, 'set')
def _set_contribution(target, value, *unused):
target.type = TimetableEntryType.CONTRIBUTION
@listens_for(TimetableEntry.break_, 'set')
def _set_break(target, value, *unused):
target.type = TimetableEntryType.BREAK
@listens_for(TimetableEntry.start_dt, 'set')
def _set_start_dt(target, value, oldvalue, *unused):
from indico.modules.events.util import register_time_change
if oldvalue in (NEVER_SET, NO_VALUE):
return
if value != oldvalue and target.object is not None:
register_time_change(target)
populate_one_to_one_backrefs(TimetableEntry, 'session_block', 'contribution', 'break_')
| {
"content_hash": "562daf073836c8b54341286c43d48245",
"timestamp": "",
"source": "github",
"line_count": 373,
"max_line_length": 110,
"avg_line_length": 34.5656836461126,
"alnum_prop": 0.6107189948033817,
"repo_name": "mvidalgarcia/indico",
"id": "2bfb49f12ac04b0c6f7e8225d49943f6e8ddd21f",
"size": "13107",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "indico/modules/events/timetable/models/entries.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "538590"
},
{
"name": "HTML",
"bytes": "1345380"
},
{
"name": "JavaScript",
"bytes": "1781971"
},
{
"name": "Mako",
"bytes": "1340"
},
{
"name": "Python",
"bytes": "4381847"
},
{
"name": "Shell",
"bytes": "3568"
},
{
"name": "TeX",
"bytes": "22182"
},
{
"name": "XSLT",
"bytes": "1504"
}
],
"symlink_target": ""
} |
"""Support for mounting images with qemu-nbd."""
import os
import random
import re
import time
from oslo.config import cfg
from nova.i18n import _, _LE
from nova.openstack.common import log as logging
from nova import utils
from nova.virt.disk.mount import api
LOG = logging.getLogger(__name__)
nbd_opts = [
cfg.IntOpt('timeout_nbd',
default=10,
help='Amount of time, in seconds, to wait for NBD '
'device start up.'),
]
CONF = cfg.CONF
CONF.register_opts(nbd_opts)
NBD_DEVICE_RE = re.compile('nbd[0-9]+')
class NbdMount(api.Mount):
"""qemu-nbd support disk images."""
mode = 'nbd'
def _detect_nbd_devices(self):
"""Detect nbd device files."""
return filter(NBD_DEVICE_RE.match, os.listdir('/sys/block/'))
def _find_unused(self, devices):
for device in devices:
if not os.path.exists(os.path.join('/sys/block/', device, 'pid')):
if not os.path.exists('/var/lock/qemu-nbd-%s' % device):
return device
else:
LOG.error(_LE('NBD error - previous umount did not '
'cleanup /var/lock/qemu-nbd-%s.'), device)
LOG.warn(_('No free nbd devices'))
return None
def _allocate_nbd(self):
if not os.path.exists('/sys/block/nbd0'):
LOG.error(_LE('nbd module not loaded'))
self.error = _('nbd unavailable: module not loaded')
return None
devices = self._detect_nbd_devices()
random.shuffle(devices)
device = self._find_unused(devices)
if not device:
# really want to log this info, not raise
self.error = _('No free nbd devices')
return None
return os.path.join('/dev', device)
@utils.synchronized('nbd-allocation-lock')
def _inner_get_dev(self):
device = self._allocate_nbd()
if not device:
return False
# NOTE(mikal): qemu-nbd will return an error if the device file is
# already in use.
LOG.debug('Get nbd device %(dev)s for %(imgfile)s',
{'dev': device, 'imgfile': self.image})
_out, err = utils.trycmd('qemu-nbd', '-c', device, self.image,
run_as_root=True)
if err:
self.error = _('qemu-nbd error: %s') % err
LOG.info(_('NBD mount error: %s'), self.error)
return False
# NOTE(vish): this forks into another process, so give it a chance
# to set up before continuing
pidfile = "/sys/block/%s/pid" % os.path.basename(device)
for _i in range(CONF.timeout_nbd):
if os.path.exists(pidfile):
self.device = device
break
time.sleep(1)
else:
self.error = _('nbd device %s did not show up') % device
LOG.info(_('NBD mount error: %s'), self.error)
# Cleanup
_out, err = utils.trycmd('qemu-nbd', '-d', device,
run_as_root=True)
if err:
LOG.warn(_('Detaching from erroneous nbd device returned '
'error: %s'), err)
return False
self.error = ''
self.linked = True
return True
def get_dev(self):
"""Retry requests for NBD devices."""
return self._get_dev_retry_helper()
def unget_dev(self):
if not self.linked:
return
LOG.debug('Release nbd device %s', self.device)
utils.execute('qemu-nbd', '-d', self.device, run_as_root=True)
self.linked = False
self.device = None
def flush_dev(self):
"""flush NBD block device buffer."""
# Perform an explicit BLKFLSBUF to support older qemu-nbd(s).
# Without this flush, when a nbd device gets re-used the
# qemu-nbd intermittently hangs.
if self.device:
utils.execute('blockdev', '--flushbufs',
self.device, run_as_root=True)
| {
"content_hash": "a2aa9211c1096b23776e8c96c68abbdd",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 78,
"avg_line_length": 33.096774193548384,
"alnum_prop": 0.5450779727095516,
"repo_name": "badock/nova",
"id": "2bc3b3e57e3416becd29b873efd48dbbfef5015a",
"size": "4677",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "nova/virt/disk/mount/nbd.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groff",
"bytes": "112"
},
{
"name": "PLpgSQL",
"bytes": "2958"
},
{
"name": "Python",
"bytes": "15441440"
},
{
"name": "Shell",
"bytes": "20796"
},
{
"name": "Smarty",
"bytes": "693857"
}
],
"symlink_target": ""
} |
import pyb, pwm
FORWARDS = 255
BACKWARDS = -FORWARDS
STOP = 0
#possible dcmotor configurations, depends on skin orientation
Y1 = {'enable_pin':pyb.Pin.board.Y8, 'enable_timer':12, 'enable_channel':2, 'control0':pyb.Pin.board.Y6,'control1':pyb.Pin.board.Y7}
Y2 = {'enable_pin':pyb.Pin.board.Y3, 'enable_timer':10, 'enable_channel':1, 'control0':pyb.Pin.board.Y2,'control1':pyb.Pin.board.Y1}
X1 = {'enable_pin':pyb.Pin.board.X8, 'enable_timer':14, 'enable_channel':1, 'control0':pyb.Pin.board.X6,'control1':pyb.Pin.board.X7}
X2 = {'enable_pin':pyb.Pin.board.X3, 'enable_timer':9, 'enable_channel':1, 'control0':pyb.Pin.board.X2,'control1':pyb.Pin.board.X1}
class DCMOTOR:
"""dirty DC Motor Class"""
def __init__(self, pins_dict, reverse_pols=False, pwm_freq=100):
self._enable_pin = pins_dict['enable_pin']
self._enable_timer = pins_dict['enable_timer']
self._enable_channel = pins_dict['enable_channel']
self._pwm_freq = pwm_freq
self._control0 = pins_dict['control0'] if not reverse_pols else pins_dict['control1']
self._control1 = pins_dict['control1'] if not reverse_pols else pins_dict['control0']
self._timer = pyb.Timer(self._enable_timer, freq=self._pwm_freq)
self._timer_channel = self._timer.channel(self._enable_channel, pyb.Timer, pin=self._enable_pin, pulse_width=0)
self._control0.init(pyb.Pin.OUT_PP)
self._control0.low()
self._control1.init(pyb.Pin.OUT_PP)
self._control1.low()
def state(self,value=None):
"""get or set motor state as -ve|0|+ve as backwards|stop|forwards"""
if value == None:
if self._pwm.duty() > 0:
if self._control0.value() and not self._control1.value():
return -self._pwm.duty()
elif not self._control0.value() and self._control1.value():
return self._pwm.duty()
else:
raise ValueError('Inconsistent state')
else:
return 0
elif value < 0:
self._control0.high()
self._control1.low()
self._pwm.duty(abs(value))
elif value > 0:
self._control0.low()
self._control1.high()
self._pwm.duty(value)
elif value == 0:
self._pwm.duty(0)
else:
raise ValueError('Invalid state value passed')
def backwards(self,value=-BACKWARDS):
self.state(-value)
def forwards(self,value=FORWARDS):
self.state(value)
def stop(self):
self.state(STOP)
def emergency_stop(self,brakes_for=50):
if self.state() != 0:
self._control0.value(int(not(self._control0.value())))
self._control1.value(int(not(self._control1.value())))
pyb.delay(brakes_for)
self.stop()
| {
"content_hash": "36819b83a8266d860425255912270df9",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 132,
"avg_line_length": 36.943661971830984,
"alnum_prop": 0.6504003049942814,
"repo_name": "PinkInk/upylib",
"id": "11554709d806e630b5173d1d12b09d8649cd634e",
"size": "2623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dcmotor/dcmotor_bak160220.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2998"
},
{
"name": "Python",
"bytes": "158212"
}
],
"symlink_target": ""
} |
import numpy
import colorsys
from scipy.ndimage.filters import gaussian_filter
from scipy.ndimage.morphology import distance_transform_edt
def rgb2hls(img):
copy = img.reshape(img.shape[0] * img.shape[1], img.shape[2])
converted = numpy.array([colorsys.rgb_to_hls(v[0]/255.0,v[1]/255.0,v[2]/255.0) for v in copy], dtype=numpy.float32)
return converted.reshape(img.shape[0], img.shape[1], img.shape[2])
def _convertHls2Rgb(hls):
rgb = colorsys.hls_to_rgb(*hls)
return tuple(int(v * 255.0) for v in rgb)
def hls2rgb(img):
copy = img.reshape(img.shape[0] * img.shape[1], img.shape[2])
output = numpy.array([_convertHls2Rgb(col) for col in copy], dtype=numpy.uint8)
return output.reshape(img.shape[0], img.shape[1], img.shape[2])
def blur(img, sigma):
output = img.astype(numpy.float32)
output[:,:,0] = gaussian_filter(img[:,:,0], sigma=sigma)
output[:,:,1] = gaussian_filter(img[:,:,1], sigma=sigma)
output[:,:,2] = gaussian_filter(img[:,:,2], sigma=sigma)
return output
def details(img):
smooth = blur(img, sigma=24.0)
diff = (img - smooth)
return diff
def distance(img):
return distance_transform_edt(img)
def normalized(array):
mn, mx = min(array.flatten()), max(array.flatten())
return (array - mn) / (mx - mn)
| {
"content_hash": "bafb6ebea9b079dee89b6b3dae305ae6",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 119,
"avg_line_length": 29.59090909090909,
"alnum_prop": 0.6612903225806451,
"repo_name": "alexjc/imgscaper",
"id": "968590010d8df45e2ede8a0df2999a75bf4f86c5",
"size": "1302",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ops.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "11389"
}
],
"symlink_target": ""
} |
import os.path
import re
# We need to ensure a local settings file is defined,
# thus no-one changes the settings file unless its a
# global change. Or at least changes the settings.tmpl file instead
try:
from .local_settings import *
except ImportError:
raise AssertionError("Local settings file not defined")
########################################
# Testing
########################################
TEST_RUNNER = "discover_runner.runner.DiscoverRunner"
# location of the tests folder
BASE_PATH = WEBDND_ROOT
TEST_DISCOVER_ROOT = os.path.join(WEBDND_ROOT)
TEST_DISCOVER_TOP_LEVEL = WEBDND_ROOT
# Regexp pattern to match when looking for test files
# The runner will look in these files for TestCase classes
TEST_DISCOVER_PATTERN = '*_test.py'
# format: 'major.minor.bug name'
VERSION = '0.3.0 BETA'
##################################################
# App settings
##################################################
ROOT_URLCONF = 'webdnd.urls'
INSTALLED_APPS = (
# User login and authentication
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Django Admin
'django.contrib.admin',
# 'django.contrib.admindocs',
# Webdnd apps
'webdnd.player',
# 'webdnd.dnd',
'webdnd.shared',
# Compression for static files
'compressor',
'django.contrib.staticfiles',
# Debug toolbar
'debug_toolbar',
# Syncrae: Tornado websockets app
'webdnd.syncrae',
# Alerts
'webdnd.alerts',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(DATABASE_ROOT, 'webdnd.sqlite3'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
},
}
# CharField
STND_CHAR_LIMIT = 100
STND_ID_CHAR_LIMIT = 5
ADMIN_CHAR_CUTOFF = 20
#DecimalField
STND_DECIMAL_PLACES = 3
# Fixtures
INITIAL_FIXTURE_DIRS = (
'player/fixtures',
)
# TODO: Prehaps we should get a cache?
##################################################
# Media and Static files
##################################################
# Absolute path to the directory that holds media.
MEDIA_ROOT = os.path.join(WEBDND_ROOT, 'media/')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
MEDIA_URL = '/media/'
# Absolute path to the directory that holds static files.
STATIC_ROOT = os.path.join(WEBDND_ROOT, 'static/')
# URL that handles the static files served from STATIC_ROOT.
STATIC_URL = '/static/'
# A list of locations of additional static files
STATICFILES_DIRS = (
('shared', os.path.join(WEBDND_ROOT, 'shared/static/')),
('alerts', os.path.join(WEBDND_ROOT, 'alerts/static/')),
('player', os.path.join(WEBDND_ROOT, 'player/static/')),
('syncrae', os.path.join(WEBDND_ROOT, 'syncrae/static/')),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
'compressor.finders.CompressorFinder',
)
# Parse to use for static file compression
COMPRESS_PARSER = 'compressor.parser.BeautifulSoupParser'
# Location of the static files
COMPRESS_ROOT = os.path.join(WEBDND_ROOT, 'static/')
COMPRESS_OUTPUT_DIR = '/compressed'
# COMPRESS_JS_FILTERS = ('compressor.filters.yui.YUIJSFilter',)
# COMPRESS_CSS_FILTERS = ('compressor.filters.yui.YUICSSFilter',)
COMPRESS_PRECOMPILERS = (
# CSS Pre-compilers
('text/less', 'lessc {infile} {outfile} --verbose'
# Prevent bad debug messages, e.g. [31m that form colors
+ (' --no-color' if DEBUG else '')
# Compress output on Prod
+ ('' if DEBUG else ' -x')
# Show line numbers in compiled code as comments
+ (' --line-numbers="comments"' if LESS_DEBUG else '')
),
# JS Pre-Compilers
# ('text/x-handlebars-template',
# 'handlebars {infile} --output {outfile}'
# Minimize compiled template in production
# + (' --min' if DEBUG else '')
# ),
# e.g. using classes
# ('text/foobar', 'path.to.MyPrecompilerFilter'),
# e.g.
# ('text/coffeescript', 'coffee --compile --stdio'),
)
# Locations of the template files
TEMPLATE_DIRS = (
os.path.join(WEBDND_ROOT, 'shared/templates'),
os.path.join(WEBDND_ROOT, 'player/templates'),
)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
# Functions which add onto the context before rendering a template
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
# alerts plugin
"alerts.alert.template_processor",
"alerts.highlighter.template_processor",
)
##################################################
# Login
##################################################
# How long cookies will last
SESSION_COOKIE_AGE = 60 * 60 * 24
SESSION_COOKIE_NAME = 'webdndID'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# Default url to redirect to for login
LOGIN_URL = '/account/login'
LOGIN_REDIRECT_URL = '/'
##################################################
# Contact info and TZ
##################################################
# Site breakdowns
ADMINS = ADMINS.extend([
# ('Dmitry Blotsky', 'dmitry.blotsky@gmail.com'),
])
# Broken links
MANAGERS = ADMINS
# email server emails are sent from
SERVER_EMAIL = ''
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Canada/Eastern'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-ca'
LANGUAGE_COOKIE_NAME = 'webdnd-language'
##################################################
# Logging
##################################################
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '[%(asctime)s] %(levelname)s - %(message)s - %(module)s@%(funcName)s %(lineno)s - %(process)d %(thread)d',
'datefmt': "%d/%b/%Y %H:%M:%S",
},
'simple': {
'format': '[%(asctime)s] %(levelname)s - %(message)s - %(module)s@%(funcName)s %(lineno)s',
'datefmt': "%d/%b/%Y %H:%M:%S",
},
},
'filters': {
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'django.utils.log.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'webdnd.syncrae.config.log.ColorizingStreamHandler',
'formatter': 'simple',
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
},
},
'loggers': {
# Root logger that colors output
# Any other loggers should have propagate False if they output
# to the console to prevent duplicated console messages
'': {
'handlers': ['console'],
'propagate': False,
'level': 'INFO',
},
# Built-in Django loggers
# 'django': {
# },
# 'django.request': {
# 'handlers': ['console'],
# 'level': 'ERROR' if not DEBUG else 'INFO',
# 'propagate': False,
# },
# 'django.db.backends': {
# },
}
}
##################################################
# Misc
##################################################
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
MIDDLEWARE_CLASSES = (
# Debug toolbar
'debug_toolbar.middleware.DebugToolbarMiddleware',
# 'shared.middleware.HtmlPrettifyMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'alerts.middleware.AlertMiddleware',
'alerts.middleware.FieldHighlightMiddleware',
)
INDEX_DIR = os.path.join(WEBDND_ROOT, 'index/')
USER_INDEX_DIR = os.path.join(INDEX_DIR, 'user/')
# Characters that a user can't search for
USER_CHAR_RE = re.compile(r'[^.@-_a-zA-Z0-9]*')
| {
"content_hash": "6dc74830ee6c624d86e42633bf417c3e",
"timestamp": "",
"source": "github",
"line_count": 332,
"max_line_length": 128,
"avg_line_length": 28.07831325301205,
"alnum_prop": 0.6042694700708002,
"repo_name": "Saevon/webdnd",
"id": "888f6c5b4b501b64e7237ec50952e8ae05217f25",
"size": "9322",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "shared/config/settings_main.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26595"
},
{
"name": "HTML",
"bytes": "43008"
},
{
"name": "JavaScript",
"bytes": "95989"
},
{
"name": "Python",
"bytes": "163056"
}
],
"symlink_target": ""
} |
"""
Run a single species simulation and plot each time step separately.
"""
import time
import numpy
import pylab
import model.grid
from model.grid import Species, Grid
import habitat
# The size of the simulation grid
height, width = 128, 128
# Simulation time
time_steps = 10
# Random number generator seed for the simulation
seed = int(time.time())
# Create a random autocorrelated habitat matrix.
habitat_matrix = habitat.generate_habitat(height, width, 1.5, False)
model.grid.initialize_model(1, seed)
# Initialize a SPOM grid
species = Species(0.8, 1.0, 0.2, 0.5, 0.1)
g = Grid(height, width, species)
g.initialize()
g.calculate_fitness_from_habitat(habitat_matrix)
g.occupancy[:] = 1 # Initialize the occupancy matrix to contain all 1s
# Run the simulation and plot the occupancy matrix at each time step
for i in xrange(time_steps+1):
pylab.title("Step %i/%i" % (i,time_steps))
pylab.imshow(g.occupancy, cmap=pylab.cm.binary, vmin=0, vmax=1)
pylab.show()
g.step()
| {
"content_hash": "474e97658c2b2e3effdab37a282dafc4",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 70,
"avg_line_length": 25.973684210526315,
"alnum_prop": 0.7375886524822695,
"repo_name": "rybicki/corridor-spom",
"id": "ee4df74da86f0f2948b17f69bb76fe62f089bad5",
"size": "987",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "passive/spom/steps.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "225955"
},
{
"name": "CSS",
"bytes": "20409"
},
{
"name": "JavaScript",
"bytes": "160"
},
{
"name": "Perl",
"bytes": "1444"
},
{
"name": "Prolog",
"bytes": "148"
},
{
"name": "Python",
"bytes": "52487"
},
{
"name": "Shell",
"bytes": "45526"
}
],
"symlink_target": ""
} |
import argparse
import sys
import os
import subprocess
import signal
import getpass
import simplejson
from termcolor import colored
import ConfigParser
import StringIO
import functools
import time
import random
import string
from configobj import ConfigObj
import tempfile
import pwd, grp
import traceback
import uuid
import yaml
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
def loop_until_timeout(timeout, interval=1):
def wrap(f):
@functools.wraps(f)
def inner(*args, **kwargs):
current_time = time.time()
expired = current_time + timeout
while current_time < expired:
if f(*args, **kwargs):
return True
time.sleep(interval)
current_time = time.time()
return False
return inner
return wrap
def find_process_by_cmdline(cmdlines):
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
for pid in pids:
try:
with open(os.path.join('/proc', pid, 'cmdline'), 'r') as fd:
cmdline = fd.read()
is_find = True
for c in cmdlines:
if c not in cmdline:
is_find = False
break
if not is_find:
continue
return pid
except IOError:
continue
return None
def ssh_run_full(ip, cmd, params=[], pipe=True):
remote_path = '/tmp/%s.sh' % uuid.uuid4()
script = '''/bin/bash << EOF
cat << EOF1 > %s
%s
EOF1
/bin/bash %s %s
ret=$?
rm -f %s
exit $ret
EOF''' % (remote_path, cmd, remote_path, ' '.join(params), remote_path)
scmd = ShellCmd('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s "%s"' % (ip, script), pipe=pipe)
scmd(False)
return scmd
def ssh_run(ip, cmd, params=[]):
scmd = ssh_run_full(ip, cmd, params)
if scmd.return_code != 0:
scmd.raise_error()
return scmd.stdout
def ssh_run_no_pipe(ip, cmd, params=[]):
scmd = ssh_run_full(ip, cmd, params, False)
if scmd.return_code != 0:
scmd.raise_error()
return scmd.stdout
class CtlError(Exception):
pass
def warn(msg):
sys.stdout.write('WARNING: %s\n' % msg)
def error(msg):
sys.stderr.write(colored('ERROR: %s\n' % msg, 'red'))
sys.exit(1)
def error_not_exit(msg):
sys.stderr.write(colored('ERROR: %s\n' % msg, 'red'))
def info(*msg):
if len(msg) == 1:
out = '%s\n' % ''.join(msg)
else:
out = ''.join(msg)
sys.stdout.write(out)
class ExceptionWrapper(object):
def __init__(self, msg):
self.msg = msg
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if globals().get('verbose', False) and exc_type and exc_val and exc_tb:
error_not_exit(''.join(traceback.format_exception(exc_type, exc_val, exc_tb)))
if exc_type == CtlError:
return
if exc_val:
error('%s\n%s' % (str(exc_val), self.msg))
def on_error(msg):
return ExceptionWrapper(msg)
def error_if_tool_is_missing(tool):
if shell_return('which %s' % tool) != 0:
raise CtlError('cannot find tool "%s", please install it and re-run' % tool)
def expand_path(path):
if path.startswith('~'):
return os.path.expanduser(path)
else:
return os.path.abspath(path)
class Ansible(object):
def __init__(self, yaml, host='localhost', debug=False, ssh_key='none'):
self.yaml = yaml
self.host = host
self.debug = debug
self.ssh_key = ssh_key
def __call__(self, *args, **kwargs):
error_if_tool_is_missing('ansible-playbook')
cmd = '''
yaml_file=`mktemp`
cat <<EOF >> $$yaml_file
$yaml
EOF
ansible_cmd="ansible-playbook $$yaml_file -i '$host,'"
if [ $debug -eq 1 ]; then
ansible_cmd="$$ansible_cmd -vvvv"
fi
if [ "$ssh_key" != "none" ]; then
ansible_cmd="$$ansible_cmd --private-key=$ssh_key"
ssh -oPasswordAuthentication=no -oStrictHostKeyChecking=no -i $ssh_key $host 'echo hi > /dev/null'
else
ssh -oPasswordAuthentication=no -oStrictHostKeyChecking=no $host 'echo hi > /dev/null'
fi
if [ $$? -ne 0 ]; then
ansible_cmd="$$ansible_cmd --ask-pass"
fi
eval $$ansible_cmd
ret=$$?
rm -f $$yaml_file
exit $$ret
'''
t = string.Template(cmd)
cmd = t.substitute({
'yaml': self.yaml,
'host': self.host,
'debug': int(self.debug),
'ssh_key': self.ssh_key
})
with on_error('Ansible failure'):
try:
shell_no_pipe(cmd)
except CtlError:
raise Exception('see prior Ansible log for detailed information')
def ansible(yaml, host='localhost', debug=False, ssh_key=None):
Ansible(yaml, host, debug, ssh_key or 'none')()
def check_zstack_user():
try:
pwd.getpwnam('zstack')
except KeyError:
raise CtlError('cannot find user account "zstack", your installation seems incomplete')
try:
grp.getgrnam('zstack')
except KeyError:
raise CtlError('cannot find user account "zstack", your installation seems incomplete')
class UseUserZstack(object):
def __init__(self):
self.root_uid = None
self.root_gid = None
check_zstack_user()
def __enter__(self):
self.root_uid = os.getuid()
self.root_gid = os.getgid()
self.root_home = os.environ['HOME']
os.setegid(grp.getgrnam('zstack').gr_gid)
os.seteuid(pwd.getpwnam('zstack').pw_uid)
os.environ['HOME'] = os.path.expanduser('~zstack')
def __exit__(self, exc_type, exc_val, exc_tb):
os.seteuid(self.root_uid)
os.setegid(self.root_gid)
os.environ['HOME'] = self.root_home
def use_user_zstack():
return UseUserZstack()
class PropertyFile(object):
def __init__(self, path, use_zstack=True):
self.path = path
self.use_zstack = use_zstack
if not os.path.isfile(self.path):
raise CtlError('cannot find property file at %s' % self.path)
with on_error("errors on reading %s" % self.path):
self.config = ConfigObj(self.path, write_empty_values=True)
def read_all_properties(self):
with on_error("errors on reading %s" % self.path):
return self.config.items()
def delete_properties(self, keys):
for k in keys:
if k in self.config:
del self.config[k]
with use_user_zstack():
self.config.write()
def read_property(self, key):
with on_error("errors on reading %s" % self.path):
return self.config.get(key, None)
def write_property(self, key, value):
with on_error("errors on writing (%s=%s) to %s" % (key, value, self.path)):
if self.use_zstack:
with use_user_zstack():
self.config[key] = value
self.config.write()
else:
self.config[key] = value
self.config.write()
def write_properties(self, lst):
with on_error("errors on writing list of key-value%s to %s" % (lst, self.path)):
if self.use_zstack:
with use_user_zstack():
for key, value in lst:
self.config[key] = value
self.config.write()
else:
for key, value in lst:
self.config[key] = value
self.config.write()
class CtlParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error:%s\n' % message)
self.print_help()
sys.exit(1)
class Ctl(object):
DEFAULT_ZSTACK_HOME = '/usr/local/zstack/apache-tomcat/webapps/zstack/'
USER_ZSTACK_HOME_DIR = os.path.expanduser('~zstack')
def __init__(self):
self.commands = {}
self.command_list = []
self.main_parser = CtlParser(prog='zstackctl', description="ZStack management tool", formatter_class=argparse.RawTextHelpFormatter)
self.main_parser.add_argument('-v', help="verbose, print execution details", dest="verbose", action="store_true", default=False)
self.zstack_home = None
self.properties_file_path = None
self.verbose = False
self.extra_arguments = None
def register_command(self, cmd):
assert cmd.name, "command name cannot be None"
assert cmd.description, "command description cannot be None"
self.commands[cmd.name] = cmd
self.command_list.append(cmd)
def _locate_zstack_home(self):
env_path = os.path.expanduser(SetEnvironmentVariableCmd.PATH)
if os.path.isfile(env_path):
env = PropertyFile(env_path)
self.zstack_home = env.read_property('ZSTACK_HOME')
if not self.zstack_home:
self.zstack_home = os.environ.get('ZSTACK_HOME', None)
if not self.zstack_home:
warn('ZSTACK_HOME is not set, default to %s' % self.DEFAULT_ZSTACK_HOME)
self.zstack_home = self.DEFAULT_ZSTACK_HOME
if not os.path.isdir(self.zstack_home):
raise CtlError('cannot find ZSTACK_HOME at %s, please set it in .bashrc or use zstack-ctl setenv ZSTACK_HOME=path' % self.zstack_home)
os.environ['ZSTACK_HOME'] = self.zstack_home
self.properties_file_path = os.path.join(self.zstack_home, 'WEB-INF/classes/zstack.properties')
if not os.path.isfile(self.properties_file_path):
warn('cannot find %s, your ZStack installation may have crashed' % self.properties_file_path)
def get_env(self, name):
env = PropertyFile(SetEnvironmentVariableCmd.PATH)
return env.read_property(name)
def put_envs(self, vs):
if not os.path.exists(SetEnvironmentVariableCmd.PATH):
shell('su - zstack -c "mkdir -p %s"' % os.path.dirname(SetEnvironmentVariableCmd.PATH))
shell('su - zstack -c "touch %s"' % SetEnvironmentVariableCmd.PATH)
env = PropertyFile(SetEnvironmentVariableCmd.PATH)
env.write_properties(vs)
def run(self):
if os.getuid() != 0:
raise CtlError('zstack-ctl needs root privilege, please run with sudo')
subparsers = self.main_parser.add_subparsers(help="All sub-commands", dest="sub_command_name")
for cmd in self.command_list:
cmd.install_argparse_arguments(subparsers.add_parser(cmd.name, help=cmd.description + '\n\n'))
args, self.extra_arguments = self.main_parser.parse_known_args(sys.argv[1:])
self.verbose = args.verbose
globals()['verbose'] = self.verbose
cmd = self.commands[args.sub_command_name]
if cmd.need_zstack_home():
self._locate_zstack_home()
if cmd.need_zstack_user():
check_zstack_user()
cmd(args)
def internal_run(self, cmd_name, args=''):
cmd = self.commands[cmd_name]
assert cmd, 'cannot find command %s' % cmd_name
params = [cmd_name]
params.extend(args.split())
args_obj, _ = self.main_parser.parse_known_args(params)
if cmd.need_zstack_home():
self._locate_zstack_home()
if cmd.need_zstack_user():
check_zstack_user()
cmd(args_obj)
def read_property_list(self, key):
prop = PropertyFile(self.properties_file_path)
ret = []
for name, value in prop.read_all_properties():
if name.startswith(key):
ret.append((name, value))
return ret
def read_all_properties(self):
prop = PropertyFile(self.properties_file_path)
return prop.read_all_properties()
def read_property(self, key):
prop = PropertyFile(self.properties_file_path)
return prop.read_property(key)
def write_properties(self, properties):
prop = PropertyFile(self.properties_file_path)
with on_error('property must be in format of "key=value", no space before and after "="'):
prop.write_properties(properties)
def write_property(self, key, value):
prop = PropertyFile(self.properties_file_path)
def get_db_url(self):
db_url = self.read_property("DB.url")
if not db_url:
db_url = self.read_property('DbFacadeDataSource.jdbcUrl')
if not db_url:
raise CtlError("cannot find DB url in %s. please set DB.url" % self.properties_file_path)
return db_url
def get_database_portal(self):
db_user = self.read_property("DB.user")
if not db_user:
db_user = self.read_property('DbFacadeDataSource.user')
if not db_user:
raise CtlError("cannot find DB user in %s. please set DB.user" % self.properties_file_path)
db_password = self.read_property("DB.password")
if db_password is None:
db_password = self.read_property('DbFacadeDataSource.password')
if db_password is None:
raise CtlError("cannot find DB password in %s. please set DB.password" % self.properties_file_path)
db_url = self.get_db_url()
db_hostname, db_port = db_url.lstrip('jdbc:mysql:').lstrip('/').split('/')[0].split(':')
return db_hostname, db_port, db_user, db_password
def check_if_management_node_has_stopped(self, force=False):
db_hostname, db_port, db_user, db_password = self.get_database_portal()
def get_nodes():
query = MySqlCommandLineQuery()
query.user = db_user
query.password = db_password
query.host = db_hostname
query.port = db_port
query.table = 'zstack'
query.sql = 'select hostname,heartBeat from ManagementNodeVO'
return query.query()
def check():
nodes = get_nodes()
if nodes:
node_ips = [n['hostname'] for n in nodes]
raise CtlError('there are some management nodes%s are still running. Please stop all of them before performing the database upgrade.'
'If you are sure they have stopped, use option --force and run this command again.\n'
'If you are upgrade by all in on installer, use option -F and run all in one installer again.\n'
'WARNING: the database may crash if you run this command with --force but without stopping management nodes' % node_ips)
def bypass_check():
nodes = get_nodes()
if nodes:
node_ips = [n['hostname'] for n in nodes]
info("it seems some nodes%s are still running. As you have specified option --force, let's wait for 10s to make sure those are stale records. Please be patient." % node_ips)
time.sleep(10)
new_nodes = get_nodes()
for n in new_nodes:
for o in nodes:
if o['hostname'] == n['hostname'] and o['heartBeat'] != n['heartBeat']:
raise CtlError("node[%s] is still Running! Its heart-beat changed from %s to %s in last 10s. Please make sure you really stop it" %
(n['hostname'], o['heartBeat'], n['heartBeat']))
if force:
bypass_check()
else:
check()
ctl = Ctl()
def script(cmd, args=None, no_pipe=False):
if args:
t = string.Template(cmd)
cmd = t.substitute(args)
fd, script_path = tempfile.mkstemp(suffix='.sh')
os.fdopen(fd, 'w').write(cmd)
try:
if ctl.verbose:
info('execute script:\n%s\n' % cmd)
if no_pipe:
shell_no_pipe('bash %s' % script_path)
else:
shell('bash %s' % script_path)
finally:
os.remove(script_path)
class ShellCmd(object):
def __init__(self, cmd, workdir=None, pipe=True):
self.cmd = cmd
if pipe:
self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, cwd=workdir)
else:
self.process = subprocess.Popen(cmd, shell=True, cwd=workdir)
self.return_code = None
self.stdout = None
self.stderr = None
def raise_error(self):
err = []
err.append('failed to execute shell command: %s' % self.cmd)
err.append('return code: %s' % self.process.returncode)
err.append('stdout: %s' % self.stdout)
err.append('stderr: %s' % self.stderr)
raise CtlError('\n'.join(err))
def __call__(self, is_exception=True):
if ctl.verbose:
info('executing shell command[%s]:' % self.cmd)
(self.stdout, self.stderr) = self.process.communicate()
if is_exception and self.process.returncode != 0:
self.raise_error()
self.return_code = self.process.returncode
if ctl.verbose:
info(simplejson.dumps({
"shell" : self.cmd,
"return_code" : self.return_code,
"stdout": self.stdout,
"stderr": self.stderr
}, ensure_ascii=True, sort_keys=True, indent=4))
return self.stdout
def shell(cmd, is_exception=True):
return ShellCmd(cmd)(is_exception)
def shell_no_pipe(cmd, is_exception=True):
return ShellCmd(cmd, pipe=False)(is_exception)
def shell_return(cmd):
scmd = ShellCmd(cmd)
scmd(False)
return scmd.return_code
class Command(object):
def __init__(self):
self.name = None
self.description = None
self.cleanup_routines = []
def install_argparse_arguments(self, parser):
pass
def install_cleanup_routine(self, func):
self.cleanup_routines.append(func)
def need_zstack_home(self):
return True
def need_zstack_user(self):
return True
def __call__(self, *args, **kwargs):
try:
self.run(*args)
finally:
for c in self.cleanup_routines:
c()
def run(self, args):
raise CtlError('the command is not implemented')
def create_check_mgmt_node_command(timeout=10):
USE_CURL = 0
USE_WGET = 1
NO_TOOL = 2
def use_tool():
cmd = ShellCmd('which wget')
cmd(False)
if cmd.return_code == 0:
return USE_WGET
else:
cmd = ShellCmd('which curl')
cmd(False)
if cmd.return_code == 0:
return USE_CURL
else:
return NO_TOOL
what_tool = use_tool()
if what_tool == USE_CURL:
return ShellCmd('''curl --noproxy --connect-timeout 1 --retry %s --retry-delay 0 --retry-max-time %s --max-time %s -H "Content-Type: application/json" -d '{"org.zstack.header.apimediator.APIIsReadyToGoMsg": {}}' http://127.0.0.1:8080/zstack/api''' % (timeout, timeout, timeout))
elif what_tool == USE_WGET:
return ShellCmd('''wget --no-proxy -O- --tries=%s --timeout=1 --header=Content-Type:application/json --post-data='{"org.zstack.header.apimediator.APIIsReadyToGoMsg": {}}' http://127.0.0.1:8080/zstack/api''' % timeout)
else:
return None
def find_process_by_cmdline(keyword):
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
for pid in pids:
try:
with open(os.path.join('/proc', pid, 'cmdline'), 'r') as fd:
cmdline = fd.read()
if keyword not in cmdline:
continue
return pid
except IOError:
continue
return None
class MySqlCommandLineQuery(object):
def __init__(self):
self.user = None
self.password = None
self.host = 'localhost'
self.port = 3306
self.sql = None
self.table = None
def query(self):
assert self.user, 'user cannot be None'
assert self.sql, 'sql cannot be None'
assert self.table, 'table cannot be None'
sql = "%s\G" % self.sql
if self.password:
cmd = '''mysql -u %s -p%s --host %s --port %s -t %s -e "%s"''' % (self.user, self.password, self.host,
self.port, self.table, sql)
else:
cmd = '''mysql -u %s --host %s --port %s -t %s -e "%s"''' % (self.user, self.host, self.port, self.table, sql)
output = shell(cmd)
output = output.strip(' \t\n\r')
ret = []
if not output:
return ret
current = None
for l in output.split('\n'):
if current is None and not l.startswith('*********'):
raise CtlError('cannot parse mysql output generated by the sql "%s", output:\n%s' % (self.sql, output))
if l.startswith('*********'):
if current:
ret.append(current)
current = {}
else:
l = l.strip()
key, value = l.split(':', 1)
current[key.strip()] = value[1:]
if current:
ret.append(current)
return ret
class ShowStatusCmd(Command):
def __init__(self):
super(ShowStatusCmd, self).__init__()
self.name = 'status'
self.description = 'show ZStack status and information.'
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='SSH URL, for example, root@192.168.0.10, to show the management node status on a remote machine')
def _stop_remote(self, args):
shell_no_pipe('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s "/usr/bin/zstack-ctl status"' % args.host)
def run(self, args):
if args.host:
self._stop_remote(args)
return
log_path = os.path.join(ctl.zstack_home, "../../logs/management-server.log")
log_path = os.path.normpath(log_path)
info_list = [
"ZSTACK_HOME: %s" % ctl.zstack_home,
"zstack.properties: %s" % ctl.properties_file_path,
"log4j2.xml: %s" % os.path.join(os.path.dirname(ctl.properties_file_path), 'log4j2.xml'),
"PID file: %s" % os.path.join(os.path.expanduser('~zstack'), "management-server.pid"),
"log file: %s" % log_path
]
def check_zstack_status():
cmd = create_check_mgmt_node_command()
def write_status(status):
info_list.append('status: %s' % status)
if not cmd:
write_status('cannot detect status, no wget and curl installed')
return
cmd(False)
if cmd.return_code != 0:
pid = get_management_node_pid()
if pid:
write_status('%s, the management node seems to become zombie as it stops responding APIs but the '
'process(PID: %s) is still running. Please stop the node using zstack-ctl stop_node' %
(colored('Unknown', 'yellow'), pid))
else:
write_status(colored('Stopped', 'red'))
return
if 'false' in cmd.stdout:
write_status('Starting, should be ready in a few seconds')
elif 'true' in cmd.stdout:
write_status(colored('Running', 'green'))
else:
write_status('Unknown')
def show_version():
db_hostname, db_port, db_user, db_password = ctl.get_database_portal()
if db_password:
cmd = ShellCmd('''mysql -u %s -p%s --host %s --port %s -t zstack -e "show tables like 'schema_version'"''' %
(db_user, db_password, db_hostname, db_port))
else:
cmd = ShellCmd('''mysql -u %s --host %s --port %s -t zstack -e "show tables like 'schema_version'"''' %
(db_user, db_hostname, db_port))
cmd(False)
if cmd.return_code != 0:
info_list.append('version: %s' % colored('unknown, MySQL is not running', 'yellow'))
return
out = cmd.stdout
if 'schema_version' not in out:
version = '0.6'
else:
query = MySqlCommandLineQuery()
query.host = db_hostname
query.port = db_port
query.user = db_user
query.password = db_password
query.table = 'zstack'
query.sql = "select version from schema_version order by version desc"
ret = query.query()
v = ret[0]
version = v['version']
info_list.append('version: %s' % version)
check_zstack_status()
show_version()
info('\n'.join(info_list))
class DeployDBCmd(Command):
DEPLOY_DB_SCRIPT_PATH = "WEB-INF/classes/deploydb.sh"
ZSTACK_PROPERTY_FILE = "WEB-INF/classes/zstack.properties"
def __init__(self):
super(DeployDBCmd, self).__init__()
self.name = "deploydb"
self.description = (
"deploy a new ZStack database, create a user 'zstack' with password specified in '--zstack-password',\n"
"and update zstack.properties if --no-update is not set.\n"
"\nDANGER: this will erase the existing ZStack database.\n"
"NOTE: If the database is running on a remote host, please make sure you have granted privileges to the root user by:\n"
"\n\tGRANT ALL PRIVILEGES ON *.* TO 'root'@'%%' IDENTIFIED BY 'your_root_password' WITH GRANT OPTION;\n"
"\tFLUSH PRIVILEGES;\n"
)
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--root-password', help='root user password of MySQL. [DEFAULT] empty password')
parser.add_argument('--zstack-password', help='password of user "zstack". [DEFAULT] empty password')
parser.add_argument('--host', help='IP or DNS name of MySQL host; default is localhost', default='localhost')
parser.add_argument('--port', help='port of MySQL host; default is 3306', type=int, default=3306)
parser.add_argument('--no-update', help='do NOT update database information to zstack.properties; if you do not know what this means, do not use it', action='store_true', default=False)
parser.add_argument('--drop', help='drop existing zstack database', action='store_true', default=False)
parser.add_argument('--keep-db', help='keep existing zstack database and not raise error.', action='store_true', default=False)
def run(self, args):
error_if_tool_is_missing('mysql')
script_path = os.path.join(ctl.zstack_home, self.DEPLOY_DB_SCRIPT_PATH)
if not os.path.exists(script_path):
error('cannot find %s, your ZStack installation may have been corrupted, please reinstall it' % script_path)
property_file_path = os.path.join(ctl.zstack_home, self.ZSTACK_PROPERTY_FILE)
if not os.path.exists(property_file_path):
error('cannot find %s, your ZStack installation may have been corrupted, please reinstall it' % property_file_path)
if args.root_password:
check_existing_db = 'mysql --user=root --password=%s --host=%s --port=%s -e "use zstack"' % (args.root_password, args.host, args.port)
else:
check_existing_db = 'mysql --user=root --host=%s --port=%s -e "use zstack"' % (args.host, args.port)
cmd = ShellCmd(check_existing_db)
cmd(False)
if not args.root_password:
args.root_password = "''"
if not args.zstack_password:
args.zstack_password = "''"
if cmd.return_code == 0 and not args.drop:
if args.keep_db:
info('detected existing zstack database and keep it; if you want to drop it, please append parameter --drop, instead of --keep-db\n')
else:
raise CtlError('detected existing zstack database; if you are sure to drop it, please append parameter --drop')
else:
cmd = ShellCmd('bash %s root %s %s %s %s' % (script_path, args.root_password, args.host, args.port, args.zstack_password))
cmd(False)
if cmd.return_code != 0:
if ('ERROR 1044' in cmd.stdout or 'ERROR 1044' in cmd.stderr) or ('Access denied' in cmd.stdout or 'Access denied' in cmd.stderr):
raise CtlError(
"failed to deploy database, access denied; if your root password is correct and you use IP rather than localhost,"
"it's probably caused by the privileges are not granted to root user for remote access; please see instructions in 'zstack-ctl -h'."
"error details: %s, %s\n" % (cmd.stdout, cmd.stderr)
)
else:
cmd.raise_error()
if not args.no_update:
if args.zstack_password == "''":
args.zstack_password = ''
properties = [
("DB.user", "zstack"),
("DB.password", args.zstack_password),
("DB.url", 'jdbc:mysql://%s:%s' % (args.host, args.port)),
]
ctl.write_properties(properties)
info('Successfully deployed ZStack database and updated corresponding DB information in %s' % property_file_path)
class TailLogCmd(Command):
def __init__(self):
super(TailLogCmd, self).__init__()
self.name = 'taillog'
self.description = "shortcut to print management node log to stdout"
ctl.register_command(self)
def run(self, args):
log_path = os.path.join(ctl.zstack_home, "../../logs/management-server.log")
log_path = os.path.normpath(log_path)
if not os.path.isfile(log_path):
raise CtlError('cannot find %s' % log_path)
script = ShellCmd('tail -f %s' % log_path, pipe=False)
script()
class ConfigureCmd(Command):
def __init__(self):
super(ConfigureCmd, self).__init__()
self.name = 'configure'
self.description = "configure zstack.properties"
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='SSH URL, for example, root@192.168.0.10, to set properties in zstack.properties on the remote machine')
parser.add_argument('--duplicate-to-remote', help='SSH URL, for example, root@192.168.0.10, to copy zstack.properties on this machine to the remote machine')
parser.add_argument('--use-file', help='path to a file that will be used to as zstack.properties')
def _configure_remote_node(self, args):
shell_no_pipe('ssh %s "/usr/bin/zstack-ctl configure %s"' % (args.host, ' '.join(ctl.extra_arguments)))
def _duplicate_remote_node(self, args):
tmp_file_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
tmp_file_name = os.path.join('/tmp/', tmp_file_name)
with open(ctl.properties_file_path, 'r') as fd:
txt = fd.read()
cmd = '''ssh -T %s << EOF
cat <<EOT > %s
%s
EOT
if [ $? != 0 ]; then
print "cannot create temporary properties file"
exit 1
fi
/usr/bin/zstack-ctl configure --use-file %s
ret=$?
rm -f %s
exit $ret
EOF
'''
shell_no_pipe(cmd % (args.duplicate_to_remote, tmp_file_name, txt, tmp_file_name, tmp_file_name))
info("successfully copied %s to remote machine %s" % (ctl.properties_file_path, args.duplicate_to_remote))
def _use_file(self, args):
path = os.path.expanduser(args.use_file)
if not os.path.isfile(path):
raise CtlError('cannot find file %s' % path)
shell('cp -f %s %s' % (path, ctl.properties_file_path))
def run(self, args):
if args.use_file:
self._use_file(args)
return
if args.duplicate_to_remote:
self._duplicate_remote_node(args)
return
if not ctl.extra_arguments:
raise CtlError('please input properties that are in format of "key=value" split by space')
if args.host:
self._configure_remote_node(args)
return
properties = [l.split('=', 1) for l in ctl.extra_arguments]
ctl.write_properties(properties)
def get_management_node_pid():
DEFAULT_PID_FILE_PATH = os.path.join(os.path.expanduser('~zstack'), "management-server.pid")
pid = find_process_by_cmdline('appName=zstack')
if pid:
return pid
pid_file_path = ctl.read_property('pidFilePath')
if not pid_file_path:
pid_file_path = DEFAULT_PID_FILE_PATH
if not os.path.exists(pid_file_path):
return None
with open(pid_file_path, 'r') as fd:
pid = fd.read()
try:
pid = int(pid)
proc_pid = '/proc/%s' % pid
if os.path.exists(proc_pid):
return pid
except Exception:
return None
return None
class StopAllCmd(Command):
def __init__(self):
super(StopAllCmd, self).__init__()
self.name = 'stop'
self.description = 'stop all ZStack related services including cassandra, kairosdb, zstack management node, web UI' \
' if those services are installed'
ctl.register_command(self)
def run(self, args):
def stop_cassandra():
exe = ctl.get_env(InstallCassandraCmd.CASSANDRA_EXEC)
if not exe or not os.path.exists(exe):
info('skip stopping cassandra, it is not installed')
return
info(colored('Stopping cassandra, it may take a few minutes...', 'blue'))
ctl.internal_run('cassandra', '--stop')
def stop_kairosdb():
exe = ctl.get_env(InstallKairosdbCmd.KAIROSDB_EXEC)
if not exe or not os.path.exists(exe):
info('skip stopping kairosdb, it is not installed')
return
info(colored('Stopping kairosdb, it may take a few minutes...', 'blue'))
ctl.internal_run('kairosdb', '--stop')
def stop_mgmt_node():
info(colored('Stopping ZStack management node, it may take a few minutes...', 'blue'))
ctl.internal_run('stop_node')
def stop_ui():
virtualenv = '/var/lib/zstack/virtualenv/zstack-dashboard'
if not os.path.exists(virtualenv):
info('skip stopping web UI, it is not installed')
return
info(colored('Stopping ZStack web UI, it may take a few minutes...', 'blue'))
ctl.internal_run('stop_ui')
stop_ui()
stop_mgmt_node()
stop_kairosdb()
stop_cassandra()
class StartAllCmd(Command):
def __init__(self):
super(StartAllCmd, self).__init__()
self.name = 'start'
self.description = 'start all ZStack related services including cassandra, kairosdb, zstack management node, web UI' \
' if those services are installed'
ctl.register_command(self)
def run(self, args):
def start_cassandra():
exe = ctl.get_env(InstallCassandraCmd.CASSANDRA_EXEC)
if not exe or not os.path.exists(exe):
info('skip starting cassandra, it is not installed')
return
info(colored('Starting cassandra, it may take a few minutes...', 'blue'))
ctl.internal_run('cassandra', '--start --wait-timeout 120')
def start_kairosdb():
exe = ctl.get_env(InstallKairosdbCmd.KAIROSDB_EXEC)
if not exe or not os.path.exists(exe):
info('skip starting kairosdb, it is not installed')
return
info(colored('Starting kairosdb, it may take a few minutes...', 'blue'))
ctl.internal_run('kairosdb', '--start --wait-timeout 120')
def start_mgmt_node():
info(colored('Starting ZStack management node, it may take a few minutes...', 'blue'))
ctl.internal_run('start_node')
def start_ui():
virtualenv = '/var/lib/zstack/virtualenv/zstack-dashboard'
if not os.path.exists(virtualenv):
info('skip starting web UI, it is not installed')
return
info(colored('Starting ZStack web UI, it may take a few minutes...', 'blue'))
ctl.internal_run('start_ui')
start_cassandra()
start_kairosdb()
start_mgmt_node()
start_ui()
class StartCmd(Command):
START_SCRIPT = '../../bin/startup.sh'
SET_ENV_SCRIPT = '../../bin/setenv.sh'
def __init__(self):
super(StartCmd, self).__init__()
self.name = 'start_node'
self.description = 'start the ZStack management node on this machine'
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='SSH URL, for example, root@192.168.0.10, to start the management node on a remote machine')
parser.add_argument('--timeout', help='Wait for ZStack Server startup timeout, default is 300 seconds.', default=300)
def _start_remote(self, args):
info('it may take a while because zstack-ctl will wait for management node ready to serve API')
shell_no_pipe('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s "/usr/bin/zstack-ctl start_node --timeout=%s"' % (args.host, args.timeout))
def run(self, args):
if args.host:
self._start_remote(args)
return
# clean the error log before booting
boot_error_log = os.path.join(ctl.USER_ZSTACK_HOME_DIR, 'bootError.log')
shell('rm -f %s' % boot_error_log)
pid = get_management_node_pid()
if pid:
info('the management node[pid:%s] is already running' % pid)
return
def check_ip_port(host, port):
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((host, int(port)))
return result == 0
def check_8080():
if shell_return('netstat -nap | grep :8080 | grep LISTEN > /dev/null') == 0:
raise CtlError('8080 is occupied by some process. Please use netstat to find out and stop it')
def check_msyql():
db_hostname, db_port, db_user, db_password = ctl.get_database_portal()
if not check_ip_port(db_hostname, db_port):
raise CtlError('unable to connect to %s:%s, please check if the MySQL is running and the firewall rules' % (db_hostname, db_port))
with on_error('unable to connect to MySQL'):
shell('mysql --host=%s --user=%s --password=%s --port=%s -e "select 1"' % (db_hostname, db_user, db_password, db_port))
def check_rabbitmq():
RABBIT_PORT = 5672
with on_error('unable to get RabbitMQ server IPs from %s, please check CloudBus.serverIp.0'):
ips = ctl.read_property_list('CloudBus.serverIp.')
if not ips:
raise CtlError('no RabbitMQ IPs defined in %s, please specify it use CloudBus.serverIp.0=the_ip' % ctl.properties_file_path)
for key, ip in ips:
if not check_ip_port(ip, RABBIT_PORT):
raise CtlError('cannot connect to RabbitMQ server[ip:%s, port:%s] defined by item[%s] in %s' % (ip, RABBIT_PORT, key, ctl.properties_file_path))
def prepare_setenv():
setenv_path = os.path.join(ctl.zstack_home, self.SET_ENV_SCRIPT)
catalina_opts = [
'-Djava.net.preferIPv4Stack=true',
'-Dcom.sun.management.jmxremote=true',
'-Djava.security.egd=file:/dev/./urandom'
]
co = ctl.get_env('CATALINA_OPTS')
if co:
info('use CATALINA_OPTS[%s] set in environment zstack environment variables; check out them by "zstack-ctl getenv"' % co)
catalina_opts.extend(co.split(' '))
with open(setenv_path, 'w') as fd:
fd.write('export CATALINA_OPTS=" %s"' % ' '.join(catalina_opts))
def start_mgmt_node():
shell('sudo -u zstack sh %s -DappName=zstack' % os.path.join(ctl.zstack_home, self.START_SCRIPT))
info("successfully started Tomcat container; now it's waiting for the management node ready for serving APIs, which may take a few seconds")
def wait_mgmt_node_start():
log_path = os.path.join(ctl.zstack_home, "../../logs/management-server.log")
timeout = int(args.timeout)
@loop_until_timeout(timeout)
def check():
if os.path.exists(boot_error_log):
with open(boot_error_log, 'r') as fd:
raise CtlError('the management server fails to boot; details can be found in the log[%s],'
'here is a brief of the error:\n%s' % (log_path, fd.read()))
cmd = create_check_mgmt_node_command(1)
cmd(False)
return cmd.return_code == 0
if not check():
raise CtlError('no management-node-ready message received within %s seconds, please check error in log file %s' % (timeout, log_path))
user = getpass.getuser()
if user != 'root':
raise CtlError('please use sudo or root user')
check_8080()
check_msyql()
check_rabbitmq()
prepare_setenv()
start_mgmt_node()
#sleep a while, since zstack won't start up so quick
time.sleep(5)
try:
wait_mgmt_node_start()
except CtlError as e:
try:
info("the management node failed to start, stop it now ...")
ctl.internal_run('stop_node')
except:
pass
raise e
info('successfully started management node')
class StopCmd(Command):
STOP_SCRIPT = "../../bin/shutdown.sh"
def __init__(self):
super(StopCmd, self).__init__()
self.name = 'stop_node'
self.description = 'stop the ZStack management node on this machine'
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='SSH URL, for example, root@192.168.0.10, to stop the management node on a remote machine')
parser.add_argument('--force', '-f', help='force kill the java process, without waiting.', action="store_true", default=False)
def _stop_remote(self, args):
if args.force:
shell_no_pipe('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s "/usr/bin/zstack-ctl stop_node --force"' % args.host)
else:
shell_no_pipe('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s "/usr/bin/zstack-ctl stop_node"' % args.host)
def run(self, args):
if args.host:
self._stop_remote(args)
return
pid = get_management_node_pid()
if not pid:
info('the management node has been stopped')
return
timeout = 30
if not args.force:
@loop_until_timeout(timeout)
def wait_stop():
return get_management_node_pid() is None
shell('bash %s' % os.path.join(ctl.zstack_home, self.STOP_SCRIPT))
if wait_stop():
info('successfully stopped management node')
return
pid = get_management_node_pid()
if pid:
if not args.force:
info('unable to stop management node within %s seconds, kill it' % timeout)
with on_error('unable to kill -9 %s' % pid):
shell('kill -9 %s' % pid)
class SaveConfigCmd(Command):
DEFAULT_PATH = '~/.zstack/'
def __init__(self):
super(SaveConfigCmd, self).__init__()
self.name = 'save_config'
self.description = 'save ZStack configuration from ZSTACK_HOME to specified folder'
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--save-to', help='the folder where ZStack configurations should be saved')
def run(self, args):
path = args.save_to
if not path:
path = self.DEFAULT_PATH
path = os.path.expanduser(path)
if not os.path.exists(path):
os.makedirs(path)
properties_file_path = os.path.join(path, 'zstack.properties')
shell('yes | cp %s %s' % (ctl.properties_file_path, properties_file_path))
info('successfully saved %s to %s' % (ctl.properties_file_path, properties_file_path))
class RestoreConfigCmd(Command):
DEFAULT_PATH = '~/.zstack/'
def __init__(self):
super(RestoreConfigCmd, self).__init__()
self.name = "restore_config"
self.description = 'restore ZStack configuration from specified folder to ZSTACK_HOME'
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--restore-from', help='the folder where ZStack configurations should be found')
def run(self, args):
path = args.restore_from
if not path:
path = self.DEFAULT_PATH
path = os.path.expanduser(path)
if os.path.isdir(path):
properties_file_path = os.path.join(path, 'zstack.properties')
elif os.path.isfile(path):
properties_file_path = path
else:
raise CtlError('cannot find zstack.properties at %s' % path)
shell('yes | cp %s %s' % (properties_file_path, ctl.properties_file_path))
info('successfully restored zstack.properties from %s to %s' % (properties_file_path, ctl.properties_file_path))
class InstallDbCmd(Command):
def __init__(self):
super(InstallDbCmd, self).__init__()
self.name = "install_db"
self.description = (
"install MySQL database on a target machine which can be a remote machine or the local machine."
"\nNOTE: you may need to set --login-password to password of previous MySQL root user, if the machine used to have MySQL installed and removed."
"\nNOTE: if you hasn't setup public key for ROOT user on the remote machine, this command will prompt you for password of SSH ROOT user for the remote machine."
)
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='host IP, for example, 192.168.0.212, please specify the real IP rather than "localhost" or "127.0.0.1" when installing on local machine; otherwise management nodes on other machines cannot access the DB.', required=True)
parser.add_argument('--root-password', help="new password of MySQL root user; an empty password is used if both this option and --login-password option are omitted")
parser.add_argument('--login-password', help="login password of MySQL root user; an empty password is used if this option is omitted."
"\n[NOTE] this option is needed only when the machine has MySQL previously installed and removed; the old MySQL root password will be left in the system,"
"you need to input it in order to reset root password for the new installed MySQL.", default=None)
parser.add_argument('--debug', help="open Ansible debug option", action="store_true", default=False)
parser.add_argument('--yum', help="Use ZStack predefined yum repositories. The valid options include: alibase,aliepel,163base,ustcepel,zstack-local. NOTE: only use it when you know exactly what it does.", default=None)
parser.add_argument('--no-backup', help='do NOT backup the database. If the database is very large and you have manually backup it, using this option will fast the upgrade process. [DEFAULT] false', default=False)
parser.add_argument('--ssh-key', help="the path of private key for SSH login $host; if provided, Ansible will use the specified key as private key to SSH login the $host", default=None)
def run(self, args):
yaml = '''---
- hosts: $host
remote_user: root
vars:
root_password: $root_password
login_password: $login_password
yum_repo: "$yum_repo"
tasks:
- name: pre-install script
script: $pre_install_script
- name: set RHEL7 yum repo
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7'
shell: echo -e "[zstack-local]\\nname=ZStack Local Yum Repo\\nbaseurl=file://$yum_folder/static/centos7_repo\\nenabled=0\\ngpgcheck=0\\n" > /etc/yum.repos.d/zstack-local.repo
- name: set RHEL6 yum repo
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '6' and ansible_distribution_version < '7'
shell: echo -e "[zstack-local]\\nname=ZStack Local Yum Repo\\nbaseurl=file://$yum_folder/static/centos6_repo\\nenabled=0\\ngpgcheck=0\\n" > /etc/yum.repos.d/zstack-local.repo
- name: install MySQL for RedHat 6 through user defined repos
when: ansible_os_family == 'RedHat' and ansible_distribution_version < '7' and yum_repo != 'false'
shell: yum clean metadata; yum --disablerepo=* --enablerepo={{yum_repo}} --nogpgcheck install -y mysql mysql-server
register: install_result
- name: install MySQL for RedHat 6 through system defined repos
when: ansible_os_family == 'RedHat' and ansible_distribution_version < '7' and yum_repo == 'false'
shell: "yum clean metadata; yum --nogpgcheck install -y mysql mysql-server "
register: install_result
- name: install MySQL for RedHat 7 from local
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7' and yum_repo != 'false'
shell: yum clean metadata; yum --disablerepo=* --enablerepo={{yum_repo}} --nogpgcheck install -y mariadb mariadb-server
register: install_result
- name: install MySQL for RedHat 7 from local
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7' and yum_repo == 'false'
shell: yum clean metadata; yum --nogpgcheck install -y mariadb mariadb-server
register: install_result
- name: install MySQL for Ubuntu
when: ansible_os_family == 'Debian'
apt: pkg={{item}} update_cache=yes
with_items:
- mysql-client
- mysql-server
register: install_result
- name: open 3306 port
shell: iptables-save | grep -- "-A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT" > /dev/null || iptables -I INPUT -p tcp -m tcp --dport 3306 -j ACCEPT
- name: run post-install script
script: $post_install_script
- name: enable MySQL daemon on RedHat 6
when: ansible_os_family == 'RedHat' and ansible_distribution_version < '7'
service: name=mysqld state=restarted enabled=yes
- name: enable MySQL daemon on RedHat 7
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7'
service: name=mariadb state=restarted enabled=yes
- name: enable MySQL on Ubuntu
when: ansible_os_family == 'Debian'
service: name=mysql state=restarted enabled=yes
- name: change root password
shell: $change_password_cmd
register: change_root_result
ignore_errors: yes
- name: grant remote access
when: change_root_result.rc == 0
shell: $grant_access_cmd
- name: rollback MySQL installation on RedHat 6
when: ansible_os_family == 'RedHat' and ansible_distribution_version < '7' and change_root_result.rc != 0 and install_result.changed == True
shell: rpm -ev mysql mysql-server
- name: rollback MySQL installation on RedHat 7
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7' and change_root_result.rc != 0 and install_result.changed == True
shell: rpm -ev mariadb mariadb-server
- name: rollback MySql installation on Ubuntu
when: ansible_os_family == 'Debian' and change_root_result.rc != 0 and install_result.changed == True
apt: pkg={{item}} state=absent update_cache=yes
with_items:
- mysql-client
- mysql-server
- name: failure
fail: >
msg="failed to change root password of MySQL, see prior error in task 'change root password'; the possible cause
is the machine used to have MySQL installed and removed, the previous password of root user is remaining on the
machine; try using --login-password. We have rolled back the MySQL installation so you can safely run install_db
again with --login-password set."
when: change_root_result.rc != 0 and install_result.changed == False
'''
if not args.root_password and not args.login_password:
args.root_password = '''"''"'''
grant_access_cmd = '''/usr/bin/mysql -u root -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '' WITH GRANT OPTION; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%s' IDENTIFIED BY '' WITH GRANT OPTION; FLUSH PRIVILEGES;"''' % args.host
elif not args.root_password:
args.root_password = args.login_password
grant_access_cmd = '''/usr/bin/mysql -u root -p%s -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%s' WITH GRANT OPTION; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%s' IDENTIFIED BY '%s' WITH GRANT OPTION; FLUSH PRIVILEGES;"''' % (args.root_password, args.root_password, args.host, args.root_password)
else:
grant_access_cmd = '''/usr/bin/mysql -u root -p%s -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%s' WITH GRANT OPTION; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%s' IDENTIFIED BY '%s' WITH GRANT OPTION; FLUSH PRIVILEGES;"''' % (args.root_password, args.root_password, args.host, args.root_password)
if args.login_password is not None:
change_root_password_cmd = '/usr/bin/mysqladmin -u root -p{{login_password}} password {{root_password}}'
else:
change_root_password_cmd = '/usr/bin/mysqladmin -u root password {{root_password}}'
pre_install_script = '''
echo -e "#aliyun base\n[alibase]\nname=CentOS-\$releasever - Base - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$releasever/os/\$basearch/\ngpgcheck=0\nenabled=0\n \n#released updates \n[aliupdates]\nname=CentOS-\$releasever - Updates - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$releasever/updates/\$basearch/\nenabled=0\ngpgcheck=0\n \n[aliextras]\nname=CentOS-\$releasever - Extras - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$releasever/extras/\$basearch/\nenabled=0\ngpgcheck=0\n \n[aliepel]\nname=Extra Packages for Enterprise Linux \$releasever - \$basearce - mirrors.aliyun.com\nbaseurl=http://mirrors.aliyun.com/epel/\$releasever/\$basearch\nfailovermethod=priority\nenabled=0\ngpgcheck=0\n" > /etc/yum.repos.d/zstack-aliyun-yum.repo
echo -e "#163 base\n[163base]\nname=CentOS-\$releasever - Base - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$releasever/os/\$basearch/\ngpgcheck=0\nenabled=0\n \n#released updates \n[163updates]\nname=CentOS-\$releasever - Updates - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$releasever/updates/\$basearch/\nenabled=0\ngpgcheck=0\n \n#additional packages that may be useful\n[163extras]\nname=CentOS-\$releasever - Extras - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$releasever/extras/\$basearch/\nenabled=0\ngpgcheck=0\n \n[ustcepel]\nname=Extra Packages for Enterprise Linux \$releasever - \$basearch - ustc \nbaseurl=http://centos.ustc.edu.cn/epel/\$releasever/\$basearch\nfailovermethod=priority\nenabled=0\ngpgcheck=0\n" > /etc/yum.repos.d/zstack-163-yum.repo
###################
#Check DNS hijacking
###################
hostname=`hostname`
pintret=`ping -c 1 -W 2 $hostname 2>/dev/null | head -n1`
echo $pintret | grep 'PING' > /dev/null
[ $? -ne 0 ] && exit 0
ip=`echo $pintret | cut -d' ' -f 3 | cut -d'(' -f 2 | cut -d')' -f 1`
ip_1=`echo $ip | cut -d'.' -f 1`
[ "127" = "$ip_1" ] && exit 0
ip addr | grep $ip > /dev/null
[ $? -eq 0 ] && exit 0
echo "The hostname($hostname) of your machine is resolved to IP($ip) which is none of IPs of your machine.
It's likely your DNS server has been hijacking, please try fixing it or add \"ip_of_your_host $hostname\" to /etc/hosts.
DNS hijacking will cause MySQL and RabbitMQ not working."
exit 1
'''
fd, pre_install_script_path = tempfile.mkstemp()
os.fdopen(fd, 'w').write(pre_install_script)
def cleanup_pre_install_script():
os.remove(pre_install_script_path)
self.install_cleanup_routine(cleanup_pre_install_script)
post_install_script = '''
if [ -f /etc/mysql/my.cnf ]; then
# Ubuntu
sed -i 's/^bind-address/#bind-address/' /etc/mysql/my.cnf
sed -i 's/^skip-networking/#skip-networking/' /etc/mysql/my.cnf
grep '^character-set-server' /etc/mysql/my.cnf >/dev/null 2>&1
if [ $? -ne 0 ]; then
sed -i '/\[mysqld\]/a character-set-server=utf8\' /etc/mysql/my.cnf
fi
grep '^skip-name-resolve' /etc/mysql/my.cnf >/dev/null 2>&1
if [ $? -ne 0 ]; then
sed -i '/\[mysqld\]/a skip-name-resolve\' /etc/mysql/my.cnf
fi
fi
if [ -f /etc/my.cnf ]; then
# CentOS
sed -i 's/^bind-address/#bind-address/' /etc/my.cnf
sed -i 's/^skip-networking/#skip-networking/' /etc/my.cnf
grep '^character-set-server' /etc/my.cnf >/dev/null 2>&1
if [ $? -ne 0 ]; then
sed -i '/\[mysqld\]/a character-set-server=utf8\' /etc/my.cnf
fi
grep '^skip-name-resolve' /etc/my.cnf >/dev/null 2>&1
if [ $? -ne 0 ]; then
sed -i '/\[mysqld\]/a skip-name-resolve\' /etc/my.cnf
fi
fi
'''
fd, post_install_script_path = tempfile.mkstemp()
os.fdopen(fd, 'w').write(post_install_script)
def cleanup_post_install_script():
os.remove(post_install_script_path)
self.install_cleanup_routine(cleanup_post_install_script)
t = string.Template(yaml)
if args.yum:
yum_repo = args.yum
else:
yum_repo = 'false'
yaml = t.substitute({
'host': args.host,
'change_password_cmd': change_root_password_cmd,
'root_password': args.root_password,
'login_password': args.login_password,
'grant_access_cmd': grant_access_cmd,
'pre_install_script': pre_install_script_path,
'yum_folder': ctl.zstack_home,
'yum_repo': yum_repo,
'post_install_script': post_install_script_path
})
ansible(yaml, args.host, args.debug, args.ssh_key)
class InstallRabbitCmd(Command):
def __init__(self):
super(InstallRabbitCmd, self).__init__()
self.name = "install_rabbitmq"
self.description = "install RabbitMQ message broker on local or remote machine."
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='host IP, for example, 192.168.0.212, please specify the real IP rather than "localhost" or "127.0.0.1" when installing on local machine; otherwise management nodes on other machines cannot access the RabbitMQ.', required=True)
parser.add_argument('--debug', help="open Ansible debug option", action="store_true", default=False)
parser.add_argument('--no-update', help="don't update the IP address to 'CloudBus.serverIp.0' in zstack.properties", action="store_true", default=False)
parser.add_argument('--ssh-key', help="the path of private key for SSH login $host; if provided, Ansible will use the specified key as private key to SSH login the $host", default=None)
parser.add_argument('--rabbit-username', help="RabbitMQ username; if set, the username will be created on RabbitMQ. [DEFAULT] rabbitmq default username", default=None)
parser.add_argument('--rabbit-password', help="RabbitMQ password; if set, the password will be created on RabbitMQ for username specified by --rabbit-username. [DEFAULT] rabbitmq default password", default=None)
parser.add_argument('--yum', help="Use ZStack predefined yum repositories. The valid options include: alibase,aliepel,163base,ustcepel,zstack-local. NOTE: only use it when you know exactly what it does.", default=None)
def run(self, args):
if (args.rabbit_password is None and args.rabbit_username) or (args.rabbit_username and args.rabbit_password is None):
raise CtlError('--rabbit-username and --rabbit-password must be both set or not set')
yaml = '''---
- hosts: $host
remote_user: root
vars:
yum_repo: "$yum_repo"
tasks:
- name: pre-install script
script: $pre_install_script
- name: set RHEL7 yum repo
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7'
shell: echo -e "[zstack-local]\\nname=ZStack Local Yum Repo\\nbaseurl=file://$yum_folder/static/centos7_repo\\nenabled=0\\ngpgcheck=0\\n" > /etc/yum.repos.d/zstack-local.repo
- name: set RHEL6 yum repo
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '6' and ansible_distribution_version < '7'
shell: echo -e "[zstack-local]\\nname=ZStack Local Yum Repo\\nbaseurl=file://$yum_folder/static/centos6_repo\\nenabled=0\\ngpgcheck=0\\n" > /etc/yum.repos.d/zstack-local.repo
- name: install RabbitMQ on RedHat OS from user defined yum repo
when: ansible_os_family == 'RedHat' and yum_repo != 'false'
shell: yum clean metadata; yum --disablerepo=* --enablerepo={{yum_repo}} --nogpgcheck install -y rabbitmq-server libselinux-python
- name: install RabbitMQ on RedHat OS from online
when: ansible_os_family == 'RedHat' and yum_repo == 'false'
shell: yum clean metadata; yum --nogpgcheck install -y rabbitmq-server libselinux-python
- name: install RabbitMQ on Ubuntu OS
when: ansible_os_family == 'Debian'
apt: pkg={{item}} update_cache=yes
with_items:
- rabbitmq-server
- name: open 5672 port
shell: iptables-save | grep -- "-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT" > /dev/null || iptables -I INPUT -p tcp -m tcp --dport 5672 -j ACCEPT
- name: open 5673 port
shell: iptables-save | grep -- "-A INPUT -p tcp -m tcp --dport 5673 -j ACCEPT" > /dev/null || iptables -I INPUT -p tcp -m tcp --dport 5673 -j ACCEPT
- name: open 15672 port
shell: iptables-save | grep -- "-A INPUT -p tcp -m tcp --dport 15672 -j ACCEPT" > /dev/null || iptables -I INPUT -p tcp -m tcp --dport 15672 -j ACCEPT
- name: enable RabbitMQ
service: name=rabbitmq-server state=started enabled=yes
- name: post-install script
script: $post_install_script
'''
pre_script = '''
echo -e "#aliyun base\n[alibase]\nname=CentOS-\$releasever - Base - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$releasever/os/\$basearch/\ngpgcheck=0\nenabled=0\n \n#released updates \n[aliupdates]\nname=CentOS-\$releasever - Updates - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$releasever/updates/\$basearch/\nenabled=0\ngpgcheck=0\n \n[aliextras]\nname=CentOS-\$releasever - Extras - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$releasever/extras/\$basearch/\nenabled=0\ngpgcheck=0\n \n[aliepel]\nname=Extra Packages for Enterprise Linux \$releasever - \$basearce - mirrors.aliyun.com\nbaseurl=http://mirrors.aliyun.com/epel/\$releasever/\$basearch\nfailovermethod=priority\nenabled=0\ngpgcheck=0\n" > /etc/yum.repos.d/zstack-aliyun-yum.repo
echo -e "#163 base\n[163base]\nname=CentOS-\$releasever - Base - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$releasever/os/\$basearch/\ngpgcheck=0\nenabled=0\n \n#released updates \n[163updates]\nname=CentOS-\$releasever - Updates - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$releasever/updates/\$basearch/\nenabled=0\ngpgcheck=0\n \n#additional packages that may be useful\n[163extras]\nname=CentOS-\$releasever - Extras - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$releasever/extras/\$basearch/\nenabled=0\ngpgcheck=0\n \n[ustcepel]\nname=Extra Packages for Enterprise Linux \$releasever - \$basearch - ustc \nbaseurl=http://centos.ustc.edu.cn/epel/\$releasever/\$basearch\nfailovermethod=priority\nenabled=0\ngpgcheck=0\n" > /etc/yum.repos.d/zstack-163-yum.repo
###################
#Check DNS hijacking
###################
hostname=`hostname`
pintret=`ping -c 1 -W 2 $hostname 2>/dev/null | head -n1`
echo $pintret | grep 'PING' > /dev/null
[ $? -ne 0 ] && exit 0
ip=`echo $pintret | cut -d' ' -f 3 | cut -d'(' -f 2 | cut -d')' -f 1`
ip_1=`echo $ip | cut -d'.' -f 1`
[ "127" = "$ip_1" ] && exit 0
ip addr | grep $ip > /dev/null
[ $? -eq 0 ] && exit 0
echo "The hostname($hostname) of your machine is resolved to IP($ip) which is none of IPs of your machine.
It's likely your DNS server has been hijacking, please try fixing it or add \"ip_of_your_host $hostname\" to /etc/hosts.
DNS hijacking will cause MySQL and RabbitMQ not working."
exit 1
'''
fd, pre_script_path = tempfile.mkstemp()
os.fdopen(fd, 'w').write(pre_script)
def cleanup_prescript():
os.remove(pre_script_path)
self.install_cleanup_routine(cleanup_prescript)
if args.rabbit_username and args.rabbit_password:
post_script = '''set -e
rabbitmqctl add_user $username $password
rabbitmqctl set_user_tags $username administrator
rabbitmqctl set_permissions -p / $username ".*" ".*" ".*"
'''
t = string.Template(post_script)
post_script = t.substitute({
'username': args.rabbit_username,
'password': args.rabbit_password
})
else:
post_script = ''
fd, post_script_path = tempfile.mkstemp()
os.fdopen(fd, 'w').write(post_script)
def cleanup_postscript():
os.remove(post_script_path)
self.install_cleanup_routine(cleanup_postscript)
t = string.Template(yaml)
if args.yum:
yum_repo = args.yum
else:
yum_repo = 'false'
yaml = t.substitute({
'host': args.host,
'pre_install_script': pre_script_path,
'yum_folder': ctl.zstack_home,
'yum_repo': yum_repo,
'post_install_script': post_script_path
})
ansible(yaml, args.host, args.debug, args.ssh_key)
if not args.no_update:
ctl.write_property('CloudBus.serverIp.0', args.host)
info('updated CloudBus.serverIp.0=%s in %s' % (args.host, ctl.properties_file_path))
if args.rabbit_username and args.rabbit_password:
ctl.write_property('CloudBus.rabbitmqUsername', args.rabbit_username)
info('updated CloudBus.rabbitmqUsername=%s in %s' % (args.rabbit_username, ctl.properties_file_path))
ctl.write_property('CloudBus.rabbitmqPassword', args.rabbit_password)
info('updated CloudBus.rabbitmqPassword=%s in %s' % (args.rabbit_password, ctl.properties_file_path))
class InstallKairosdbCmd(Command):
PACKAGE_NAME = "kairosdb-1.1.1-1.tar.gz"
KAIROSDB_EXEC = 'KAIROSDB_EXEC'
KAIROSDB_CONF = 'KAIROSDB_CONF'
KAIROSDB_LOG = 'KAIROSDB_LOG'
def __init__(self):
super(InstallKairosdbCmd, self).__init__()
self.name = "install_kairosdb"
self.description = (
"install kairosdb"
)
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--file', help='path to the %s' % self.PACKAGE_NAME, required=False)
parser.add_argument('--listen-address', help='the IP kairosdb listens to, which cannot be 0.0.0.0', required=True)
parser.add_argument('--cassandra-rpc-address', help='the RPC address of cassandra, which must be in the format of'
'\nIP:port, for example, 192.168.0.199:9160. If omitted, the'
'\naddress will be retrieved from local cassandra YAML config,'
'\nor an error will be raised if the YAML config cannot be found', required=False)
parser.add_argument('--listen-port', help='the port kairosdb listens to, default to 18080', default=18080, required=False)
parser.add_argument('--update-zstack-config', action='store_true', default=True, help='update kairosdb config to zstack.properties', required=False)
def run(self, args):
if not args.file:
args.file = os.path.join(ctl.USER_ZSTACK_HOME_DIR, self.PACKAGE_NAME)
if not os.path.exists(args.file):
raise CtlError('cannot find %s, you may need to specify the option[--file]' % args.file)
if not args.file.endswith(self.PACKAGE_NAME):
raise CtlError('at this version, zstack only supports %s' % self.PACKAGE_NAME)
shell('su - zstack -c "tar xzf %s -C %s"' % (args.file, ctl.USER_ZSTACK_HOME_DIR))
kairosdb_dir = os.path.join(ctl.USER_ZSTACK_HOME_DIR, "kairosdb")
info("successfully installed %s to %s" % (args.file, os.path.join(ctl.USER_ZSTACK_HOME_DIR, kairosdb_dir)))
if args.listen_address == '0.0.0.0':
raise CtlError('for your data safety, please do NOT use 0.0.0.0 as the listen address')
original_conf_path = os.path.join(kairosdb_dir, "conf/kairosdb.properties")
shell("yes | cp %s %s.bak" % (original_conf_path, original_conf_path))
all_configs = []
if ctl.extra_arguments:
configs = [l.split('=', 1) for l in ctl.extra_arguments]
for l in configs:
if len(l) != 2:
raise CtlError('invalid config[%s]. The config must be in the format of key=value without spaces around the =' % l)
all_configs.append(l)
if args.cassandra_rpc_address and ':' not in args.cassandra_rpc_address:
raise CtlError('invalid --cassandra-rpc-address[%s]. It must be in the format of IP:port' % args.cassandra_rpc_address)
elif not args.cassandra_rpc_address:
cassandra_conf = ctl.get_env(InstallCassandraCmd.CASSANDRA_CONF)
if not cassandra_conf:
raise CtlError('cannot find cassandra conf[%s] in %s, have you installed cassandra? or'
' you can use --cassandra-rpc-address to set the address explicitly' % (InstallCassandraCmd.CASSANDRA_CONF, SetEnvironmentVariableCmd.PATH))
with open(cassandra_conf, 'r') as fd:
with on_error('cannot YAML load %s, it seems corrupted' % InstallCassandraCmd.CASSANDRA_CONF):
c_conf = yaml.load(fd.read())
addr = c_conf['rpc_address']
if not addr:
raise CtlError('rpc_address is not set in %s. Please fix it otherwise kairosdb cannot boot later' % InstallCassandraCmd.CASSANDRA_CONF)
port = c_conf['rpc_port']
if not port:
raise CtlError('rpc_port is not set in %s. Please fix it otherwise kairosdb cannot boot later' % InstallCassandraCmd.CASSANDRA_CONF)
args.cassandra_rpc_address = '%s:%s' % (addr, port)
all_configs.extend([
('kairosdb.service.datastore', 'org.kairosdb.datastore.cassandra.CassandraModule'),
('kairosdb.jetty.address', args.listen_address),
('kairosdb.jetty.port', args.listen_port),
('kairosdb.datastore.cassandra.host_list', args.cassandra_rpc_address)
])
prop = PropertyFile(original_conf_path)
prop.write_properties(all_configs)
if args.update_zstack_config:
ctl.write_properties([
('Kairosdb.ip', args.listen_address),
('Kairosdb.port', args.listen_port),
])
info('successfully wrote kairosdb properties to %s' % ctl.properties_file_path)
ctl.put_envs([
(self.KAIROSDB_EXEC, os.path.normpath('%s/bin/kairosdb.sh' % kairosdb_dir)),
(self.KAIROSDB_CONF, original_conf_path),
(self.KAIROSDB_LOG, os.path.join(kairosdb_dir, 'log')),
])
log_conf = os.path.normpath('%s/conf/logging/logback.xml' % kairosdb_dir)
shell('''sed -i 's/<root level="DEBUG">/<root level="INFO">/g' %s''' % log_conf)
info('successfully installed kairosdb, the config file is written to %s' % original_conf_path)
class InstallCassandraCmd(Command):
CASSANDRA_EXEC = 'CASSANDRA_EXEC'
CASSANDRA_CONF = 'CASSANDRA_CONF'
CASSANDRA_LOG = 'CASSANDRA_LOG'
def __init__(self):
super(InstallCassandraCmd, self).__init__()
self.name = "install_cassandra"
self.description = (
"install cassandra nosql database."
"\nNOTE: you can pass an extra JSON string that will be converted to the cassandra YAML config. The string must"
"\nbe quoted by a single quote('), and the content must be the valid JSON format, for example:"
"\n\nzstack-ctl install_cassandra --file /tmp/apache-cassandra-2.2.3-bin.tar.gz '{\"rpc_address\":\"192.168.0.199\", \"listen_address\":\"192.168.0.199\"}'"
)
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--file', help='path to the apache-cassandra-2.2.3-bin.tar.gz', required=False)
parser.add_argument('--user-zstack', help='do all operations with user zstack', default=True, action='store_true', required=False)
parser.add_argument('--listen-address', help='the IP used for both rpc_address and listen_address.'
'This option is overridden if rpc_address or listen_address'
' is specified in the JSON body', required=False)
def run(self, args):
if not args.file:
args.file = os.path.join(ctl.USER_ZSTACK_HOME_DIR, "apache-cassandra-2.2.3-bin.tar.gz")
if not os.path.exists(args.file):
raise CtlError('cannot find %s, you may need to specify the option[--file]' % args.file)
if not args.file.endswith("apache-cassandra-2.2.3-bin.tar.gz"):
raise CtlError('at this version, zstack only support apache-cassandra-2.2.3-bin.tar.gz')
shell('su - zstack -c "tar xzf %s -C %s"' % (args.file, ctl.USER_ZSTACK_HOME_DIR))
cassandra_dir = os.path.join(ctl.USER_ZSTACK_HOME_DIR, "apache-cassandra-2.2.3")
info("successfully installed %s to %s" % (args.file, os.path.join(ctl.USER_ZSTACK_HOME_DIR, cassandra_dir)))
yaml_conf = os.path.join(cassandra_dir, "conf/cassandra.yaml")
shell('yes | cp %s %s.bak' % (yaml_conf, yaml_conf))
if ctl.extra_arguments:
extra = ' '.join(ctl.extra_arguments)
with on_error("%s is not a valid JSON string" % extra):
conf = simplejson.loads(extra)
else:
conf = {}
if args.listen_address:
if 'rpc_address' not in conf:
conf['rpc_address'] = args.listen_address
if 'listen_address' not in conf:
conf['listen_address'] = args.listen_address
if 'commitlog_directory' not in conf:
conf['commitlog_directory'] = ['/var/lib/cassandra/commitlog']
if 'data_file_directories' not in conf:
conf['data_file_directories'] = ['/var/lib/cassandra/data']
if 'commitlog_directory' not in conf:
conf['saved_caches_directory'] = ['/var/lib/cassandra/saved_caches']
conf['start_rpc'] = True
if args.user_zstack:
with use_user_zstack():
with open(yaml_conf, 'r') as fd:
c_conf = yaml.load(fd.read())
else:
with open(yaml_conf, 'r') as fd:
c_conf = yaml.load(fd.read())
for k, v in conf.items():
c_conf[k] = v
listen_address = c_conf['listen_address']
rpc_address = c_conf['rpc_address']
if listen_address != rpc_address:
raise CtlError('listen_address[%s] and rpc_address[%s] do not match' % (listen_address, rpc_address))
seed_provider = c_conf['seed_provider']
with on_error("cannot find parameter[seeds] in %s" % yaml_conf):
# check if the parameter is in the YAML conf
_ = seed_provider[0]['parameters'][0]['seeds']
seed_provider[0]['parameters'][0]['seeds'] = listen_address
info("change parameter['seeds'] to listen_address[%s], otherwise cassandra may fail to get seeds" % listen_address)
if args.user_zstack:
with use_user_zstack():
with open(yaml_conf, 'w') as fd:
fd.write(yaml.dump(c_conf, default_flow_style=False))
else:
with open(yaml_conf, 'w') as fd:
fd.write(yaml.dump(c_conf, default_flow_style=False))
ctl.put_envs([
(self.CASSANDRA_EXEC, os.path.join(cassandra_dir, 'bin/cassandra')),
(self.CASSANDRA_CONF, yaml_conf),
(self.CASSANDRA_LOG, os.path.join(cassandra_dir, 'log')),
])
info('configs are written into %s' % yaml_conf)
class KairosdbCmd(Command):
NAME = 'kairosdb'
def __init__(self):
super(KairosdbCmd, self).__init__()
self.name = self.NAME
self.description = (
'control kairosdb life cycle'
)
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--start', help='start kairosdb', action="store_true", required=False)
parser.add_argument('--stop', help='stop kairosdb', action="store_true", required=False)
parser.add_argument('--status', help='show kairosdb status', action="store_true", required=False)
parser.add_argument('--wait-timeout', type=int, help='wait timeout(in seconds) until kairosdb web port is available. This is normally used'
' with --start option to make sure cassandra successfully starts.',
default=-1, required=False)
def _status(self, args):
return find_process_by_cmdline('org.kairosdb.core.Main')
def start(self, args):
pid = self._status(args)
if pid:
info('kairosdb[PID:%s] is already running' % pid)
return
exe = ctl.get_env(InstallKairosdbCmd.KAIROSDB_EXEC)
if not os.path.exists(exe):
raise CtlError('cannot find the variable[%s] in %s. Have you installed kaiosdb?' %
(InstallKairosdbCmd.KAIROSDB_EXEC, SetEnvironmentVariableCmd.PATH))
shell('bash %s start' % exe)
info('successfully starts kairosdb')
if args.wait_timeout < 0:
return
info('waiting for kairosdb to listen on web port until %s seconds timeout' % args.wait_timeout)
conf = ctl.get_env(InstallKairosdbCmd.KAIROSDB_CONF)
if not conf:
warn('cannot find the variable[%s] in %s, ignore --wait-timeout' %
(InstallKairosdbCmd.KAIROSDB_CONF, SetEnvironmentVariableCmd.PATH))
return
if not os.path.exists(conf):
warn('cannot find kairosdb conf at %s, ignore --wait-timeout' % conf)
return
prop = PropertyFile(conf)
port = prop.read_property('kairosdb.jetty.port')
if not port:
raise CtlError('kairosdb.jetty.port is not set in %s' % InstallKairosdbCmd.KAIROSDB_CONF)
while args.wait_timeout > 0:
ret = shell_return('netstat -nap | grep %s > /dev/null' % port)
if ret == 0:
info('kairosdb is listening on the web port[%s] now' % port)
return
time.sleep(1)
args.wait_timeout -= 1
raise CtlError("kairosdb is not listening on the web port[%s] after %s seconds, it may not successfully start,"
"please check the log file in %s" % (port, args.wait_timeout, ctl.get_env(InstallKairosdbCmd.KAIROSDB_CONF)))
def stop(self, args):
pid = self._status(args)
if not pid:
info('kairosdb is already stopped')
return
exe = ctl.get_env(InstallKairosdbCmd.KAIROSDB_EXEC)
if not os.path.exists(exe):
shell('kill %s' % pid)
else:
shell('bash %s stop' % exe)
count = 30
while count > 0:
pid = self._status(args)
if not pid:
info('successfully stopped kairosdb')
return
time.sleep(1)
count -= 1
info('kairosdb is still running after %s seconds, kill -9 it' % count)
shell('kill -9 %s' % pid)
def status(self, args):
pid = self._status(args)
if pid:
info('kairosdb[PID:%s] is running' % pid)
else:
info('kairosdb is stopped')
def run(self, args):
if args.start:
self.start(args)
elif args.stop:
self.stop(args)
elif args.status:
self.status(args)
else:
self.status(args)
class CassandraCmd(Command):
def __init__(self):
super(CassandraCmd, self).__init__()
self.name = "cassandra"
self.description = (
"control cassandra's life cycle"
)
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--start', help='start cassandra', action="store_true", required=False)
parser.add_argument('--stop', help='stop cassandra', action="store_true", required=False)
parser.add_argument('--status', help='show cassandra status', action="store_true", required=False)
parser.add_argument('--wait-timeout', type=int, help='wait timeout(in seconds) until cassandra RPC port is available. This is normally used'
' with --start option to make sure cassandra successfully starts.',
default=-1, required=False)
def start(self, args):
pid = self._status(args)
if pid:
info('cassandra[PID:%s] is already running' % pid)
return
exe = ctl.get_env(InstallCassandraCmd.CASSANDRA_EXEC)
if not exe:
raise CtlError('cannot find the variable[%s] in %s. Have you installed cassandra?' %
(InstallCassandraCmd.CASSANDRA_EXEC, SetEnvironmentVariableCmd.PATH))
# cd to the /bin folder to start cassandra, otherwise the command line
# will be too long to be truncated by the linux /proc/[pid]/cmdline, which
# leads _status() not working
shell('cd %s && bash %s' % (os.path.dirname(exe), os.path.basename(exe)))
info('successfully starts cassandra')
if args.wait_timeout <= 0:
return
info('waiting for cassandra to listen on the RPC port until timeout after %s seconds' % args.wait_timeout)
conf = ctl.get_env(InstallCassandraCmd.CASSANDRA_CONF)
if not conf:
warn('cannot find the variable[%s] in %s, ignore --wait-timeout' %
(InstallCassandraCmd.CASSANDRA_CONF, SetEnvironmentVariableCmd.PATH))
return
if not os.path.exists(conf):
warn('cannot find cassandra conf at %s, ignore --wait-timeout' % conf)
return
with open(conf, 'r') as fd:
m = yaml.load(fd.read())
port = m['rpc_port']
if not port:
warn('cannot find parameter[rpc_port] in %s, ignore --wait-timeout' % conf)
while args.wait_timeout > 0:
ret = shell_return('netstat -nap | grep %s > /dev/null' % port)
if ret == 0:
info('cassandra is listening on RPC port[%s] now' % port)
return
time.sleep(1)
args.wait_timeout -= 1
raise CtlError("cassandra is not listening on RPC port[%s] after %s seconds, it may not successfully start,"
"please check the log file in %s" % (port, args.wait_timeout, ctl.get_env(InstallCassandraCmd.CASSANDRA_LOG)))
def stop(self, args):
pid = self._status(args)
if not pid:
info('cassandra is already stopped')
return
shell('kill %s' % pid)
count = 30
while count > 0:
pid = self._status(args)
if not pid:
info('successfully stopped cassandra')
return
time.sleep(1)
count -= 1
info('cassandra is still running after %s seconds, kill -9 it' % count)
shell('kill -9 %s' % pid)
def _status(self, args):
return find_process_by_cmdline('org.apache.cassandra.service.CassandraDaemon')
def status(self, args):
pid = self._status(args)
if not pid:
info('cassandra is stopped')
else:
info('cassandra[PID:%s] is running' % pid)
def run(self, args):
if args.start:
self.start(args)
elif args.stop:
self.stop(args)
elif args.status:
self.status(args)
else:
self.status(args)
class InstallManagementNodeCmd(Command):
def __init__(self):
super(InstallManagementNodeCmd, self).__init__()
self.name = "install_management_node"
self.description = (
"install ZStack management node from current machine to a remote machine with zstack.properties."
"\nNOTE: please configure current node before installing node on other machines"
)
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='target host IP, for example, 192.168.0.212, to install ZStack management node to a remote machine', required=True)
parser.add_argument('--install-path', help='the path on remote machine where Apache Tomcat will be installed, which must be an absolute path; [DEFAULT]: /usr/local/zstack', default='/usr/local/zstack')
parser.add_argument('--source-dir', help='the source folder containing Apache Tomcat package and zstack.war, if omitted, it will default to a path related to $ZSTACK_HOME')
parser.add_argument('--debug', help="open Ansible debug option", action="store_true", default=False)
parser.add_argument('--force-reinstall', help="delete existing Apache Tomcat and resinstall ZStack", action="store_true", default=False)
parser.add_argument('--yum', help="Use ZStack predefined yum repositories. The valid options include: alibase,aliepel,163base,ustcepel,zstack-local. NOTE: only use it when you know exactly what it does.", default=None)
parser.add_argument('--ssh-key', help="the path of private key for SSH login $host; if provided, Ansible will use the specified key as private key to SSH login the $host", default=None)
def run(self, args):
if not os.path.isabs(args.install_path):
raise CtlError('%s is not an absolute path' % args.install_path)
if not args.source_dir:
args.source_dir = os.path.join(ctl.zstack_home, "../../../")
if not os.path.isdir(args.source_dir):
raise CtlError('%s is not an directory' % args.source_dir)
apache_tomcat = None
zstack = None
apache_tomcat_zip_name = None
for file in os.listdir(args.source_dir):
full_path = os.path.join(args.source_dir, file)
if file.startswith('apache-tomcat') and file.endswith('zip') and os.path.isfile(full_path):
apache_tomcat = full_path
apache_tomcat_zip_name = file
if file == 'zstack.war':
zstack = full_path
if not apache_tomcat:
raise CtlError('cannot find Apache Tomcat ZIP in %s, please use --source-dir to specify the directory containing the ZIP' % args.source_dir)
if not zstack:
raise CtlError('cannot find zstack.war in %s, please use --source-dir to specify the directory containing the WAR file' % args.source_dir)
pypi_path = os.path.join(ctl.zstack_home, "static/pypi/")
if not os.path.isdir(pypi_path):
raise CtlError('cannot find %s, please make sure you have installed ZStack management node' % pypi_path)
pypi_tar_path = os.path.join(ctl.zstack_home, "static/pypi.tar.bz")
static_path = os.path.join(ctl.zstack_home, "static")
shell('cd %s; tar jcf pypi.tar.bz pypi' % static_path)
yaml = '''---
- hosts: $host
remote_user: root
vars:
root: $install_path
yum_repo: "$yum_repo"
tasks:
- name: check remote env on RedHat OS 6
when: ansible_os_family == 'RedHat' and ansible_distribution_version < '7'
script: $pre_script_on_rh6
- name: prepare remote environment
script: $pre_script
- name: set RHEL7 yum repo
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7'
shell: echo -e "[zstack-local]\\nname=ZStack Local Yum Repo\\nbaseurl=file://$yum_folder/static/centos7_repo\\nenabled=0\\ngpgcheck=0\\n" > /etc/yum.repos.d/zstack-local.repo
- name: set RHEL6 yum repo
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '6' and ansible_distribution_version < '7'
shell: echo -e "[zstack-local]\\nname=ZStack Local Yum Repo\\nbaseurl=file://$yum_folder/static/centos6_repo\\nenabled=0\\ngpgcheck=0\\n" > /etc/yum.repos.d/zstack-local.repo
- name: install dependencies on RedHat OS from user defined repo
when: ansible_os_family == 'RedHat' and yum_repo != 'false'
shell: yum clean metadata; yum --disablerepo=* --enablerepo={{yum_repo}} --nogpgcheck install -y java-1.7.0-openjdk wget python-devel gcc autoconf tar gzip unzip python-pip openssh-clients sshpass bzip2 ntp ntpdate sudo libselinux-python
- name: install dependencies on RedHat OS from system repos
when: ansible_os_family == 'RedHat' and yum_repo == 'false'
shell: yum clean metadata; yum --nogpgcheck install -y java-1.7.0-openjdk wget python-devel gcc autoconf tar gzip unzip python-pip openssh-clients sshpass bzip2 ntp ntpdate sudo libselinux-python
- name: install dependencies Debian OS
when: ansible_os_family == 'Debian'
apt: pkg={{item}} update_cache=yes
with_items:
- openjdk-7-jdk
- wget
- python-dev
- gcc
- autoconf
- tar
- gzip
- unzip
- python-pip
- sshpass
- bzip2
- ntp
- ntpdate
- sudo
- name: install MySQL client for RedHat 6 from user defined repos
when: ansible_os_family == 'RedHat' and ansible_distribution_version < '7' and yum_repo != 'false'
shell: yum --disablerepo=* --enablerepo={{yum_repo}} --nogpgcheck install -y mysql
- name: install MySQL client for RedHat 6 from system repo
when: ansible_os_family == 'RedHat' and ansible_distribution_version < '7' and yum_repo == 'false'
shell: yum --nogpgcheck install -y mysql
- name: install MySQL client for RedHat 7 from user defined repos
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7' and yum_repo != 'false'
shell: yum --disablerepo=* --enablerepo={{yum_repo}} --nogpgcheck install -y mariadb
- name: install MySQL client for RedHat 7 from system repos
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7' and yum_repo == 'false'
shell: yum --nogpgcheck install -y mariadb
- name: install MySQL client for Ubuntu
when: ansible_os_family == 'Debian'
apt: pkg={{item}}
with_items:
- mysql-client
- name: copy pypi tar file
copy: src=$pypi_tar_path dest=$pypi_tar_path_dest
- name: untar pypi
shell: "cd /tmp/; tar jxf $pypi_tar_path_dest"
- name: install pip from local source
shell: "cd $pypi_path; pip install --ignore-installed pip*.tar.gz"
- name: install virtualenv
pip: name="virtualenv" extra_args="-i file://$pypi_path/simple --ignore-installed --trusted-host localhost"
- name: copy Apache Tomcat
copy: src=$apache_path dest={{root}}/$apache_tomcat_zip_name
- name: copy zstack.war
copy: src=$zstack_path dest={{root}}/zstack.war
- name: install ZStack
script: $post_script
- name: copy zstack.properties
copy: src=$properties_file dest={{root}}/apache-tomcat/webapps/zstack/WEB-INF/classes/zstack.properties
- name: setup zstack account
script: $setup_account
'''
pre_script = '''
echo -e "#aliyun base\n[alibase]\nname=CentOS-\$$releasever - Base - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$$releasever/os/\$$basearch/\ngpgcheck=0\nenabled=0\n \n#released updates \n[aliupdates]\nname=CentOS-\$$releasever - Updates - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$$releasever/updates/\$$basearch/\nenabled=0\ngpgcheck=0\n \n[aliextras]\nname=CentOS-\$$releasever - Extras - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$$releasever/extras/\$$basearch/\nenabled=0\ngpgcheck=0\n \n[aliepel]\nname=Extra Packages for Enterprise Linux \$$releasever - \$$basearce - mirrors.aliyun.com\nbaseurl=http://mirrors.aliyun.com/epel/\$$releasever/\$$basearch\nfailovermethod=priority\nenabled=0\ngpgcheck=0\n" > /etc/yum.repos.d/zstack-aliyun-yum.repo
echo -e "#163 base\n[163base]\nname=CentOS-\$$releasever - Base - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$$releasever/os/\$$basearch/\ngpgcheck=0\nenabled=0\n \n#released updates \n[163updates]\nname=CentOS-\$$releasever - Updates - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$$releasever/updates/\$$basearch/\nenabled=0\ngpgcheck=0\n \n#additional packages that may be useful\n[163extras]\nname=CentOS-\$$releasever - Extras - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$$releasever/extras/\$$basearch/\nenabled=0\ngpgcheck=0\n \n[ustcepel]\nname=Extra Packages for Enterprise Linux \$$releasever - \$$basearch - ustc \nbaseurl=http://centos.ustc.edu.cn/epel/\$$releasever/\$$basearch\nfailovermethod=priority\nenabled=0\ngpgcheck=0\n" > /etc/yum.repos.d/zstack-163-yum.repo
whereis zstack-ctl
if [ $$? -eq 0 ]; then
zstack-ctl stop_node
fi
apache_path=$install_path/apache-tomcat
if [[ -d $$apache_path ]] && [[ $force_resinstall -eq 0 ]]; then
echo "found existing Apache Tomcat directory $$apache_path; please use --force-reinstall to delete it and re-install"
exit 1
fi
rm -rf $install_path
mkdir -p $install_path
'''
t = string.Template(pre_script)
pre_script = t.substitute({
'force_resinstall': int(args.force_reinstall),
'install_path': args.install_path
})
fd, pre_script_path = tempfile.mkstemp(suffix='.sh')
os.fdopen(fd, 'w').write(pre_script)
pre_script_on_rh6 = '''
ZSTACK_INSTALL_LOG='/tmp/zstack_installation.log'
rpm -qi python-crypto >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Management node remote installation failed. You need to manually remove python-crypto by \n\n \`rpm -ev python-crypto\` \n\n in remote management node; otherwise it will conflict with ansible's pycrypto." >>$ZSTACK_INSTALL_LOG
exit 1
fi
'''
t = string.Template(pre_script_on_rh6)
fd, pre_script_on_rh6_path = tempfile.mkstemp(suffix='.sh')
os.fdopen(fd, 'w').write(pre_script_on_rh6)
def cleanup_pre_script():
os.remove(pre_script_path)
os.remove(pre_script_on_rh6_path)
self.install_cleanup_routine(cleanup_pre_script)
post_script = '''
set -e
filename=$apache_tomcat_zip_name
foldername="$${filename%.*}"
apache_path=$install_path/apache-tomcat
unzip $apache -d $install_path
ln -s $install_path/$$foldername $$apache_path
unzip $zstack -d $$apache_path/webapps/zstack
chmod a+x $$apache_path/bin/*
cat >> $$apache_path/bin/setenv.sh <<EOF
export CATALINA_OPTS=" -Djava.net.preferIPv4Stack=true -Dcom.sun.management.jmxremote=true"
EOF
install_script="$$apache_path/webapps/zstack/WEB-INF/classes/tools/install.sh"
eval "bash $$install_script zstack-ctl"
eval "bash $$install_script zstack-cli"
set +e
grep "ZSTACK_HOME" ~/.bashrc > /dev/null
if [ $$? -eq 0 ]; then
sed -i "s#export ZSTACK_HOME=.*#export ZSTACK_HOME=$$apache_path/webapps/zstack#" ~/.bashrc
else
echo "export ZSTACK_HOME=$$apache_path/webapps/zstack" >> ~/.bashrc
fi
which ansible-playbook &> /dev/null
if [ $$? -ne 0 ]; then
pip install -i file://$pypi_path/simple --trusted-host localhost ansible
fi
'''
t = string.Template(post_script)
post_script = t.substitute({
'install_path': args.install_path,
'apache': os.path.join(args.install_path, apache_tomcat_zip_name),
'zstack': os.path.join(args.install_path, 'zstack.war'),
'apache_tomcat_zip_name': apache_tomcat_zip_name,
'pypi_path': '/tmp/pypi/'
})
fd, post_script_path = tempfile.mkstemp(suffix='.sh')
os.fdopen(fd, 'w').write(post_script)
def cleanup_post_script():
os.remove(post_script_path)
self.install_cleanup_routine(cleanup_post_script)
setup_account = '''id -u zstack >/dev/null 2>&1 || (useradd -d $install_path zstack && mkdir -p $install_path && chown -R zstack.zstack $install_path)
grep 'zstack' /etc/sudoers >/dev/null || echo 'zstack ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
grep '^root' /etc/sudoers >/dev/null || echo 'root ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
sed -i '/requiretty$$/d' /etc/sudoers
chown -R zstack.zstack $install_path
mkdir /home/zstack && chown -R zstack.zstack /home/zstack
zstack-ctl setenv ZSTACK_HOME=$install_path/apache-tomcat/webapps/zstack
'''
t = string.Template(setup_account)
setup_account = t.substitute({
'install_path': args.install_path
})
fd, setup_account_path = tempfile.mkstemp()
os.fdopen(fd, 'w').write(setup_account)
def clean_up():
os.remove(setup_account_path)
self.install_cleanup_routine(clean_up)
t = string.Template(yaml)
if args.yum:
yum_repo = 'true'
else:
yum_repo = 'false'
yaml = t.substitute({
'host': args.host,
'install_path': args.install_path,
'apache_path': apache_tomcat,
'zstack_path': zstack,
'pre_script': pre_script_path,
'pre_script_on_rh6': pre_script_on_rh6_path,
'post_script': post_script_path,
'properties_file': ctl.properties_file_path,
'apache_tomcat_zip_name': apache_tomcat_zip_name,
'pypi_tar_path': pypi_tar_path,
'pypi_tar_path_dest': '/tmp/pypi.tar.bz',
'pypi_path': '/tmp/pypi/',
'yum_folder': ctl.zstack_home,
'yum_repo': yum_repo,
'setup_account': setup_account_path
})
ansible(yaml, args.host, args.debug, args.ssh_key)
info('successfully installed new management node on machine(%s)' % args.host)
class ShowConfiguration(Command):
def __init__(self):
super(ShowConfiguration, self).__init__()
self.name = "show_configuration"
self.description = "a shortcut that prints contents of zstack.properties to screen"
ctl.register_command(self)
def run(self, args):
shell_no_pipe('cat %s' % ctl.properties_file_path)
class SetEnvironmentVariableCmd(Command):
PATH = os.path.join(ctl.USER_ZSTACK_HOME_DIR, "zstack-ctl/ctl-env")
def __init__(self):
super(SetEnvironmentVariableCmd, self).__init__()
self.name = "setenv"
self.description = "set variables to zstack-ctl variable file at %s" % self.PATH
ctl.register_command(self)
def need_zstack_home(self):
return False
def run(self, args):
if not ctl.extra_arguments:
raise CtlError('please input variables that are in format of "key=value" split by space')
if not os.path.isdir(ctl.USER_ZSTACK_HOME_DIR):
raise CtlError('cannot find home directory(%s) of user "zstack"' % ctl.USER_ZSTACK_HOME_DIR)
with use_user_zstack():
path_dir = os.path.dirname(self.PATH)
if not os.path.isdir(path_dir):
os.makedirs(path_dir)
with open(self.PATH, 'a'):
# create the file if not existing
pass
env = PropertyFile(self.PATH)
arg_str = ' '.join(ctl.extra_arguments)
env.write_properties([arg_str.split('=', 1)])
class UnsetEnvironmentVariableCmd(Command):
NAME = 'unsetenv'
def __init__(self):
super(UnsetEnvironmentVariableCmd, self).__init__()
self.name = self.NAME
self.description = (
'unset variables in %s' % SetEnvironmentVariableCmd.PATH
)
ctl.register_command(self)
def run(self, args):
if not os.path.exists(SetEnvironmentVariableCmd.PATH):
return
if not ctl.extra_arguments:
raise CtlError('please input a list of variable names you want to unset')
env = PropertyFile(SetEnvironmentVariableCmd.PATH)
env.delete_properties(ctl.extra_arguments)
info('unset zstack environment variables: %s' % ctl.extra_arguments)
class GetEnvironmentVariableCmd(Command):
NAME = 'getenv'
def __init__(self):
super(GetEnvironmentVariableCmd, self).__init__()
self.name = self.NAME
self.description = (
"get variables from %s" % SetEnvironmentVariableCmd.PATH
)
ctl.register_command(self)
def run(self, args):
if not os.path.exists(SetEnvironmentVariableCmd.PATH):
raise CtlError('cannot find the environment variable file at %s' % SetEnvironmentVariableCmd.PATH)
ret = []
if ctl.extra_arguments:
env = PropertyFile(SetEnvironmentVariableCmd.PATH)
for key in ctl.extra_arguments:
value = env.read_property(key)
if value:
ret.append('%s=%s' % (key, value))
else:
env = PropertyFile(SetEnvironmentVariableCmd.PATH)
for k, v in env.read_all_properties():
ret.append('%s=%s' % (k, v))
info('\n'.join(ret))
class InstallWebUiCmd(Command):
def __init__(self):
super(InstallWebUiCmd, self).__init__()
self.name = "install_ui"
self.description = "install ZStack web UI"
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='target host IP, for example, 192.168.0.212, to install ZStack web UI; if omitted, it will be installed on local machine')
parser.add_argument('--ssh-key', help="the path of private key for SSH login $host; if provided, Ansible will use the specified key as private key to SSH login the $host", default=None)
parser.add_argument('--yum', help="Use ZStack predefined yum repositories. The valid options include: alibase,aliepel,163base,ustcepel,zstack-local. NOTE: only use it when you know exactly what it does.", default=None)
def _install_to_local(self):
install_script = os.path.join(ctl.zstack_home, "WEB-INF/classes/tools/install.sh")
if not os.path.isfile(install_script):
raise CtlError('cannot find %s, please make sure you have installed ZStack management node' % install_script)
info('found installation script at %s, start installing ZStack web UI' % install_script)
shell('bash %s zstack-dashboard' % install_script)
def run(self, args):
if not args.host:
self._install_to_local()
return
tools_path = os.path.join(ctl.zstack_home, "WEB-INF/classes/tools/")
if not os.path.isdir(tools_path):
raise CtlError('cannot find %s, please make sure you have installed ZStack management node' % tools_path)
ui_binary = None
for l in os.listdir(tools_path):
if l.startswith('zstack_dashboard'):
ui_binary = l
break
if not ui_binary:
raise CtlError('cannot find zstack-dashboard package under %s, please make sure you have installed ZStack management node' % tools_path)
ui_binary_path = os.path.join(tools_path, ui_binary)
pypi_path = os.path.join(ctl.zstack_home, "static/pypi/")
if not os.path.isdir(pypi_path):
raise CtlError('cannot find %s, please make sure you have installed ZStack management node' % pypi_path)
pypi_tar_path = os.path.join(ctl.zstack_home, "static/pypi.tar.bz")
if not os.path.isfile(pypi_tar_path):
static_path = os.path.join(ctl.zstack_home, "static")
os.system('cd %s; tar jcf pypi.tar.bz pypi' % static_path)
yaml = '''---
- hosts: $host
remote_user: root
vars:
virtualenv_root: /var/lib/zstack/virtualenv/zstack-dashboard
yum_repo: "$yum_repo"
tasks:
- name: pre-install script
script: $pre_install_script
- name: set RHEL7 yum repo
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '7'
shell: echo -e "[zstack-local]\\nname=ZStack Local Yum Repo\\nbaseurl=file://$yum_folder/static/centos7_repo\\nenabled=0\\ngpgcheck=0\\n" > /etc/yum.repos.d/zstack-local.repo
- name: set RHEL6 yum repo
when: ansible_os_family == 'RedHat' and ansible_distribution_version >= '6' and ansible_distribution_version < '7'
shell: echo -e "[zstack-local]\\nname=ZStack Local Yum Repo\\nbaseurl=file://$yum_folder/static/centos6_repo\\nenabled=0\\ngpgcheck=0\\n" > /etc/yum.repos.d/zstack-local.repo
- name: install Python pip for RedHat OS from user defined repo
when: ansible_os_family == 'RedHat' and yum_repo != 'false'
shell: yum clean metadata; yum --disablerepo=* --enablerepo={{yum_repo}} --nogpgcheck install -y libselinux-python python-pip bzip2 python-devel gcc autoconf
- name: install Python pip for RedHat OS from system repo
when: ansible_os_family == 'RedHat' and yum_repo == 'false'
shell: yum clean metadata; yum --nogpgcheck install -y libselinux-python python-pip bzip2 python-devel gcc autoconf
- name: copy zstack-dashboard package
copy: src=$src dest=$dest
- name: copy pypi tar file
copy: src=$pypi_tar_path dest=$pypi_tar_path_dest
- name: untar pypi
shell: "cd /tmp/; tar jxf $pypi_tar_path_dest"
- name: install Python pip for Ubuntu
when: ansible_os_family == 'Debian'
apt: pkg=python-pip update_cache=yes
- name: install pip from local source
shell: "cd $pypi_path; pip install --ignore-installed pip*.tar.gz"
- shell: virtualenv --version | grep "12.1.1"
register: virtualenv_ret
ignore_errors: True
- name: install virtualenv
pip: name=virtualenv version=12.1.1 extra_args="--ignore-installed --trusted-host localhost -i file://$pypi_path/simple"
when: virtualenv_ret.rc != 0
- name: create virtualenv
shell: "rm -rf {{virtualenv_root}} && virtualenv {{virtualenv_root}}"
- name: install zstack-dashboard
pip: name=$dest extra_args="--trusted-host localhost -i file://$pypi_path/simple" virtualenv="{{virtualenv_root}}"
'''
pre_script = '''
echo -e "#aliyun base\n[alibase]\nname=CentOS-\$releasever - Base - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$releasever/os/\$basearch/\ngpgcheck=0\nenabled=0\n \n#released updates \n[aliupdates]\nname=CentOS-\$releasever - Updates - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$releasever/updates/\$basearch/\nenabled=0\ngpgcheck=0\n \n[aliextras]\nname=CentOS-\$releasever - Extras - mirrors.aliyun.com\nfailovermethod=priority\nbaseurl=http://mirrors.aliyun.com/centos/\$releasever/extras/\$basearch/\nenabled=0\ngpgcheck=0\n \n[aliepel]\nname=Extra Packages for Enterprise Linux \$releasever - \$basearce - mirrors.aliyun.com\nbaseurl=http://mirrors.aliyun.com/epel/\$releasever/\$basearch\nfailovermethod=priority\nenabled=0\ngpgcheck=0\n" > /etc/yum.repos.d/zstack-aliyun-yum.repo
echo -e "#163 base\n[163base]\nname=CentOS-\$releasever - Base - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$releasever/os/\$basearch/\ngpgcheck=0\nenabled=0\n \n#released updates \n[163updates]\nname=CentOS-\$releasever - Updates - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$releasever/updates/\$basearch/\nenabled=0\ngpgcheck=0\n \n#additional packages that may be useful\n[163extras]\nname=CentOS-\$releasever - Extras - mirrors.163.com\nfailovermethod=priority\nbaseurl=http://mirrors.163.com/centos/\$releasever/extras/\$basearch/\nenabled=0\ngpgcheck=0\n \n[ustcepel]\nname=Extra Packages for Enterprise Linux \$releasever - \$basearch - ustc \nbaseurl=http://centos.ustc.edu.cn/epel/\$releasever/\$basearch\nfailovermethod=priority\nenabled=0\ngpgcheck=0\n" > /etc/yum.repos.d/zstack-163-yum.repo
'''
fd, pre_script_path = tempfile.mkstemp()
os.fdopen(fd, 'w').write(pre_script)
def cleanup_prescript():
os.remove(pre_script_path)
self.install_cleanup_routine(cleanup_prescript)
t = string.Template(yaml)
if args.yum:
yum_repo = args.yum
else:
yum_repo = 'false'
yaml = t.substitute({
"src": ui_binary_path,
"dest": os.path.join('/tmp', ui_binary),
"host": args.host,
'pre_install_script': pre_script_path,
'pypi_tar_path': pypi_tar_path,
'pypi_tar_path_dest': '/tmp/pypi.tar.bz',
'pypi_path': '/tmp/pypi/',
'yum_folder': ctl.zstack_home,
'yum_repo': yum_repo
})
ansible(yaml, args.host, ssh_key=args.ssh_key)
class BootstrapCmd(Command):
def __init__(self):
super(BootstrapCmd, self).__init__()
self.name = 'bootstrap'
self.description = (
'create user and group of "zstack" and add "zstack" to sudoers;'
'\nthis command is only needed by installation script'
' and users that install ZStack manually'
)
ctl.register_command(self)
def need_zstack_user(self):
return False
def run(self, args):
shell('id -u zstack 2>/dev/null || (useradd -d %s zstack -s /bin/false && mkdir -p %s && chown -R zstack.zstack %s)' % (ctl.USER_ZSTACK_HOME_DIR, ctl.USER_ZSTACK_HOME_DIR, ctl.USER_ZSTACK_HOME_DIR))
shell("grep 'zstack' /etc/sudoers || echo 'zstack ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers")
shell('mkdir -p %s && chown zstack:zstack %s' % (ctl.USER_ZSTACK_HOME_DIR, ctl.USER_ZSTACK_HOME_DIR))
class UpgradeManagementNodeCmd(Command):
def __init__(self):
super(UpgradeManagementNodeCmd, self).__init__()
self.name = "upgrade_management_node"
self.description = 'upgrade the management node to a specified version'
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='IP or DNS name of the machine to upgrade the management node', default=None)
parser.add_argument('--war-file', help='path to zstack.war. A HTTP/HTTPS url or a path to a local zstack.war', required=True)
parser.add_argument('--debug', help="open Ansible debug option", action="store_true", default=False)
parser.add_argument('--ssh-key', help="the path of private key for SSH login $host; if provided, Ansible will use the specified key as private key to SSH login the $host", default=None)
def run(self, args):
error_if_tool_is_missing('unzip')
need_download = args.war_file.startswith('http')
if need_download:
error_if_tool_is_missing('wget')
upgrade_tmp_dir = os.path.join(ctl.USER_ZSTACK_HOME_DIR, 'upgrade', time.strftime('%Y-%m-%d-%H-%M-%S', time.gmtime()))
shell('mkdir -p %s' % upgrade_tmp_dir)
property_file_backup_path = os.path.join(upgrade_tmp_dir, 'zstack.properties')
class NewWarFilePath(object):
self.path = None
new_war = NewWarFilePath()
if not need_download:
new_war.path = expand_path(args.war_file)
if not os.path.exists(new_war.path):
raise CtlError('%s not found' % new_war.path)
def local_upgrade():
def backup():
ctl.internal_run('save_config', '--save-to %s' % os.path.dirname(property_file_backup_path))
shell('cp -r %s %s' % (ctl.zstack_home, upgrade_tmp_dir))
info('backup %s to %s' % (ctl.zstack_home, upgrade_tmp_dir))
def download_war_if_needed():
if need_download:
new_war.path = os.path.join(upgrade_tmp_dir, 'new', 'zstack.war')
shell_no_pipe('wget --no-check-certificate %s -O %s' % (args.war_file, new_war.path))
info('downloaded new zstack.war to %s' % new_war.path)
def stop_node():
info('start to stop the management node ...')
ctl.internal_run('stop_node')
def upgrade():
info('start to upgrade the management node ...')
shell('rm -rf %s' % ctl.zstack_home)
if ctl.zstack_home.endswith('/'):
webapp_dir = os.path.dirname(os.path.dirname(ctl.zstack_home))
else:
webapp_dir = os.path.dirname(ctl.zstack_home)
shell('cp %s %s' % (new_war.path, webapp_dir))
ShellCmd('unzip %s -d zstack' % os.path.basename(new_war.path), workdir=webapp_dir)()
def restore_config():
info('restoring the zstack.properties ...')
ctl.internal_run('restore_config', '--restore-from %s' % property_file_backup_path)
def install_tools():
info('upgrading zstack-cli, zstack-ctl; this may cost several minutes ...')
install_script = os.path.join(ctl.zstack_home, "WEB-INF/classes/tools/install.sh")
if not os.path.isfile(install_script):
raise CtlError('cannot find %s, please make sure you have installed ZStack management node' % install_script)
shell("bash %s zstack-cli" % install_script)
shell("bash %s zstack-ctl" % install_script)
info('successfully upgraded zstack-cli, zstack-ctl')
def save_new_war():
sdir = os.path.join(ctl.zstack_home, "../../../")
shell('yes | cp %s %s' % (new_war.path, sdir))
def chown_to_zstack():
info('change permission to user zstack')
shell('chown -R zstack:zstack %s' % os.path.join(ctl.zstack_home, '../../'))
backup()
download_war_if_needed()
stop_node()
upgrade()
restore_config()
install_tools()
save_new_war()
chown_to_zstack()
info('----------------------------------------------\n'
'Successfully upgraded the ZStack management node to a new version.\n'
'We backup the old zstack as follows:\n'
'\tzstack.properties: %s\n'
'\tzstack folder: %s\n'
'Please test your new ZStack. If everything is OK and stable, you can manually delete those backup by deleting %s.\n'
'Otherwise you can use them to rollback to the previous version\n'
'-----------------------------------------------\n' %
(property_file_backup_path, os.path.join(upgrade_tmp_dir, 'zstack'), upgrade_tmp_dir))
def remote_upgrade():
need_copy = 'true'
src_war = new_war.path
dst_war = '/tmp/zstack.war'
if need_download:
need_copy = 'false'
src_war = args.war_file
dst_war = args.war_file
upgrade_script = '''
zstack-ctl upgrade_management_node --war-file=$war_file
if [ $$? -ne 0 ]; then
echo 'failed to upgrade the remote management node'
exit 1
fi
if [ "$need_copy" == "true" ]; then
rm -f $war_file
fi
'''
t = string.Template(upgrade_script)
upgrade_script = t.substitute({
'war_file': dst_war,
'need_copy': need_copy
})
fd, upgrade_script_path = tempfile.mkstemp(suffix='.sh')
os.fdopen(fd, 'w').write(upgrade_script)
def cleanup_upgrade_script():
os.remove(upgrade_script_path)
self.install_cleanup_routine(cleanup_upgrade_script)
yaml = '''---
- hosts: $host
remote_user: root
vars:
need_copy: "$need_copy"
tasks:
- name: copy zstack.war to remote
copy: src=$src_war dest=$dst_war
when: need_copy == 'true'
- name: upgrade management node
script: $upgrade_script
register: output
ignore_errors: yes
- name: failure
fail: msg="failed to upgrade the remote management node. {{ output.stdout }} {{ output.stderr }}"
when: output.rc != 0
'''
t = string.Template(yaml)
yaml = t.substitute({
"src_war": src_war,
"dst_war": dst_war,
"host": args.host,
"need_copy": need_copy,
"upgrade_script": upgrade_script_path
})
info('start to upgrade the remote management node; the process may cost several minutes ...')
ansible(yaml, args.host, args.debug, ssh_key=args.ssh_key)
info('upgraded the remote management node successfully')
if args.host:
remote_upgrade()
else:
local_upgrade()
class UpgradeDbCmd(Command):
def __init__(self):
super(UpgradeDbCmd, self).__init__()
self.name = 'upgrade_db'
self.description = (
'upgrade the database from current version to a new version'
)
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--force', help='bypass management nodes status check.'
'\nNOTE: only use it when you know exactly what it does', action='store_true', default=False)
parser.add_argument('--no-backup', help='do NOT backup the database. If the database is very large and you have manually backup it, using this option will fast the upgrade process. [DEFAULT] false', default=False)
parser.add_argument('--dry-run', help='Check if db could be upgraded. [DEFAULT] not set', action='store_true', default=False)
def run(self, args):
error_if_tool_is_missing('mysqldump')
error_if_tool_is_missing('mysql')
db_url = ctl.get_db_url()
if 'zstack' not in db_url:
db_url = '%s/zstack' % db_url.rstrip('/')
db_hostname, db_port, db_user, db_password = ctl.get_database_portal()
flyway_path = os.path.join(ctl.zstack_home, 'WEB-INF/classes/tools/flyway-3.2.1/flyway')
if not os.path.exists(flyway_path):
raise CtlError('cannot find %s. Have you run upgrade_management_node?' % flyway_path)
upgrading_schema_dir = os.path.join(ctl.zstack_home, 'WEB-INF/classes/db/upgrade/')
if not os.path.exists(upgrading_schema_dir):
raise CtlError('cannot find %s. Have you run upgrade_management_node?' % upgrading_schema_dir)
ctl.check_if_management_node_has_stopped(args.force)
if args.dry_run:
info('Dry run finished. Database could be upgraded. ')
return True
def backup_current_database():
if args.no_backup:
return
info('start to backup the database ...')
db_backup_path = os.path.join(ctl.USER_ZSTACK_HOME_DIR, 'db_backup', time.strftime('%Y-%m-%d-%H-%M-%S', time.gmtime()), 'backup.sql')
shell('mkdir -p %s' % os.path.dirname(db_backup_path))
if db_password:
shell('mysqldump -u %s -p%s --host %s --port %s zstack > %s' % (db_user, db_password, db_hostname, db_port, db_backup_path))
else:
shell('mysqldump -u %s --host %s --port %s zstack > %s' % (db_user, db_hostname, db_port, db_backup_path))
info('successfully backup the database to %s' % db_backup_path)
def create_schema_version_table_if_needed():
if db_password:
out = shell('''mysql -u %s -p%s --host %s --port %s -t zstack -e "show tables like 'schema_version'"''' %
(db_user, db_password, db_hostname, db_port))
else:
out = shell('''mysql -u %s --host %s --port %s -t zstack -e "show tables like 'schema_version'"''' %
(db_user, db_hostname, db_port))
if 'schema_version' in out:
return
info('version table "schema_version" is not existing; initializing a new version table first')
if db_password:
shell_no_pipe('bash %s baseline -baselineVersion=0.6 -baselineDescription="0.6 version" -user=%s -password=%s -url=%s' %
(flyway_path, db_user, db_password, db_url))
else:
shell_no_pipe('bash %s baseline -baselineVersion=0.6 -baselineDescription="0.6 version" -user=%s -url=%s' %
(flyway_path, db_user, db_url))
def migrate():
schema_path = 'filesystem:%s' % upgrading_schema_dir
if db_password:
shell_no_pipe('bash %s migrate -user=%s -password=%s -url=%s -locations=%s' % (flyway_path, db_user, db_password, db_url, schema_path))
else:
shell_no_pipe('bash %s migrate -user=%s -url=%s -locations=%s' % (flyway_path, db_user, db_url, schema_path))
info('Successfully upgraded the database to the latest version.\n')
backup_current_database()
create_schema_version_table_if_needed()
migrate()
class UpgradeCtlCmd(Command):
def __init__(self):
super(UpgradeCtlCmd, self).__init__()
self.name = 'upgrade_ctl'
self.description = (
'upgrade the zstack-ctl to a new version'
)
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--package', help='the path to the new zstack-ctl package', required=True)
def run(self, args):
error_if_tool_is_missing('pip')
path = expand_path(args.package)
if not os.path.exists(path):
raise CtlError('%s not found' % path)
pypi_path = os.path.join(ctl.zstack_home, "static/pypi/")
if not os.path.isdir(pypi_path):
raise CtlError('cannot find %s, please make sure you have installed ZStack management node' % pypi_path)
install_script = '''set -e
which virtualenv &>/dev/null
if [ $$? != 0 ]; then
pip install -i file://$pypi_path/simple --trusted-host localhost virtualenv
fi
CTL_VIRENV_PATH=/var/lib/zstack/virtualenv/zstackctl
rm -rf $$CTL_VIRENV_PATH
virtualenv $$CTL_VIRENV_PATH
. $$CTL_VIRENV_PATH/bin/activate
pip install -i file://$pypi_path/simple --trusted-host --ignore-installed $package || exit 1
chmod +x /usr/bin/zstack-ctl
'''
script(install_script, {"pypi_path": pypi_path, "package": args.package})
info('successfully upgraded zstack-ctl to %s' % args.package)
class RollbackManagementNodeCmd(Command):
def __init__(self):
super(RollbackManagementNodeCmd, self).__init__()
self.name = "rollback_management_node"
self.description = "rollback the management node to a previous version if the upgrade fails"
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help='the IP or DNS name of machine to rollback the management node')
parser.add_argument('--war-file', help='path to zstack.war. A HTTP/HTTPS url or a path to a local zstack.war', required=True)
parser.add_argument('--debug', help="open Ansible debug option", action="store_true", default=False)
parser.add_argument('--ssh-key', help="the path of private key for SSH login $host; if provided, Ansible will use the specified key as private key to SSH login the $host", default=None)
parser.add_argument('--property-file', help="the path to zstack.properties. If omitted, the current zstack.properties will be used", default=None)
def run(self, args):
error_if_tool_is_missing('unzip')
rollback_tmp_dir = os.path.join(ctl.USER_ZSTACK_HOME_DIR, 'rollback', time.strftime('%Y-%m-%d-%H-%M-%S', time.gmtime()))
shell('mkdir -p %s' % rollback_tmp_dir)
need_download = args.war_file.startswith('http')
class Info(object):
def __init__(self):
self.war_path = None
self.property_file = None
rollbackinfo = Info()
def local_rollback():
def backup_current_zstack():
info('start to backup the current zstack ...')
shell('cp -r %s %s' % (ctl.zstack_home, rollback_tmp_dir))
info('backup %s to %s' % (ctl.zstack_home, rollback_tmp_dir))
info('successfully backup the current zstack to %s' % os.path.join(rollback_tmp_dir, os.path.basename(ctl.zstack_home)))
def download_war_if_needed():
if need_download:
rollbackinfo.war_path = os.path.join(rollback_tmp_dir, 'zstack.war')
shell_no_pipe('wget --no-check-certificate %s -O %s' % (args.war_file, rollbackinfo.war_path))
info('downloaded zstack.war to %s' % rollbackinfo.war_path)
else:
rollbackinfo.war_path = expand_path(args.war_file)
if not os.path.exists(rollbackinfo.war_path):
raise CtlError('%s not found' % rollbackinfo.war_path)
def save_property_file_if_needed():
if not args.property_file:
ctl.internal_run('save_config', '--save-to %s' % rollback_tmp_dir)
rollbackinfo.property_file = os.path.join(rollback_tmp_dir, 'zstack.properties')
else:
rollbackinfo.property_file = args.property_file
if not os.path.exists(rollbackinfo.property_file):
raise CtlError('%s not found' % rollbackinfo.property_file)
def stop_node():
info('start to stop the management node ...')
ctl.internal_run('stop_node')
def rollback():
info('start to rollback the management node ...')
shell('rm -rf %s' % ctl.zstack_home)
shell('unzip %s -d %s' % (rollbackinfo.war_path, ctl.zstack_home))
def restore_config():
info('restoring the zstack.properties ...')
ctl.internal_run('restore_config', '--restore-from %s' % rollbackinfo.property_file)
def install_tools():
info('rollback zstack-cli, zstack-ctl to the previous version. This may cost several minutes ...')
install_script = os.path.join(ctl.zstack_home, "WEB-INF/classes/tools/install.sh")
if not os.path.isfile(install_script):
raise CtlError('cannot find %s, please make sure you have installed ZStack management node' % install_script)
shell("bash %s zstack-cli" % install_script)
shell("bash %s zstack-ctl" % install_script)
info('successfully upgraded zstack-cli, zstack-ctl')
backup_current_zstack()
download_war_if_needed()
save_property_file_if_needed()
stop_node()
rollback()
restore_config()
install_tools()
info('----------------------------------------------\n'
'Successfully rollback the ZStack management node to a previous version.\n'
'We backup the current zstack as follows:\n'
'\tzstack.properties: %s\n'
'\tzstack folder: %s\n'
'Please test your ZStack. If everything is OK and stable, you can manually delete those backup by deleting %s.\n'
'-----------------------------------------------\n' %
(rollbackinfo.property_file, os.path.join(rollback_tmp_dir, os.path.basename(ctl.zstack_home)), rollback_tmp_dir))
def remote_rollback():
error_if_tool_is_missing('wget')
need_copy = 'true'
src_war = rollbackinfo.war_path
dst_war = '/tmp/zstack.war'
if need_download:
need_copy = 'false'
src_war = args.war_file
dst_war = args.war_file
rollback_script = '''
zstack-ctl rollback_management_node --war-file=$war_file
if [ $$? -ne 0 ]; then
echo 'failed to rollback the remote management node'
exit 1
fi
if [ "$need_copy" == "true" ]; then
rm -f $war_file
fi
'''
t = string.Template(rollback_script)
rollback_script = t.substitute({
'war_file': dst_war,
'need_copy': need_copy
})
fd, rollback_script_path = tempfile.mkstemp(suffix='.sh')
os.fdopen(fd, 'w').write(rollback_script)
def cleanup_rollback_script():
os.remove(rollback_script_path)
self.install_cleanup_routine(cleanup_rollback_script)
yaml = '''---
- hosts: $host
remote_user: root
vars:
need_copy: "$need_copy"
tasks:
- name: copy zstack.war to remote
copy: src=$src_war dest=$dst_war
when: need_copy == 'true'
- name: rollback the management node
script: $rollback_script
register: output
ignore_errors: yes
- name: failure
fail: msg="failed to rollback the remote management node. {{ output.stdout }} {{ output.stderr }}"
when: output.rc != 0
'''
t = string.Template(yaml)
yaml = t.substitute({
"src_war": src_war,
"dst_war": dst_war,
"host": args.host,
"need_copy": need_copy,
"rollback_script": rollback_script_path
})
info('start to rollback the remote management node; the process may cost several minutes ...')
ansible(yaml, args.host, args.debug, ssh_key=args.ssh_key)
info('successfully rollback the remote management node')
if args.host:
remote_rollback()
else:
local_rollback()
class RollbackDatabaseCmd(Command):
def __init__(self):
super(RollbackDatabaseCmd, self).__init__()
self.name = 'rollback_db'
self.description = "rollback the database to the previous version if the upgrade fails"
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--db-dump', help="the previous database dump file", required=True)
parser.add_argument('--root-password', help="the password for mysql root user. [DEFAULT] empty password")
parser.add_argument('--force', help='bypass management nodes status check.'
'\nNOTE: only use it when you know exactly what it does', action='store_true', default=False)
def run(self, args):
error_if_tool_is_missing('mysql')
ctl.check_if_management_node_has_stopped(args.force)
if not os.path.exists(args.db_dump):
raise CtlError('%s not found' % args.db_dump)
host, port, _, _ = ctl.get_database_portal()
if args.root_password:
cmd = ShellCmd('mysql -u root -p%s --host %s --port %s -e "select 1"' % (args.root_password, host, port))
else:
cmd = ShellCmd('mysql -u root --host %s --port %s -e "select 1"' % (host, port))
cmd(False)
if cmd.return_code != 0:
error_not_exit('failed to test the mysql server. You may have provided a wrong password of the root user. Please use --root-password to provide the correct password')
cmd.raise_error()
info('start to rollback the database ...')
if args.root_password:
shell('mysql -u root -p%s --host %s --port %s -t zstack < %s' % (args.root_password, host, port, args.db_dump))
else:
shell('mysql -u root --host %s --port %s -t zstack < %s' % (host, port, args.db_dump))
info('successfully rollback the database to the dump file %s' % args.db_dump)
class StopUiCmd(Command):
def __init__(self):
super(StopUiCmd, self).__init__()
self.name = 'stop_ui'
self.description = "stop UI server on the local or remote host"
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help="UI server IP. [DEFAULT] localhost", default='localhost')
def _remote_stop(self, host):
cmd = '/etc/init.d/zstack-dashboard stop'
ssh_run_no_pipe(host, cmd)
def run(self, args):
if args.host != 'localhost':
self._remote_stop(args.host)
return
pidfile = '/var/run/zstack/zstack-dashboard.pid'
if os.path.exists(pidfile):
with open(pidfile, 'r') as fd:
pid = fd.readline()
pid = pid.strip(' \t\n\r')
shell('kill %s >/dev/null 2>&1' % pid, is_exception=False)
def stop_all():
pid = find_process_by_cmdline('zstack_dashboard')
if pid:
shell('kill -9 %s >/dev/null 2>&1' % pid)
stop_all()
else:
return
stop_all()
info('successfully stopped the UI server')
class UiStatusCmd(Command):
def __init__(self):
super(UiStatusCmd, self).__init__()
self.name = "ui_status"
self.description = "check the UI server status on the local or remote host."
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help="UI server IP. [DEFAULT] localhost", default='localhost')
def _remote_status(self, host):
cmd = '/etc/init.d/zstack-dashboard status'
ssh_run_no_pipe(host, cmd)
def run(self, args):
if args.host != 'localhost':
self._remote_status(args.host)
return
pidfile = '/var/run/zstack/zstack-dashboard.pid'
if os.path.exists(pidfile):
with open(pidfile, 'r') as fd:
pid = fd.readline()
pid = pid.strip(' \t\n\r')
check_pid_cmd = ShellCmd('ps -p %s > /dev/null' % pid)
check_pid_cmd(is_exception=False)
if check_pid_cmd.return_code == 0:
info('%s: [PID:%s]' % (colored('Running', 'green'), pid))
return
pid = find_process_by_cmdline('zstack_dashboard')
if pid:
info('%s: [PID: %s]' % (colored('Zombie', 'yellow'), pid))
else:
info('%s: [PID: %s]' % (colored('Stopped', 'red'), pid))
class InstallLicenseCmd(Command):
def __init__(self):
super(InstallLicenseCmd, self).__init__()
self.name = "install_license"
self.description = "install zstack license"
ctl.register_command(self)
def install_argparse_arguments(self, parser):
parser.add_argument('--license', '-l', help="path to the license file", required=True)
parser.add_argument('--prikey', help="[OPTIONAL] the path to the private key used to generate license request")
def run(self, args):
lpath = expand_path(args.license)
if not os.path.isfile(lpath):
raise CtlError('cannot find the license file at %s' % args.license)
ppath = None
if args.prikey:
ppath = expand_path(args.prikey)
if not os.path.isfile(ppath):
raise CtlError('cannot find the private key file at %s' % args.prikey)
license_folder = os.path.join(ctl.USER_ZSTACK_HOME_DIR, 'license')
shell('''su - zstack -c "mkdir -p %s"''' % license_folder)
shell('''yes | cp %s %s/license.txt''' % (lpath, license_folder))
shell('''chown zstack:zstack %s/license.txt''' % license_folder)
info("successfully installed the license file to %s/license.txt" % license_folder)
if ppath:
shell('''yes | cp %s %s/pri.key''' % (ppath, license_folder))
shell('''chown zstack:zstack %s/pri.key''' % license_folder)
info("successfully installed the private key file to %s/pri.key" % license_folder)
class StartUiCmd(Command):
PID_FILE = '/var/run/zstack/zstack-dashboard.pid'
def __init__(self):
super(StartUiCmd, self).__init__()
self.name = "start_ui"
self.description = "start UI server on the local or remote host"
ctl.register_command(self)
if not os.path.exists(os.path.dirname(self.PID_FILE)):
shell("mkdir -p %s" % os.path.dirname(self.PID_FILE))
shell("mkdir -p /var/log/zstack")
def install_argparse_arguments(self, parser):
parser.add_argument('--host', help="UI server IP. [DEFAULT] localhost", default='localhost')
def _remote_start(self, host, params):
cmd = '/etc/init.d/zstack-dashboard start --rabbitmq %s' % params
ssh_run_no_pipe(host, cmd)
info('successfully start the UI server on the remote host[%s]' % host)
def _check_status(self):
if os.path.exists(self.PID_FILE):
with open(self.PID_FILE, 'r') as fd:
pid = fd.readline()
pid = pid.strip(' \t\n\r')
check_pid_cmd = ShellCmd('ps -p %s > /dev/null' % pid)
check_pid_cmd(is_exception=False)
if check_pid_cmd.return_code == 0:
info('UI server is still running[PID:%s]' % pid)
return False
pid = find_process_by_cmdline('zstack_dashboard')
if pid:
info('found a zombie UI server[PID:%s], kill it and start a new one' % pid)
shell('kill -9 %s > /dev/null' % pid)
return True
def run(self, args):
ips = ctl.read_property_list("CloudBus.serverIp.")
if not ips:
raise CtlError('no RabbitMQ IPs found in %s. The IPs should be configured as CloudBus.serverIp.0, CloudBus.serverIp.1 ... CloudBus.serverIp.N' % ctl.properties_file_path)
ips = [v for k, v in ips]
username = ctl.read_property("CloudBus.rabbitmqUsername")
password = ctl.read_property("CloudBus.rabbitmqPassword")
if username and not password:
raise CtlError('CloudBus.rabbitmqUsername is configured but CloudBus.rabbitmqPassword is not. They must be both set or not set. Check %s' % ctl.properties_file_path)
if not username and password:
raise CtlError('CloudBus.rabbitmqPassword is configured but CloudBus.rabbitmqUsername is not. They must be both set or not set. Check %s' % ctl.properties_file_path)
if username and password:
urls = ["%s:%s@%s" % (username, password, ip) for ip in ips]
else:
urls = ips
param = ','.join(urls)
if args.host != 'localhost':
self._remote_start(args.host, param)
return
virtualenv = '/var/lib/zstack/virtualenv/zstack-dashboard'
if not os.path.exists(virtualenv):
raise CtlError('%s not found. Are you sure the UI server is installed on %s?' % (virtualenv, args.host))
if not self._check_status():
return
shell('iptables-save | grep -- "-A INPUT -p tcp -m tcp --dport 5000 -j ACCEPT" > /dev/null || iptables -I INPUT -p tcp -m tcp --dport 5000 -j ACCEPT')
scmd = '. %s/bin/activate\nnohup python -c "from zstack_dashboard import web; web.main()" --rabbitmq %s >/var/log/zstack/zstack-dashboard.log 2>&1 </dev/null &' % (virtualenv, param)
script(scmd, no_pipe=True)
@loop_until_timeout(5, 0.5)
def write_pid():
pid = find_process_by_cmdline('zstack_dashboard')
if pid:
with open(self.PID_FILE, 'w') as fd:
fd.write(str(pid))
return True
else:
return False
write_pid()
pid = find_process_by_cmdline('zstack_dashboard')
info('successfully started UI server on the local host, PID[%s]' % pid)
def main():
BootstrapCmd()
DeployDBCmd()
ShowStatusCmd()
TailLogCmd()
StartCmd()
StopCmd()
SaveConfigCmd()
RestoreConfigCmd()
ConfigureCmd()
InstallDbCmd()
InstallRabbitCmd()
InstallManagementNodeCmd()
ShowConfiguration()
SetEnvironmentVariableCmd()
GetEnvironmentVariableCmd()
InstallWebUiCmd()
UpgradeManagementNodeCmd()
UpgradeDbCmd()
UpgradeCtlCmd()
RollbackManagementNodeCmd()
RollbackDatabaseCmd()
StartUiCmd()
StopUiCmd()
UiStatusCmd()
InstallCassandraCmd()
InstallKairosdbCmd()
CassandraCmd()
KairosdbCmd()
StartAllCmd()
StopAllCmd()
InstallLicenseCmd()
UnsetEnvironmentVariableCmd()
try:
ctl.run()
except CtlError as e:
if ctl.verbose:
error_not_exit(traceback.format_exc())
error(str(e))
if __name__ == '__main__':
main()
| {
"content_hash": "d36ab004eab2dd35f35a5e7c959de62b",
"timestamp": "",
"source": "github",
"line_count": 3361,
"max_line_length": 893,
"avg_line_length": 42.66319547753645,
"alnum_prop": 0.6053727221373726,
"repo_name": "ghxandsky/zstack-utility",
"id": "fd2918e631979ff5719991132d9b644cd0810554",
"size": "143410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "zstackctl/zstackctl/ctl.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "AGS Script",
"bytes": "1147"
},
{
"name": "HTML",
"bytes": "4277"
},
{
"name": "Puppet",
"bytes": "10604"
},
{
"name": "Python",
"bytes": "1507292"
},
{
"name": "Shell",
"bytes": "188218"
}
],
"symlink_target": ""
} |
from .model_tests import *
from .form_tests import *
from .tags_tests import *
from .managers_tests import *
| {
"content_hash": "607a2726c2d82661f9bc02b503cc7bc1",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 29,
"avg_line_length": 27.25,
"alnum_prop": 0.7431192660550459,
"repo_name": "tsouvarev/django-money",
"id": "cca1f4101adffd98a4ed257960b00512bf431686",
"size": "109",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "djmoney/tests/__init__.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "65353"
},
{
"name": "Shell",
"bytes": "3667"
}
],
"symlink_target": ""
} |
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='DashboardWidget',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('column', models.CharField(max_length=1, choices=[('l', 'left'), ('r', 'right')])),
('index', models.IntegerField()),
('widgetname', models.CharField(max_length=200, choices=[('shorttermdevices', 'Devices for short term lending'), ('statistics', 'Statistics'), ('groups', 'Groups'), ('newestdevices', 'Newest devices'), ('edithistory', 'Edit history'), ('returnsoon', 'Devices, that are due soon'), ('bookmarks', 'Bookmarked Devices'), ('recentlendings', 'Recent lendings'), ('sections', 'Sections'), ('overdue', 'Overdue devices')])),
('minimized', models.BooleanField(default=False)),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),
],
),
]
| {
"content_hash": "811438ad80fb9cefdab99cb54e6bf839",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 433,
"avg_line_length": 52.95652173913044,
"alnum_prop": 0.6149425287356322,
"repo_name": "vIiRuS/Lagerregal",
"id": "acd96c1f73115a032487d0495ff7b2042369194c",
"size": "1218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main/migrations/0001_initial.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "42486"
},
{
"name": "HTML",
"bytes": "264180"
},
{
"name": "JavaScript",
"bytes": "179557"
},
{
"name": "Python",
"bytes": "396530"
}
],
"symlink_target": ""
} |
"""
The implementations of the hdfs clients.
"""
import logging
import threading
from luigi.contrib.hdfs import config as hdfs_config
from luigi.contrib.hdfs import webhdfs_client as hdfs_webhdfs_client
from luigi.contrib.hdfs import hadoopcli_clients as hdfs_hadoopcli_clients
logger = logging.getLogger('luigi-interface')
_AUTOCONFIG_CLIENT = threading.local()
def get_autoconfig_client(client_cache=_AUTOCONFIG_CLIENT):
"""
Creates the client as specified in the `luigi.cfg` configuration.
"""
try:
return client_cache.client
except AttributeError:
configured_client = hdfs_config.get_configured_hdfs_client()
if configured_client == "webhdfs":
client_cache.client = hdfs_webhdfs_client.WebHdfsClient()
elif configured_client == "hadoopcli":
client_cache.client = hdfs_hadoopcli_clients.create_hadoopcli_client()
else:
raise Exception("Unknown hdfs client " + configured_client)
return client_cache.client
def _with_ac(method_name):
def result(*args, **kwargs):
return getattr(get_autoconfig_client(), method_name)(*args, **kwargs)
return result
exists = _with_ac('exists')
rename = _with_ac('rename')
remove = _with_ac('remove')
mkdir = _with_ac('mkdir')
listdir = _with_ac('listdir')
| {
"content_hash": "fd7980fb453de7bc03b524a951e6748a",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 82,
"avg_line_length": 30.651162790697676,
"alnum_prop": 0.6949924127465857,
"repo_name": "dlstadther/luigi",
"id": "d3c113a9b98b4a3ef65cbf0f1030d3d7f5baecff",
"size": "1922",
"binary": false,
"copies": "4",
"ref": "refs/heads/upstream-master",
"path": "luigi/contrib/hdfs/clients.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5575"
},
{
"name": "HTML",
"bytes": "43591"
},
{
"name": "JavaScript",
"bytes": "178078"
},
{
"name": "Python",
"bytes": "2150576"
},
{
"name": "Shell",
"bytes": "2973"
}
],
"symlink_target": ""
} |
import tensorflow as tf
import train
import numpy as np
import pprint
flags = tf.app.flags
flags.DEFINE_string("dataset", "cosmo", "")
flags.DEFINE_string("datafile", "data/cosmo_primary_64_1k_train.npy", "Input data file for cosmo")
flags.DEFINE_integer("epoch", 1, "Epochs to train [1]")
flags.DEFINE_float("learning_rate", 0.0002, "Learning rate of for adam [0.0002]")
flags.DEFINE_float("beta1", 0.5, "Momentum term of adam [0.5]")
flags.DEFINE_float("flip_labels", 0, "Probability of flipping labels [0]")
flags.DEFINE_integer("z_dim", 100, "Dimension of noise vector z [100]")
flags.DEFINE_integer("nd_layers", 4, "Number of discriminator conv2d layers. [4]")
flags.DEFINE_integer("ng_layers", 4, "Number of generator conv2d_transpose layers. [4]")
flags.DEFINE_integer("gf_dim", 64, "Dimension of gen filters in last conv layer. [64]")
flags.DEFINE_integer("df_dim", 64, "Dimension of discrim filters in first conv layer. [64]")
flags.DEFINE_integer("batch_size", 64, "The size of batch images [64]")
flags.DEFINE_integer("output_size", 64, "The size of the output images to produce [64]")
flags.DEFINE_integer("c_dim", 1, "Dimension of image color. [1]")
flags.DEFINE_string("data_format", "NHWC", "data format [NHWC]")
flags.DEFINE_boolean("transpose_matmul_b", False, "Transpose matmul B matrix for performance [False]")
flags.DEFINE_string("checkpoint_dir", "checkpoints", "Directory name to save the checkpoints [checkpoint]")
flags.DEFINE_string("experiment", "run_0", "Tensorboard run directory name [run_0]")
flags.DEFINE_boolean("save_checkpoint", False, "Save a checkpoint every epoch [False]")
flags.DEFINE_boolean("verbose", True, "print loss on every step [False]")
flags.DEFINE_string("arch", "default", "Architecture, default, KNL or HSW")
config = flags.FLAGS
def main(_):
pprint.PrettyPrinter().pprint(config.__flags)
avg_time = train.train_dcgan(get_data(), config)
print("\nBatch size = %i. Average time per batch = %3.3f +- %3.5f (s)"%(config.batch_size, avg_time[0], avg_time[1]))
print("\nimages/sec = %i"%(config.batch_size/avg_time[0]))
def get_data():
data = np.load(config.datafile, mmap_mode='r')
if config.data_format == 'NHWC':
data = np.expand_dims(data, axis=-1)
else: # 'NCHW'
data = np.expand_dims(data, axis=1)
return data
if __name__ == '__main__':
tf.app.run()
| {
"content_hash": "3410152a2fd563d884612992ab25246f",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 121,
"avg_line_length": 49.229166666666664,
"alnum_prop": 0.6961489631823953,
"repo_name": "MustafaMustafa/dcgan-tf-benchmark",
"id": "4e901d6dc4b731fa0a426b3dde59522f4bd0121f",
"size": "2363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dcgan/main.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "23941"
},
{
"name": "Shell",
"bytes": "597"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.