prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def _get_available_ports():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def get_available_ports(only_free=False):
ports = _get_available_ports()
if only_free:
<|fim_middle|>
return ports
def find_port(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
return port
if not strict and founds >= len(ids) / 2:
return port
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def autodetect_robot():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
dxl_io.close()
continue
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
<|fim▁end|> | ports = list(set(ports) - set(DxlIO.get_used_ports())) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def _get_available_ports():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def get_available_ports(only_free=False):
ports = _get_available_ports()
if only_free:
ports = list(set(ports) - set(DxlIO.get_used_ports()))
return ports
def find_port(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
<|fim_middle|>
if not strict and founds >= len(ids) / 2:
return port
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def autodetect_robot():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
dxl_io.close()
continue
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
<|fim▁end|> | return port |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def _get_available_ports():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def get_available_ports(only_free=False):
ports = _get_available_ports()
if only_free:
ports = list(set(ports) - set(DxlIO.get_used_ports()))
return ports
def find_port(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
return port
if not strict and founds >= len(ids) / 2:
<|fim_middle|>
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def autodetect_robot():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
dxl_io.close()
continue
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
<|fim▁end|> | return port |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def _get_available_ports():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def get_available_ports(only_free=False):
ports = _get_available_ports()
if only_free:
ports = list(set(ports) - set(DxlIO.get_used_ports()))
return ports
def find_port(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
return port
if not strict and founds >= len(ids) / 2:
return port
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def autodetect_robot():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
<|fim_middle|>
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
<|fim▁end|> | dxl_io.close()
continue |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def <|fim_middle|>():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def get_available_ports(only_free=False):
ports = _get_available_ports()
if only_free:
ports = list(set(ports) - set(DxlIO.get_used_ports()))
return ports
def find_port(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
return port
if not strict and founds >= len(ids) / 2:
return port
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def autodetect_robot():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
dxl_io.close()
continue
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
<|fim▁end|> | _get_available_ports |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def _get_available_ports():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def <|fim_middle|>(only_free=False):
ports = _get_available_ports()
if only_free:
ports = list(set(ports) - set(DxlIO.get_used_ports()))
return ports
def find_port(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
return port
if not strict and founds >= len(ids) / 2:
return port
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def autodetect_robot():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
dxl_io.close()
continue
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
<|fim▁end|> | get_available_ports |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def _get_available_ports():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def get_available_ports(only_free=False):
ports = _get_available_ports()
if only_free:
ports = list(set(ports) - set(DxlIO.get_used_ports()))
return ports
def <|fim_middle|>(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
return port
if not strict and founds >= len(ids) / 2:
return port
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def autodetect_robot():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
dxl_io.close()
continue
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
<|fim▁end|> | find_port |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def _get_available_ports():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def get_available_ports(only_free=False):
ports = _get_available_ports()
if only_free:
ports = list(set(ports) - set(DxlIO.get_used_ports()))
return ports
def find_port(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
return port
if not strict and founds >= len(ids) / 2:
return port
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def <|fim_middle|>():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
dxl_io.close()
continue
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
<|fim▁end|> | autodetect_robot |
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>"""
WSGI config for ahaha project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also<|fim▁hole|>framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ahaha.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)<|fim▁end|> | might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""<|fim▁hole|> Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]<|fim▁end|> | |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
<|fim_middle|>
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | """
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor) |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
<|fim_middle|>
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | super(FlavorManageController, self).__init__() |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
<|fim_middle|>
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202) |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
<|fim_middle|>
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor) |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
<|fim_middle|>
<|fim▁end|> | """
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension] |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
<|fim_middle|>
<|fim▁end|> | controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension] |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
<|fim_middle|>
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg) |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
<|fim_middle|>
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context) |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def <|fim_middle|>(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | __init__ |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def <|fim_middle|>(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | _delete |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def <|fim_middle|>(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def get_controller_extensions(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | _create |
<|file_name|>flavormanage.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack.compute import flavors as flavors_api
from nova.api.openstack.compute.views import flavors as flavors_view
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'flavormanage')
class FlavorManageController(wsgi.Controller):
"""
The Flavor Lifecycle API controller for the OpenStack API.
"""
_view_builder_class = flavors_view.ViewBuilder
def __init__(self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
@wsgi.serializers(xml=flavors_api.FlavorTemplate)
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
root_gb = vals.get('disk')
ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
swap = vals.get('swap', 0)
rxtx_factor = vals.get('rxtx_factor', 1.0)
is_public = vals.get('os-flavor-access:is_public', True)
try:
flavor = flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb,
flavorid=flavorid, swap=swap,
rxtx_factor=rxtx_factor,
is_public=is_public)
if not flavor['is_public']:
flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context)
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
return self._view_builder.show(req, flavor)
class Flavormanage(extensions.ExtensionDescriptor):
"""
Flavor create/delete API support
"""
name = "FlavorManage"
alias = "os-flavor-manage"
namespace = ("http://docs.openstack.org/compute/ext/"
"flavor_manage/api/v1.1")
updated = "2012-01-19T00:00:00+00:00"
def <|fim_middle|>(self):
controller = FlavorManageController()
extension = extensions.ControllerExtension(self, 'flavors', controller)
return [extension]
<|fim▁end|> | get_controller_extensions |
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test<|fim▁hole|>class TestDispatcherFile(test.BaseTestCase):
def setUp(self):
super(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
def test_file_dispatcher_with_all_config(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_no_path(self):
self.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)<|fim▁end|> | from ceilometer.publisher import utils
|
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test
from ceilometer.publisher import utils
class TestDispatcherFile(test.BaseTestCase):
d<|fim_middle|>
<|fim▁end|> | ef setUp(self):
super(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
def test_file_dispatcher_with_all_config(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_no_path(self):
self.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)
|
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test
from ceilometer.publisher import utils
class TestDispatcherFile(test.BaseTestCase):
def setUp(self):
s<|fim_middle|>
def test_file_dispatcher_with_all_config(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_no_path(self):
self.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)
<|fim▁end|> | uper(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
|
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test
from ceilometer.publisher import utils
class TestDispatcherFile(test.BaseTestCase):
def setUp(self):
super(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
def test_file_dispatcher_with_all_config(self):
# Create a temporaryFile to get a file name
t<|fim_middle|>
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_no_path(self):
self.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)
<|fim▁end|> | f = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
|
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test
from ceilometer.publisher import utils
class TestDispatcherFile(test.BaseTestCase):
def setUp(self):
super(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
def test_file_dispatcher_with_all_config(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
t<|fim_middle|>
def test_file_dispatcher_with_no_path(self):
self.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)
<|fim▁end|> | f = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
|
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test
from ceilometer.publisher import utils
class TestDispatcherFile(test.BaseTestCase):
def setUp(self):
super(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
def test_file_dispatcher_with_all_config(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_no_path(self):
s<|fim_middle|>
<|fim▁end|> | elf.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)
|
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test
from ceilometer.publisher import utils
class TestDispatcherFile(test.BaseTestCase):
def s<|fim_middle|>self):
super(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
def test_file_dispatcher_with_all_config(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_no_path(self):
self.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)
<|fim▁end|> | etUp( |
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test
from ceilometer.publisher import utils
class TestDispatcherFile(test.BaseTestCase):
def setUp(self):
super(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
def t<|fim_middle|>self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_no_path(self):
self.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)
<|fim▁end|> | est_file_dispatcher_with_all_config( |
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test
from ceilometer.publisher import utils
class TestDispatcherFile(test.BaseTestCase):
def setUp(self):
super(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
def test_file_dispatcher_with_all_config(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def t<|fim_middle|>self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_no_path(self):
self.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)
<|fim▁end|> | est_file_dispatcher_with_path_only( |
<|file_name|>test_file.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging.handlers
import os
import tempfile
from ceilometer.dispatcher import file
from ceilometer.openstack.common.fixture import config
from ceilometer.openstack.common import test
from ceilometer.publisher import utils
class TestDispatcherFile(test.BaseTestCase):
def setUp(self):
super(TestDispatcherFile, self).setUp()
self.CONF = self.useFixture(config.Config()).conf
def test_file_dispatcher_with_all_config(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = 50
self.CONF.dispatcher_file.backup_count = 5
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.handlers.RotatingFileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
self.assertEqual(1, len(dispatcher.log.handlers))
# The handler should be RotatingFileHandler
handler = dispatcher.log.handlers[0]
self.assertIsInstance(handler,
logging.FileHandler)
msg = {'counter_name': 'test',
'resource_id': self.id(),
'counter_volume': 1,
}
msg['message_signature'] = utils.compute_signature(
msg,
self.CONF.publisher.metering_secret,
)
# The record_metering_data method should exist and not produce errors.
dispatcher.record_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def t<|fim_middle|>self):
self.CONF.dispatcher_file.file_path = None
dispatcher = file.FileDispatcher(self.CONF)
# The log should be None
self.assertIsNone(dispatcher.log)
<|fim▁end|> | est_file_dispatcher_with_no_path( |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################<|fim▁hole|><|fim▁end|> | from . import account_move
from . import account_move_line
from . import account_master_port |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|># or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | # Licensed to Cloudera, Inc. under one |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
<|fim_middle|>
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | add_permission(username, groupname, 'access', appname) |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
<|fim_middle|>
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save() |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
<|fim_middle|>
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save() |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
<|fim_middle|>
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save() |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
<|fim_middle|>
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj) |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
<|fim_middle|>
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj) |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
<|fim_middle|>
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | return cluster.clear_caches(), fsmanager.clear_cache() |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
<|fim_middle|>
<|fim▁end|> | cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1]) |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
<|fim_middle|>
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | user.groups.add(group)
user.save() |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
<|fim_middle|>
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | group = get_default_user_group()
assert group is not None
groupname = group.name |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
<|fim_middle|>
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | user.groups.add(group)
user.save() |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
<|fim_middle|>
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | user.groups.remove(group)
user.save() |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
<|fim_middle|>
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | return json.dumps(json.loads(json_obj)) |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
<|fim_middle|>
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | return json.dumps(json_obj) |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
<|fim_middle|>
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True))) |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
<|fim_middle|>
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | return etree.tostring(xml_obj) |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def <|fim_middle|>(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | grant_access |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def <|fim_middle|>(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | add_permission |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def <|fim_middle|>(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | add_to_group |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def <|fim_middle|>(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | remove_from_group |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def <|fim_middle|>(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | reformat_json |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def <|fim_middle|>(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | reformat_xml |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def <|fim_middle|>():
return cluster.clear_caches(), fsmanager.clear_cache()
def restore_sys_caches(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | clear_sys_caches |
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from lxml import objectify, etree
from django.contrib.auth.models import Group, User
from useradmin.models import HuePermission, GroupPermission, get_default_user_group
from hadoop import cluster
from desktop.lib import fsmanager
def grant_access(username, groupname, appname):
add_permission(username, groupname, 'access', appname)
def add_permission(username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def add_to_group(username, groupname=None):
if groupname is None:
group = get_default_user_group()
assert group is not None
groupname = group.name
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if not user.groups.filter(name=group.name).exists():
user.groups.add(group)
user.save()
def remove_from_group(username, groupname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save()
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cdata=False, remove_blank_text=True)))
else:
return etree.tostring(xml_obj)
def clear_sys_caches():
return cluster.clear_caches(), fsmanager.clear_cache()
def <|fim_middle|>(old_caches):
cluster.restore_caches(old_caches[0])
fsmanager.restore_cache(old_caches[1])<|fim▁end|> | restore_sys_caches |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()<|fim▁hole|> def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def<|fim_middle|>
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | __init__(self, title, info):
self.title = title
self.info = info
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
sel<|fim_middle|>
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | f.title = title
self.info = info
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PAR<|fim_middle|>
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | ENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
sup<|fim_middle|>
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | er().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
rai<|fim_middle|>
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | se NotImplementedError
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pas<|fim_middle|>
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | s
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pas<|fim_middle|>
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | s
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pas<|fim_middle|>
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | s
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try<|fim_middle|>
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | :
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dia<|fim_middle|>
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | log = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""<|fim_middle|>
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> |
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try<|fim_middle|>
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | :
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
reg<|fim_middle|>
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | ex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pa<|fim_middle|>
<|fim▁end|> | ges.register(page_class.__module__, page_class)
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old <|fim_middle|>
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | _options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __i<|fim_middle|>lf, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | nit__(se |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __i<|fim_middle|>lf, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | nit__(se |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def inf<|fim_middle|>lf):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | o(se |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def che<|fim_middle|>lf):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | ck(se |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def loa<|fim_middle|>lf):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | d(se |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def sav<|fim_middle|>lf):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | e(se |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def res<|fim_middle|>lf):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | tore_defaults(se |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def dis<|fim_middle|>lf, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | play_error(se |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def ini<|fim_middle|>lf, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | t_regex_checker(se |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def che<|fim_middle|>
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | ck(): |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def liv<|fim_middle|>xt):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | e_checker(te |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def reg<|fim_middle|>ge_class):
_pages.register(page_class.__module__, page_class)
<|fim▁end|> | ister_options_page(pa |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)<|fim▁hole|>
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()<|fim▁end|> | diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
|
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
<|fim_middle|>
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | print 10*20 |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
<|fim_middle|>
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | result=a/b
print result |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
<|fim_middle|>
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | result2=(base*altura)/2
print result2 |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
<|fim_middle|>
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v) |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):<|fim_middle|>
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
<|fim_middle|>
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | self.nombre=nombre
self.edad=edad |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
<|fim_middle|>
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | return self.nombre |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
<|fim_middle|>
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | if self.edad>=18:
return true
else:
return false |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
<|fim_middle|>
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | return true |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
<|fim_middle|>
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | return false |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
<|fim_middle|>
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | print"Es mayor de edad"
else:
print"Es menor de edad" |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
<|fim_middle|>
<|fim▁end|> | main() |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def <|fim_middle|>():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | sumaDos |
Subsets and Splits