prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def <|fim_middle|>(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|> | clean |
<|file_name|>0002_auto_20190430_1520.py<|end_file_name|><|fim▁begin|># Generated by Django 2.1.7 on 2019-04-30 13:20
from django.db import migrations, models<|fim▁hole|>
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='publishablemodel',
name='id',
field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
),
]<|fim▁end|> | import uuid
class Migration(migrations.Migration): |
<|file_name|>0002_auto_20190430_1520.py<|end_file_name|><|fim▁begin|># Generated by Django 2.1.7 on 2019-04-30 13:20
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
<|fim_middle|>
<|fim▁end|> | dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='publishablemodel',
name='id',
field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
),
] |
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# RedPipe documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 19 13:22:45 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
import os
import sys
from os import path
ROOTDIR = path.abspath(os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, ROOTDIR)
import redpipe # noqa
<|fim▁hole|> 'alabaster',
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'RedPipe'
copyright = u'2017, John Loehrer'
author = u'John Loehrer'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = redpipe.__version__
# The full version, including alpha/beta/rc tags.
release = redpipe.__version__
# 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
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = 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 = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
'logo': 'redpipe-logo.gif',
'github_banner': True,
'github_user': '72squared',
'github_repo': 'redpipe',
'travis_button': True,
'analytics_id': 'UA-98626018-1',
}
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'relations.html',
'searchbox.html',
]
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'RedPipedoc'
# -- 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, 'RedPipe.tex', u'%s Documentation' % project,
u'John Loehrer', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, project, u'%s Documentation' % project,
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, project, u'%s Documentation' % project,
author, project, 'making redis pipelines easy in python',
'Miscellaneous'),
]
suppress_warnings = ['image.nonlocal_uri']<|fim▁end|> | extensions = [ |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()<|fim▁hole|> u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))<|fim▁end|> | |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
<|fim_middle|>
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells) |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
<|fim_middle|>
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u) |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
<|fim_middle|>
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
) |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
<|fim_middle|>
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16'] |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
<|fim_middle|>
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2)) |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
<|fim_middle|>
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats)) |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
<|fim_middle|>
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2}) |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
<|fim_middle|>
<|fim▁end|> | cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells)) |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def <|fim_middle|>():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | test_basic |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def <|fim_middle|>():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | test_bounding_box |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def <|fim_middle|>(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | test_plot |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def <|fim_middle|>(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | test_get_nuclides |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def <|fim_middle|>():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | test_cells |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def <|fim_middle|>(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | test_get_all_materials |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def <|fim_middle|>():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | test_get_all_universes |
<|file_name|>test_universe.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def test_get_all_materials(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def <|fim_middle|>(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
<|fim▁end|> | test_create_xml |
<|file_name|>read_project_steps.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2014 BigML<|fim▁hole|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from world import world
from bigml.api import HTTP_OK
def i_get_the_project(step, resource):
resource = world.api.get_project(resource)
world.status = resource['code']
assert world.status == HTTP_OK
world.project = resource['object']<|fim▁end|> | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at |
<|file_name|>read_project_steps.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2014 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from world import world
from bigml.api import HTTP_OK
def i_get_the_project(step, resource):
<|fim_middle|>
<|fim▁end|> | resource = world.api.get_project(resource)
world.status = resource['code']
assert world.status == HTTP_OK
world.project = resource['object'] |
<|file_name|>read_project_steps.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2014 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from world import world
from bigml.api import HTTP_OK
def <|fim_middle|>(step, resource):
resource = world.api.get_project(resource)
world.status = resource['code']
assert world.status == HTTP_OK
world.project = resource['object']
<|fim▁end|> | i_get_the_project |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|># Scrapy settings for helloscrapy project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'helloscrapy'
SPIDER_MODULES = ['helloscrapy.spiders']
NEWSPIDER_MODULE = 'helloscrapy.spiders'<|fim▁hole|>DOWNLOAD_DELAY = 3
ROBOTSTXT_OBEY = True<|fim▁end|> |
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'helloscrapy (+http://www.yourdomain.com)'
|
<|file_name|>FindNextHigherNumberWithSameDigits.py<|end_file_name|><|fim▁begin|>'''
Given a number, find the next higher number using only the digits in the given number.
For example if the given number is 1234, next higher number with same digits is 1243
'''<|fim▁hole|> number = str(num)
length = len(number)
for i in range(length-2,-1,-1):
current = number[i]
right = number[i+1]
if current < right:
temp = sorted(number[i:])
Next = temp[temp.index(current)+1]
temp.remove(Next)
temp = ''.join(temp)
return int(number[:i]+Next+temp)
return num<|fim▁end|> |
def FindNext(num): |
<|file_name|>FindNextHigherNumberWithSameDigits.py<|end_file_name|><|fim▁begin|>'''
Given a number, find the next higher number using only the digits in the given number.
For example if the given number is 1234, next higher number with same digits is 1243
'''
def FindNext(num):
<|fim_middle|>
<|fim▁end|> | number = str(num)
length = len(number)
for i in range(length-2,-1,-1):
current = number[i]
right = number[i+1]
if current < right:
temp = sorted(number[i:])
Next = temp[temp.index(current)+1]
temp.remove(Next)
temp = ''.join(temp)
return int(number[:i]+Next+temp)
return num |
<|file_name|>FindNextHigherNumberWithSameDigits.py<|end_file_name|><|fim▁begin|>'''
Given a number, find the next higher number using only the digits in the given number.
For example if the given number is 1234, next higher number with same digits is 1243
'''
def FindNext(num):
number = str(num)
length = len(number)
for i in range(length-2,-1,-1):
current = number[i]
right = number[i+1]
if current < right:
<|fim_middle|>
return num
<|fim▁end|> | temp = sorted(number[i:])
Next = temp[temp.index(current)+1]
temp.remove(Next)
temp = ''.join(temp)
return int(number[:i]+Next+temp) |
<|file_name|>FindNextHigherNumberWithSameDigits.py<|end_file_name|><|fim▁begin|>'''
Given a number, find the next higher number using only the digits in the given number.
For example if the given number is 1234, next higher number with same digits is 1243
'''
def <|fim_middle|>(num):
number = str(num)
length = len(number)
for i in range(length-2,-1,-1):
current = number[i]
right = number[i+1]
if current < right:
temp = sorted(number[i:])
Next = temp[temp.index(current)+1]
temp.remove(Next)
temp = ''.join(temp)
return int(number[:i]+Next+temp)
return num
<|fim▁end|> | FindNext |
<|file_name|>testes_notificacao.py<|end_file_name|><|fim▁begin|># coding=utf-8
# ---------------------------------------------------------------
# Desenvolvedor: Arannã Sousa Santos
# Mês: 12
# Ano: 2015
# Projeto: pagseguro_xml
# e-mail: [email protected]
# ---------------------------------------------------------------
import logging
from pagseguro_xml.notificacao import ApiPagSeguroNotificacao_v3, CONST_v3
logger = logging.basicConfig(level=logging.DEBUG)
<|fim▁hole|>PAGSEGURO_API_AMBIENTE = u'sandbox'
PAGSEGURO_API_EMAIL = u'[email protected]'
PAGSEGURO_API_TOKEN_PRODUCAO = u''
PAGSEGURO_API_TOKEN_SANDBOX = u''
CHAVE_NOTIFICACAO = u'AA0000-AA00A0A0AA00-AA00AA000000-AA0000' # ela éh de producao
api = ApiPagSeguroNotificacao_v3(ambiente=CONST_v3.AMBIENTE.SANDBOX)
PAGSEGURO_API_TOKEN = PAGSEGURO_API_TOKEN_PRODUCAO
ok, retorno = api.consulta_notificacao_transacao_v3(PAGSEGURO_API_EMAIL, PAGSEGURO_API_TOKEN, CHAVE_NOTIFICACAO)
if ok:
print u'-' * 50
print retorno.xml
print u'-' * 50
for a in retorno.alertas:
print a
else:
print u'Motivo do erro:', retorno<|fim▁end|> | |
<|file_name|>testes_notificacao.py<|end_file_name|><|fim▁begin|># coding=utf-8
# ---------------------------------------------------------------
# Desenvolvedor: Arannã Sousa Santos
# Mês: 12
# Ano: 2015
# Projeto: pagseguro_xml
# e-mail: [email protected]
# ---------------------------------------------------------------
import logging
from pagseguro_xml.notificacao import ApiPagSeguroNotificacao_v3, CONST_v3
logger = logging.basicConfig(level=logging.DEBUG)
PAGSEGURO_API_AMBIENTE = u'sandbox'
PAGSEGURO_API_EMAIL = u'[email protected]'
PAGSEGURO_API_TOKEN_PRODUCAO = u''
PAGSEGURO_API_TOKEN_SANDBOX = u''
CHAVE_NOTIFICACAO = u'AA0000-AA00A0A0AA00-AA00AA000000-AA0000' # ela éh de producao
api = ApiPagSeguroNotificacao_v3(ambiente=CONST_v3.AMBIENTE.SANDBOX)
PAGSEGURO_API_TOKEN = PAGSEGURO_API_TOKEN_PRODUCAO
ok, retorno = api.consulta_notificacao_transacao_v3(PAGSEGURO_API_EMAIL, PAGSEGURO_API_TOKEN, CHAVE_NOTIFICACAO)
if ok:
pri <|fim_middle|>
lse:
print u'Motivo do erro:', retorno
<|fim▁end|> | nt u'-' * 50
print retorno.xml
print u'-' * 50
for a in retorno.alertas:
print a
e |
<|file_name|>testes_notificacao.py<|end_file_name|><|fim▁begin|># coding=utf-8
# ---------------------------------------------------------------
# Desenvolvedor: Arannã Sousa Santos
# Mês: 12
# Ano: 2015
# Projeto: pagseguro_xml
# e-mail: [email protected]
# ---------------------------------------------------------------
import logging
from pagseguro_xml.notificacao import ApiPagSeguroNotificacao_v3, CONST_v3
logger = logging.basicConfig(level=logging.DEBUG)
PAGSEGURO_API_AMBIENTE = u'sandbox'
PAGSEGURO_API_EMAIL = u'[email protected]'
PAGSEGURO_API_TOKEN_PRODUCAO = u''
PAGSEGURO_API_TOKEN_SANDBOX = u''
CHAVE_NOTIFICACAO = u'AA0000-AA00A0A0AA00-AA00AA000000-AA0000' # ela éh de producao
api = ApiPagSeguroNotificacao_v3(ambiente=CONST_v3.AMBIENTE.SANDBOX)
PAGSEGURO_API_TOKEN = PAGSEGURO_API_TOKEN_PRODUCAO
ok, retorno = api.consulta_notificacao_transacao_v3(PAGSEGURO_API_EMAIL, PAGSEGURO_API_TOKEN, CHAVE_NOTIFICACAO)
if ok:
print u'-' * 50
print retorno.xml
print u'-' * 50
for a in retorno.alertas:
print a
else:
pri <|fim_middle|>
<|fim▁end|> | nt u'Motivo do erro:', retorno
|
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:<|fim▁hole|> # "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]<|fim▁end|> | |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
<|fim_middle|>
<|fim▁end|> | """A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower] |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
<|fim_middle|>
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:] |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
<|fim_middle|>
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
<|fim_middle|>
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | return self._cp.sections() |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
<|fim_middle|>
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
<|fim_middle|>
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
<|fim_middle|>
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
<|fim_middle|>
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)] |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
<|fim_middle|>
<|fim▁end|> | ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower] |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
<|fim_middle|>
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | from configparser import RawConfigParser |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
<|fim_middle|>
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | from ConfigParser import RawConfigParser |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
<|fim_middle|>
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',)) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
<|fim_middle|>
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | self._cp = RawConfigParser(dict_type=OrderedMultiDict) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
<|fim_middle|>
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | filenames_to_try = [filenames_to_try] |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
<|fim_middle|>
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | filenames_to_try = [filenames_to_try] |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
<|fim_middle|>
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | return [] |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
<|fim_middle|>
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | option_name = self._cp.optionxform(option_name) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
<|fim_middle|>
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | return self._get_optval_in_sections(self.sections(), option_name) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
<|fim_middle|>
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | return self._get_optval_in_sections([section_name], option_name) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
<|fim_middle|>
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | return self._get_optval_in_sections(section_name, option_name) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
<|fim_middle|>
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | continue |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
<|fim_middle|>
return self._boolean_states[ovs_lower]
<|fim▁end|> | raise ValueError("Not a boolean: %s" % optval_str) |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def <|fim_middle|>(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | __init__ |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def <|fim_middle|>(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | read |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def <|fim_middle|>(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | sections |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def <|fim_middle|>(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | options |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def <|fim_middle|>(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | get |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def <|fim_middle|>(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | _get_optval_in_sections |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def <|fim_middle|>(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _coerce_to_boolean(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | getboolean |
<|file_name|>UsefulConfigParser.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self, filenames_to_try=[]):
# FUN FACT: In Python 3.2, they spontaneously changed the behaviour of
# RawConfigParser so that it no longer considers ';' a comment delimiter
# for inline comments.
#
# Compare:
# "Configuration files may include comments, prefixed by specific
# characters (# and ;). Comments may appear on their own in an otherwise
# empty line, or may be entered in lines holding values or section names.
# In the latter case, they need to be preceded by a whitespace character
# to be recognized as a comment. (For backwards compatibility, only ;
# starts an inline comment, while # does not.)"
# -- https://docs.python.org/2/library/configparser.html
# vs:
# "Comment prefixes are strings that indicate the start of a valid comment
# within a config file. comment_prefixes are used only on otherwise empty
# lines (optionally indented) whereas inline_comment_prefixes can be used
# after every valid value (e.g. section names, options and empty lines as
# well). By default inline comments are disabled and '#' and ';' are used
# as prefixes for whole line comments.
# Changed in version 3.2: In previous versions of configparser behaviour
# matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
self._cp = RawConfigParser(dict_type=OrderedMultiDict)
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
return self._cp.read(self._filenames_to_try)
def sections(self):
return self._cp.sections()
def options(self, section_name):
## The client code doesn't need to check in advance that the requested
## section name is present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
return []
return self._cp.options(section_name)
def get(self, section_name, option_name, do_optionxform=True):
if do_optionxform:
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform
option_name = self._cp.optionxform(option_name)
if section_name is None:
return self._get_optval_in_sections(self.sections(), option_name)
elif isinstance(section_name, str):
return self._get_optval_in_sections([section_name], option_name)
else:
return self._get_optval_in_sections(section_name, option_name)
def _get_optval_in_sections(self, section_names, option_name):
## The client code doesn't need to check in advance that the requested
## section name(s) are present in the config; this function will check
## this automatically, so no exception is raised by RawConfigParser.
optvals = []
for section_name in section_names:
## Check that `section_name` is present in the config.
## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError.
if not self._cp.has_section(section_name):
continue
optvals.extend([optval
for optname, optval in self._cp.items(section_name)
if optname == option_name])
return optvals
def getboolean(self, section_name, option_name, do_optionxform=True):
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
return [self._coerce_to_boolean(optval)
for optval in self.get(section_name, option_name, do_optionxform)]
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def <|fim_middle|>(self, optval_str):
# 'The accepted values for the option are "1", "yes", "true", and "on",
# which cause this method to return True, and "0", "no", "false", and
# "off", which cause it to return False. These string values are checked
# in a case-insensitive manner. Any other value will cause it to raise
# ValueError.'
# https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean
ovs_lower = optval_str.lower()
if ovs_lower not in self._boolean_states:
raise ValueError("Not a boolean: %s" % optval_str)
return self._boolean_states[ovs_lower]
<|fim▁end|> | _coerce_to_boolean |
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
"""Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def _handle(self, *args, **options):
if len(args) != 2:
raise CommandError("Need to specify (only) branch and changeset")
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
raise CommandError("No project found named '%s'" % project)
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])<|fim▁hole|> def handle(self, *args, **options):
if options['profile_file']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file'])
else:
self._handle(*args, **options)<|fim▁end|> | RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
|
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
<|fim_middle|>
<|fim▁end|> | """Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def _handle(self, *args, **options):
if len(args) != 2:
raise CommandError("Need to specify (only) branch and changeset")
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
raise CommandError("No project found named '%s'" % project)
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
def handle(self, *args, **options):
if options['profile_file']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file'])
else:
self._handle(*args, **options) |
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
"""Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def _handle(self, *args, **options):
<|fim_middle|>
def handle(self, *args, **options):
if options['profile_file']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file'])
else:
self._handle(*args, **options)
<|fim▁end|> | if len(args) != 2:
raise CommandError("Need to specify (only) branch and changeset")
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
raise CommandError("No project found named '%s'" % project)
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group']) |
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
"""Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def _handle(self, *args, **options):
if len(args) != 2:
raise CommandError("Need to specify (only) branch and changeset")
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
raise CommandError("No project found named '%s'" % project)
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
def handle(self, *args, **options):
<|fim_middle|>
<|fim▁end|> | if options['profile_file']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file'])
else:
self._handle(*args, **options) |
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
"""Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def _handle(self, *args, **options):
if len(args) != 2:
<|fim_middle|>
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
raise CommandError("No project found named '%s'" % project)
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
def handle(self, *args, **options):
if options['profile_file']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file'])
else:
self._handle(*args, **options)
<|fim▁end|> | raise CommandError("Need to specify (only) branch and changeset") |
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
"""Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def _handle(self, *args, **options):
if len(args) != 2:
raise CommandError("Need to specify (only) branch and changeset")
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
<|fim_middle|>
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
def handle(self, *args, **options):
if options['profile_file']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file'])
else:
self._handle(*args, **options)
<|fim▁end|> | raise CommandError("No project found named '%s'" % project) |
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
"""Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def _handle(self, *args, **options):
if len(args) != 2:
raise CommandError("Need to specify (only) branch and changeset")
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
raise CommandError("No project found named '%s'" % project)
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
def handle(self, *args, **options):
if options['profile_file']:
<|fim_middle|>
else:
self._handle(*args, **options)
<|fim▁end|> | profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file']) |
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
"""Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def _handle(self, *args, **options):
if len(args) != 2:
raise CommandError("Need to specify (only) branch and changeset")
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
raise CommandError("No project found named '%s'" % project)
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
def handle(self, *args, **options):
if options['profile_file']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file'])
else:
<|fim_middle|>
<|fim▁end|> | self._handle(*args, **options) |
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
"""Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def <|fim_middle|>(self, *args, **options):
if len(args) != 2:
raise CommandError("Need to specify (only) branch and changeset")
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
raise CommandError("No project found named '%s'" % project)
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
def handle(self, *args, **options):
if options['profile_file']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file'])
else:
self._handle(*args, **options)
<|fim▁end|> | _handle |
<|file_name|>ingest_push.py<|end_file_name|><|fim▁begin|>from cProfile import Profile
from optparse import make_option
from django.conf import settings
from django.core.management.base import (BaseCommand,
CommandError)
from treeherder.etl.buildapi import (Builds4hJobsProcess,
PendingJobsProcess,
RunningJobsProcess)
from treeherder.etl.pushlog import HgPushlogProcess
from treeherder.model.derived import RefDataManager
class Command(BaseCommand):
"""Management command to ingest data from a single push."""
help = "Ingests a single push into treeherder"
args = '<project> <changeset>'
option_list = BaseCommand.option_list + (
make_option('--profile-file',
action='store',
dest='profile_file',
default=None,
help='Profile command and write result to profile file'),
make_option('--filter-job-group',
action='store',
dest='filter_job_group',
default=None,
help="Only process jobs in specified group symbol "
"(e.g. 'T')")
)
def _handle(self, *args, **options):
if len(args) != 2:
raise CommandError("Need to specify (only) branch and changeset")
(project, changeset) = args
# get reference to repo
rdm = RefDataManager()
repos = filter(lambda x: x['name'] == project,
rdm.get_all_repository_info())
if not repos:
raise CommandError("No project found named '%s'" % project)
repo = repos[0]
# make sure all tasks are run synchronously / immediately
settings.CELERY_ALWAYS_EAGER = True
# get hg pushlog
pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url']
# ingest this particular revision for this project
process = HgPushlogProcess()
# Use the actual push SHA, in case the changeset specified was a tag
# or branch name (eg tip). HgPushlogProcess returns the full SHA, but
# job ingestion expects the short version, so we truncate it.
push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12]
Builds4hJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
PendingJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
RunningJobsProcess().run(filter_to_project=project,
filter_to_revision=push_sha,
filter_to_job_group=options['filter_job_group'])
def <|fim_middle|>(self, *args, **options):
if options['profile_file']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.dump_stats(options['profile_file'])
else:
self._handle(*args, **options)
<|fim▁end|> | handle |
<|file_name|>pyugrid_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_above_reference_datum',
'sea_surface_height_above_reference_ellipsoid']
models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'),
FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/'
'Forecasts/NECOFS_GOM3_FORECAST.nc'),
SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'),
WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/'
'Dec2013Storm_2D_preliminary_run_1_waves_only'))
# In[2]:
import iris
iris.FUTURE.netcdf_promote = True
def cube_func(cube):
return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods))
constraint = iris.Constraint(cube_func=cube_func)
cubes = dict()
for model, url in models.items():
cube = iris.load_cube(url, constraint)
cubes.update({model: cube})
# In[3]:
cubes
# In[4]:
import pyugrid
import matplotlib.tri as tri
def get_mesh(cube, url):
ug = pyugrid.UGrid.from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube
def get_triang(cube):
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, triangles=nv)
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def plot_model(model):
cube = cubes[model]
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
ind = -1 # just take the last time index for now
zcube = cube[ind]
triang = tris[model]
fig, ax = plt.subplots(figsize=(7, 7),<|fim▁hole|> levs = np.arange(-1, 5, 0.2)
cs = ax.tricontourf(triang, zcube.data, levels=levs)
fig.colorbar(cs)
ax.tricontour(triang, zcube.data, colors='k',levels=levs)
tvar = cube.coord('time')
tstr = tvar.units.num2date(tvar.points[ind])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr))
return fig, ax
# In[7]:
fig, ax = plot_model('ADCIRC')
# In[8]:
fig, ax = plot_model('FVCOM')
# In[9]:
fig, ax = plot_model('WW3')
# In[10]:
fig, ax = plot_model('SELFE')<|fim▁end|> | subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines() |
<|file_name|>pyugrid_test.py<|end_file_name|><|fim▁begin|>
# coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_above_reference_datum',
'sea_surface_height_above_reference_ellipsoid']
models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'),
FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/'
'Forecasts/NECOFS_GOM3_FORECAST.nc'),
SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'),
WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/'
'Dec2013Storm_2D_preliminary_run_1_waves_only'))
# In[2]:
import iris
iris.FUTURE.netcdf_promote = True
def cube_func(cube):
<|fim_middle|>
constraint = iris.Constraint(cube_func=cube_func)
cubes = dict()
for model, url in models.items():
cube = iris.load_cube(url, constraint)
cubes.update({model: cube})
# In[3]:
cubes
# In[4]:
import pyugrid
import matplotlib.tri as tri
def get_mesh(cube, url):
ug = pyugrid.UGrid.from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube
def get_triang(cube):
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, triangles=nv)
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def plot_model(model):
cube = cubes[model]
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
ind = -1 # just take the last time index for now
zcube = cube[ind]
triang = tris[model]
fig, ax = plt.subplots(figsize=(7, 7),
subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines()
levs = np.arange(-1, 5, 0.2)
cs = ax.tricontourf(triang, zcube.data, levels=levs)
fig.colorbar(cs)
ax.tricontour(triang, zcube.data, colors='k',levels=levs)
tvar = cube.coord('time')
tstr = tvar.units.num2date(tvar.points[ind])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr))
return fig, ax
# In[7]:
fig, ax = plot_model('ADCIRC')
# In[8]:
fig, ax = plot_model('FVCOM')
# In[9]:
fig, ax = plot_model('WW3')
# In[10]:
fig, ax = plot_model('SELFE')
<|fim▁end|> | return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods)) |
<|file_name|>pyugrid_test.py<|end_file_name|><|fim▁begin|>
# coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_above_reference_datum',
'sea_surface_height_above_reference_ellipsoid']
models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'),
FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/'
'Forecasts/NECOFS_GOM3_FORECAST.nc'),
SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'),
WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/'
'Dec2013Storm_2D_preliminary_run_1_waves_only'))
# In[2]:
import iris
iris.FUTURE.netcdf_promote = True
def cube_func(cube):
return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods))
constraint = iris.Constraint(cube_func=cube_func)
cubes = dict()
for model, url in models.items():
cube = iris.load_cube(url, constraint)
cubes.update({model: cube})
# In[3]:
cubes
# In[4]:
import pyugrid
import matplotlib.tri as tri
def get_mesh(cube, url):
<|fim_middle|>
def get_triang(cube):
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, triangles=nv)
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def plot_model(model):
cube = cubes[model]
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
ind = -1 # just take the last time index for now
zcube = cube[ind]
triang = tris[model]
fig, ax = plt.subplots(figsize=(7, 7),
subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines()
levs = np.arange(-1, 5, 0.2)
cs = ax.tricontourf(triang, zcube.data, levels=levs)
fig.colorbar(cs)
ax.tricontour(triang, zcube.data, colors='k',levels=levs)
tvar = cube.coord('time')
tstr = tvar.units.num2date(tvar.points[ind])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr))
return fig, ax
# In[7]:
fig, ax = plot_model('ADCIRC')
# In[8]:
fig, ax = plot_model('FVCOM')
# In[9]:
fig, ax = plot_model('WW3')
# In[10]:
fig, ax = plot_model('SELFE')
<|fim▁end|> | ug = pyugrid.UGrid.from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube |
<|file_name|>pyugrid_test.py<|end_file_name|><|fim▁begin|>
# coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_above_reference_datum',
'sea_surface_height_above_reference_ellipsoid']
models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'),
FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/'
'Forecasts/NECOFS_GOM3_FORECAST.nc'),
SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'),
WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/'
'Dec2013Storm_2D_preliminary_run_1_waves_only'))
# In[2]:
import iris
iris.FUTURE.netcdf_promote = True
def cube_func(cube):
return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods))
constraint = iris.Constraint(cube_func=cube_func)
cubes = dict()
for model, url in models.items():
cube = iris.load_cube(url, constraint)
cubes.update({model: cube})
# In[3]:
cubes
# In[4]:
import pyugrid
import matplotlib.tri as tri
def get_mesh(cube, url):
ug = pyugrid.UGrid.from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube
def get_triang(cube):
<|fim_middle|>
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def plot_model(model):
cube = cubes[model]
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
ind = -1 # just take the last time index for now
zcube = cube[ind]
triang = tris[model]
fig, ax = plt.subplots(figsize=(7, 7),
subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines()
levs = np.arange(-1, 5, 0.2)
cs = ax.tricontourf(triang, zcube.data, levels=levs)
fig.colorbar(cs)
ax.tricontour(triang, zcube.data, colors='k',levels=levs)
tvar = cube.coord('time')
tstr = tvar.units.num2date(tvar.points[ind])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr))
return fig, ax
# In[7]:
fig, ax = plot_model('ADCIRC')
# In[8]:
fig, ax = plot_model('FVCOM')
# In[9]:
fig, ax = plot_model('WW3')
# In[10]:
fig, ax = plot_model('SELFE')
<|fim▁end|> | lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, triangles=nv) |
<|file_name|>pyugrid_test.py<|end_file_name|><|fim▁begin|>
# coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_above_reference_datum',
'sea_surface_height_above_reference_ellipsoid']
models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'),
FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/'
'Forecasts/NECOFS_GOM3_FORECAST.nc'),
SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'),
WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/'
'Dec2013Storm_2D_preliminary_run_1_waves_only'))
# In[2]:
import iris
iris.FUTURE.netcdf_promote = True
def cube_func(cube):
return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods))
constraint = iris.Constraint(cube_func=cube_func)
cubes = dict()
for model, url in models.items():
cube = iris.load_cube(url, constraint)
cubes.update({model: cube})
# In[3]:
cubes
# In[4]:
import pyugrid
import matplotlib.tri as tri
def get_mesh(cube, url):
ug = pyugrid.UGrid.from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube
def get_triang(cube):
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, triangles=nv)
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def plot_model(model):
<|fim_middle|>
# In[7]:
fig, ax = plot_model('ADCIRC')
# In[8]:
fig, ax = plot_model('FVCOM')
# In[9]:
fig, ax = plot_model('WW3')
# In[10]:
fig, ax = plot_model('SELFE')
<|fim▁end|> | cube = cubes[model]
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
ind = -1 # just take the last time index for now
zcube = cube[ind]
triang = tris[model]
fig, ax = plt.subplots(figsize=(7, 7),
subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines()
levs = np.arange(-1, 5, 0.2)
cs = ax.tricontourf(triang, zcube.data, levels=levs)
fig.colorbar(cs)
ax.tricontour(triang, zcube.data, colors='k',levels=levs)
tvar = cube.coord('time')
tstr = tvar.units.num2date(tvar.points[ind])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr))
return fig, ax |
<|file_name|>pyugrid_test.py<|end_file_name|><|fim▁begin|>
# coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_above_reference_datum',
'sea_surface_height_above_reference_ellipsoid']
models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'),
FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/'
'Forecasts/NECOFS_GOM3_FORECAST.nc'),
SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'),
WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/'
'Dec2013Storm_2D_preliminary_run_1_waves_only'))
# In[2]:
import iris
iris.FUTURE.netcdf_promote = True
def <|fim_middle|>(cube):
return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods))
constraint = iris.Constraint(cube_func=cube_func)
cubes = dict()
for model, url in models.items():
cube = iris.load_cube(url, constraint)
cubes.update({model: cube})
# In[3]:
cubes
# In[4]:
import pyugrid
import matplotlib.tri as tri
def get_mesh(cube, url):
ug = pyugrid.UGrid.from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube
def get_triang(cube):
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, triangles=nv)
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def plot_model(model):
cube = cubes[model]
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
ind = -1 # just take the last time index for now
zcube = cube[ind]
triang = tris[model]
fig, ax = plt.subplots(figsize=(7, 7),
subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines()
levs = np.arange(-1, 5, 0.2)
cs = ax.tricontourf(triang, zcube.data, levels=levs)
fig.colorbar(cs)
ax.tricontour(triang, zcube.data, colors='k',levels=levs)
tvar = cube.coord('time')
tstr = tvar.units.num2date(tvar.points[ind])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr))
return fig, ax
# In[7]:
fig, ax = plot_model('ADCIRC')
# In[8]:
fig, ax = plot_model('FVCOM')
# In[9]:
fig, ax = plot_model('WW3')
# In[10]:
fig, ax = plot_model('SELFE')
<|fim▁end|> | cube_func |
<|file_name|>pyugrid_test.py<|end_file_name|><|fim▁begin|>
# coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_above_reference_datum',
'sea_surface_height_above_reference_ellipsoid']
models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'),
FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/'
'Forecasts/NECOFS_GOM3_FORECAST.nc'),
SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'),
WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/'
'Dec2013Storm_2D_preliminary_run_1_waves_only'))
# In[2]:
import iris
iris.FUTURE.netcdf_promote = True
def cube_func(cube):
return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods))
constraint = iris.Constraint(cube_func=cube_func)
cubes = dict()
for model, url in models.items():
cube = iris.load_cube(url, constraint)
cubes.update({model: cube})
# In[3]:
cubes
# In[4]:
import pyugrid
import matplotlib.tri as tri
def <|fim_middle|>(cube, url):
ug = pyugrid.UGrid.from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube
def get_triang(cube):
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, triangles=nv)
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def plot_model(model):
cube = cubes[model]
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
ind = -1 # just take the last time index for now
zcube = cube[ind]
triang = tris[model]
fig, ax = plt.subplots(figsize=(7, 7),
subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines()
levs = np.arange(-1, 5, 0.2)
cs = ax.tricontourf(triang, zcube.data, levels=levs)
fig.colorbar(cs)
ax.tricontour(triang, zcube.data, colors='k',levels=levs)
tvar = cube.coord('time')
tstr = tvar.units.num2date(tvar.points[ind])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr))
return fig, ax
# In[7]:
fig, ax = plot_model('ADCIRC')
# In[8]:
fig, ax = plot_model('FVCOM')
# In[9]:
fig, ax = plot_model('WW3')
# In[10]:
fig, ax = plot_model('SELFE')
<|fim▁end|> | get_mesh |
<|file_name|>pyugrid_test.py<|end_file_name|><|fim▁begin|>
# coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_above_reference_datum',
'sea_surface_height_above_reference_ellipsoid']
models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'),
FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/'
'Forecasts/NECOFS_GOM3_FORECAST.nc'),
SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'),
WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/'
'Dec2013Storm_2D_preliminary_run_1_waves_only'))
# In[2]:
import iris
iris.FUTURE.netcdf_promote = True
def cube_func(cube):
return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods))
constraint = iris.Constraint(cube_func=cube_func)
cubes = dict()
for model, url in models.items():
cube = iris.load_cube(url, constraint)
cubes.update({model: cube})
# In[3]:
cubes
# In[4]:
import pyugrid
import matplotlib.tri as tri
def get_mesh(cube, url):
ug = pyugrid.UGrid.from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube
def <|fim_middle|>(cube):
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, triangles=nv)
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def plot_model(model):
cube = cubes[model]
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
ind = -1 # just take the last time index for now
zcube = cube[ind]
triang = tris[model]
fig, ax = plt.subplots(figsize=(7, 7),
subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines()
levs = np.arange(-1, 5, 0.2)
cs = ax.tricontourf(triang, zcube.data, levels=levs)
fig.colorbar(cs)
ax.tricontour(triang, zcube.data, colors='k',levels=levs)
tvar = cube.coord('time')
tstr = tvar.units.num2date(tvar.points[ind])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr))
return fig, ax
# In[7]:
fig, ax = plot_model('ADCIRC')
# In[8]:
fig, ax = plot_model('FVCOM')
# In[9]:
fig, ax = plot_model('WW3')
# In[10]:
fig, ax = plot_model('SELFE')
<|fim▁end|> | get_triang |
<|file_name|>pyugrid_test.py<|end_file_name|><|fim▁begin|>
# coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_above_reference_datum',
'sea_surface_height_above_reference_ellipsoid']
models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'),
FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/'
'Forecasts/NECOFS_GOM3_FORECAST.nc'),
SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/'
'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'),
WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/'
'Dec2013Storm_2D_preliminary_run_1_waves_only'))
# In[2]:
import iris
iris.FUTURE.netcdf_promote = True
def cube_func(cube):
return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods))
constraint = iris.Constraint(cube_func=cube_func)
cubes = dict()
for model, url in models.items():
cube = iris.load_cube(url, constraint)
cubes.update({model: cube})
# In[3]:
cubes
# In[4]:
import pyugrid
import matplotlib.tri as tri
def get_mesh(cube, url):
ug = pyugrid.UGrid.from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube
def get_triang(cube):
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, triangles=nv)
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def <|fim_middle|>(model):
cube = cubes[model]
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
ind = -1 # just take the last time index for now
zcube = cube[ind]
triang = tris[model]
fig, ax = plt.subplots(figsize=(7, 7),
subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines()
levs = np.arange(-1, 5, 0.2)
cs = ax.tricontourf(triang, zcube.data, levels=levs)
fig.colorbar(cs)
ax.tricontour(triang, zcube.data, colors='k',levels=levs)
tvar = cube.coord('time')
tstr = tvar.units.num2date(tvar.points[ind])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr))
return fig, ax
# In[7]:
fig, ax = plot_model('ADCIRC')
# In[8]:
fig, ax = plot_model('FVCOM')
# In[9]:
fig, ax = plot_model('WW3')
# In[10]:
fig, ax = plot_model('SELFE')
<|fim▁end|> | plot_model |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
<|fim▁hole|> hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)<|fim▁end|> | async def async_setup_entry( |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
""<|fim_middle|>
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
""<|fim_middle|>
<|fim▁end|> | "Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
""<|fim_middle|>
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
""<|fim_middle|>
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
""<|fim_middle|>
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
""<|fim_middle|>
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Return a unique ID."""
return self._unique_id
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
""<|fim_middle|>
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Return the name of the sensor."""
return self._name
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
""<|fim_middle|>
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Return the state of the sensor."""
return self._pvpc_data.state
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
""<|fim_middle|>
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Return True if entity is available."""
return self._pvpc_data.state_available
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
""<|fim_middle|>
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Return the state attributes."""
return self._pvpc_data.attributes
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
""<|fim_middle|>
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | "Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
""<|fim_middle|>
<|fim▁end|> | "Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
se <|fim_middle|>
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | lf._pvpc_data.state = state.state
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
se <|fim_middle|>
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | lf._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_L <|fim_middle|>
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | OGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_L <|fim_middle|>
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | OGGER.debug("%s: data source is not yet available", self.entity_id)
return
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
se <|fim_middle|>
<|fim▁end|> | lf._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.