<commit_before>import collections
from component_loader import load_components

component_suites_path = '../renderer/node_modules/dash-components-core/lib/metadata.json';

# Other valid react attributes include:
# https://facebook.github.io/react/docs/tags-and-attributes.html#html-attributes

supported_react_attributes = [
    'src', 'height', 'width', 'accept',
    'acceptCharset', 'accessKey', 'action', 'allowFullScreen',
    'allowTransparency', 'alt', 'async', 'autoComplete', 'autoFocus',
    'autoPlay', 'cellPadding', 'cellSpacing', 'charSet', 'checked',
    'classID', 'colSpan', 'cols', 'content', 'contentEditable',
    'contextMenu', 'controls', 'coords', 'crossOrigin', 'data',
    'dateTime', 'defer', 'dir', 'disabled', 'download', 'draggable',
    'encType', 'form', 'formAction', 'formEncType', 'formMethod',
    'formNoValidate', 'formTarget', 'frameBorder', 'headers', 'hidden',
    'high', 'href', 'hrefLang', 'htmlFor', 'httpEquiv', 'icon',
    'lang', 'list', 'loop', 'low', 'manifest', 'marginHeight',
    'marginWidth', 'max', 'maxLength', 'media', 'mediaGroup',
    'method', 'min', 'multiple', 'muted', 'name', 'noValidate',
    'open', 'optimum', 'pattern', 'placeholder', 'poster', 'preload',
    'radioGroup', 'readOnly', 'rel', 'required', 'role', 'rowSpan',
    'rows', 'sandbox', 'scope', 'scoped', 'scrolling', 'seamless',
    'selected', 'shape', 'size', 'sizes', 'span', 'spellCheck',
    'srcDoc', 'srcSet', 'start', 'step', 'tabIndex', 'target',
    'title', 'type', 'useMap', 'value', 'wmode']
# TODO: add `label` back - it conflicts with the actual html element type I think

class Component(collections.MutableSequence):
    def __init__(self, **kwargs):
        for required_key in ['content', 'id']:
            if required_key not in kwargs:
                raise Exception("'{}' is a required keyword "
                                "argument.".format(required_key))

        for k, v in kwargs.iteritems():
            if k in ['id', 'content', 'className', 'style', 'selected'] or v is not None:  # not sure about this -- sometimes the user will want to send up None, like to clear the output cell
                setattr(self, k, v)
        if 'dependencies' in kwargs:
            self.dependencies = kwargs['dependencies']

    def to_plotly_json(self):
        as_json = {
            'props': {p: getattr(self, p)
                      for p in self._prop_names
                      if p != 'content' and hasattr(self, p)},
            'type': self._type,
            'children': self.content
        }
        if hasattr(self, 'dependencies'):
            as_json['dependencies'] = self.dependencies
        return as_json

    def __getitem__(self, id):
        if isinstance(self.content, basestring) or self.content is None:
            raise KeyError

        for item in self.content:
            if isinstance(item, basestring) or self.content is None:
                continue
            elif getattr(item, 'id', None) == id:
                return item
            try:
                component = item[id]
            except:
                pass
            else:
                return component
        raise KeyError

    def __setitem__(self, index, component):
        if isinstance(self.content, basestring) or self.content is None:
            raise KeyError
        self.content.__setitem__(index, component)

    def __delitem__(self, id):
        if isinstance(self.content, basestring) or self.content is None:
            raise KeyError

        for i, item in enumerate(self.content):
            if isinstance(item, basestring) or self.content is None:
                continue
            else:
                if item.id == id:
                    self.content.__delitem__(i)
                    return
            try:
                item.__delitem__(id)
            except:
                pass
            else:
                return
        raise KeyError

    def __len__(self):
        if isinstance(self.content, basestring) or self.content is None:
            return 1
        else:
            count = 1
            for item in self.content:
                if (isinstance(self.content, basestring) or
                   self.content is None):
                    count += 1
                else:
                    count += item.__len__()
            return count

    def insert(self, index, component):
        if isinstance(self.content, basestring) or self.content is None:
            self.content = [self.content]
        self.content.insert(index, component)

def generate_class(typename, args, setup):
    # http://jameso.be/2013/08/06/namedtuple.html
    import sys
    c = '''class {typename}(Component):
        """A {typename} component.\nValid keys:\n{bullet_list_of_valid_keys}
        """
        def __init__(self, {default_argtext}):
            self._prop_names = {list_of_valid_keys}
            self._type = '{typename}'
            super({typename}, self).__init__({argtext})
            setup(self)

        def __repr__(self):
            if(any(getattr(self, c, None) is not None for c in self._prop_names
                   if c is not "content")):
                return '{typename}(\\n    '+', \\n    '.join([c+'='+repr(getattr(self, c, None))
                                                for c in self._prop_names if getattr(self, c, None) is not None])+'\\n)'
            else:
                return '{typename}(' + repr(self.content) + ')'
    '''
    args.extend([s for s in supported_react_attributes if s not in args])
    list_of_valid_keys = repr(args)
    bullet_list_of_valid_keys = ('- ' + ' (dflt: None)\n- '.join(args) +
                                 ' (dflt: None)')

    default_argtext = ''
    argtext = ''
    for arg in args:
        default_argtext += arg + '=None, '
        argtext += arg + '=' + arg + ', '

    default_argtext += '**kwargs'
    argtext = argtext[:-2]

    d = c.format(**locals())

    namespace = {'Component': Component, 'setup': setup}
    exec d in namespace
    result = namespace[typename]
    result.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
    return result

def empty(self):
    pass

def init_dropdown(self):
    if self.selected is None:
        self.selected = self.options[0]['val']

_valid_kwargs = ['content', 'id', 'className', 'style', 'dependencies']

_customelements = load_components(component_suites_path, _valid_kwargs)

_htmlelements = ['a', 'abbr', 'address', 'area', 'article', 'aside',
                 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote',
                 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code',
                 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details',
                 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset',
                 'figcaption', 'figure', 'footer', 'form',
                 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr',
                 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen',
                 'label', 'legend', 'li', 'link', 'main', 'map', 'mark',
                 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript',
                 'object', 'ol', 'optgroup', 'option', 'output', 'p',
                 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt',
                 'ruby', 's', 'samp', 'script', 'section', 'select',
                 'small', 'source', 'span', 'strong', 'style', 'sub',
                 'summary', 'sup', 'table', 'tbody', 'td', 'textarea',
                 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u',
                 'ul', 'var', 'video', 'wbr']

_invalid_elements = ['del']

for _i in _invalid_elements:
    _htmlelements.remove(_i)

for _h in _htmlelements:
    globals()[_h] = generate_class(_h, _valid_kwargs, empty)

for _s in _customelements:
    globals()[_s['type']] = generate_class(_s['type'],
                                           _s['valid_kwargs'],
                                           _s['setup'])

def gen_table(rows, header=[]):
    tbl = table([
        thead([
            tr([
                th(h) for h in header
            ])
        ]),
        tbody([
            tr([
                td(cell) for cell in row
            ]) for row in rows
        ])
    ])
    return tbl
<commit_msg>:bug: Fix path to `dash-core-components` metadata<commit_after>import collections
from component_loader import load_components

component_suites_path = '../renderer/node_modules/dash-core-components/lib/metadata.json';

# Other valid react attributes include:
# https://facebook.github.io/react/docs/tags-and-attributes.html#html-attributes

supported_react_attributes = [
    'src', 'height', 'width', 'accept',
    'acceptCharset', 'accessKey', 'action', 'allowFullScreen',
    'allowTransparency', 'alt', 'async', 'autoComplete', 'autoFocus',
    'autoPlay', 'cellPadding', 'cellSpacing', 'charSet', 'checked',
    'classID', 'colSpan', 'cols', 'content', 'contentEditable',
    'contextMenu', 'controls', 'coords', 'crossOrigin', 'data',
    'dateTime', 'defer', 'dir', 'disabled', 'download', 'draggable',
    'encType', 'form', 'formAction', 'formEncType', 'formMethod',
    'formNoValidate', 'formTarget', 'frameBorder', 'headers', 'hidden',
    'high', 'href', 'hrefLang', 'htmlFor', 'httpEquiv', 'icon',
    'lang', 'list', 'loop', 'low', 'manifest', 'marginHeight',
    'marginWidth', 'max', 'maxLength', 'media', 'mediaGroup',
    'method', 'min', 'multiple', 'muted', 'name', 'noValidate',
    'open', 'optimum', 'pattern', 'placeholder', 'poster', 'preload',
    'radioGroup', 'readOnly', 'rel', 'required', 'role', 'rowSpan',
    'rows', 'sandbox', 'scope', 'scoped', 'scrolling', 'seamless',
    'selected', 'shape', 'size', 'sizes', 'span', 'spellCheck',
    'srcDoc', 'srcSet', 'start', 'step', 'tabIndex', 'target',
    'title', 'type', 'useMap', 'value', 'wmode']
# TODO: add `label` back - it conflicts with the actual html element type I think

class Component(collections.MutableSequence):
    def __init__(self, **kwargs):
        for required_key in ['content', 'id']:
            if required_key not in kwargs:
                raise Exception("'{}' is a required keyword "
                                "argument.".format(required_key))

        for k, v in kwargs.iteritems():
            if k in ['id', 'content', 'className', 'style', 'selected'] or v is not None:  # not sure about this -- sometimes the user will want to send up None, like to clear the output cell
                setattr(self, k, v)
        if 'dependencies' in kwargs:
            self.dependencies = kwargs['dependencies']

    def to_plotly_json(self):
        as_json = {
            'props': {p: getattr(self, p)
                      for p in self._prop_names
                      if p != 'content' and hasattr(self, p)},
            'type': self._type,
            'children': self.content
        }
        if hasattr(self, 'dependencies'):
            as_json['dependencies'] = self.dependencies
        return as_json

    def __getitem__(self, id):
        if isinstance(self.content, basestring) or self.content is None:
            raise KeyError

        for item in self.content:
            if isinstance(item, basestring) or self.content is None:
                continue
            elif getattr(item, 'id', None) == id:
                return item
            try:
                component = item[id]
            except:
                pass
            else:
                return component
        raise KeyError

    def __setitem__(self, index, component):
        if isinstance(self.content, basestring) or self.content is None:
            raise KeyError
        self.content.__setitem__(index, component)

    def __delitem__(self, id):
        if isinstance(self.content, basestring) or self.content is None:
            raise KeyError

        for i, item in enumerate(self.content):
            if isinstance(item, basestring) or self.content is None:
                continue
            else:
                if item.id == id:
                    self.content.__delitem__(i)
                    return
            try:
                item.__delitem__(id)
            except:
                pass
            else:
                return
        raise KeyError

    def __len__(self):
        if isinstance(self.content, basestring) or self.content is None:
            return 1
        else:
            count = 1
            for item in self.content:
                if (isinstance(self.content, basestring) or
                   self.content is None):
                    count += 1
                else:
                    count += item.__len__()
            return count

    def insert(self, index, component):
        if isinstance(self.content, basestring) or self.content is None:
            self.content = [self.content]
        self.content.insert(index, component)

def generate_class(typename, args, setup):
    # http://jameso.be/2013/08/06/namedtuple.html
    import sys
    c = '''class {typename}(Component):
        """A {typename} component.\nValid keys:\n{bullet_list_of_valid_keys}
        """
        def __init__(self, {default_argtext}):
            self._prop_names = {list_of_valid_keys}
            self._type = '{typename}'
            super({typename}, self).__init__({argtext})
            setup(self)

        def __repr__(self):
            if(any(getattr(self, c, None) is not None for c in self._prop_names
                   if c is not "content")):
                return '{typename}(\\n    '+', \\n    '.join([c+'='+repr(getattr(self, c, None))
                                                for c in self._prop_names if getattr(self, c, None) is not None])+'\\n)'
            else:
                return '{typename}(' + repr(self.content) + ')'
    '''
    args.extend([s for s in supported_react_attributes if s not in args])
    list_of_valid_keys = repr(args)
    bullet_list_of_valid_keys = ('- ' + ' (dflt: None)\n- '.join(args) +
                                 ' (dflt: None)')

    default_argtext = ''
    argtext = ''
    for arg in args:
        default_argtext += arg + '=None, '
        argtext += arg + '=' + arg + ', '

    default_argtext += '**kwargs'
    argtext = argtext[:-2]

    d = c.format(**locals())

    namespace = {'Component': Component, 'setup': setup}
    exec d in namespace
    result = namespace[typename]
    result.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
    return result

def empty(self):
    pass

def init_dropdown(self):
    if self.selected is None:
        self.selected = self.options[0]['val']

_valid_kwargs = ['content', 'id', 'className', 'style', 'dependencies']

_customelements = load_components(component_suites_path, _valid_kwargs)

_htmlelements = ['a', 'abbr', 'address', 'area', 'article', 'aside',
                 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote',
                 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code',
                 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details',
                 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset',
                 'figcaption', 'figure', 'footer', 'form',
                 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr',
                 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen',
                 'label', 'legend', 'li', 'link', 'main', 'map', 'mark',
                 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript',
                 'object', 'ol', 'optgroup', 'option', 'output', 'p',
                 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt',
                 'ruby', 's', 'samp', 'script', 'section', 'select',
                 'small', 'source', 'span', 'strong', 'style', 'sub',
                 'summary', 'sup', 'table', 'tbody', 'td', 'textarea',
                 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u',
                 'ul', 'var', 'video', 'wbr']

_invalid_elements = ['del']

for _i in _invalid_elements:
    _htmlelements.remove(_i)

for _h in _htmlelements:
    globals()[_h] = generate_class(_h, _valid_kwargs, empty)

for _s in _customelements:
    globals()[_s['type']] = generate_class(_s['type'],
                                           _s['valid_kwargs'],
                                           _s['setup'])

def gen_table(rows, header=[]):
    tbl = table([
        thead([
            tr([
                th(h) for h in header
            ])
        ]),
        tbody([
            tr([
                td(cell) for cell in row
            ]) for row in rows
        ])
    ])
    return tbl
<|endoftext|>


<commit_before>__version_info__ = {
    'major': 1,
    'minor': 4,
    'micro': 3,
    'releaselevel': 'final',
    'serial': 1
}

def get_version(short=False):
    assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
    vers = ["%(major)i.%(minor)i" % __version_info__, ]
    if __version_info__['micro'] and not short:
        vers.append(".%(micro)i" % __version_info__)
    if __version_info__['releaselevel'] != 'final' and not short:
        vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
    return ''.join(vers)

__version__ = get_version()

default_app_config = 'categories.apps.CategoriesConfig'

def register():
    from categories import settings
    from categories.registration import (_process_registry, registry)
    _process_registry(settings.FK_REGISTRY, registry.register_fk)
    _process_registry(settings.M2M_REGISTRY, registry.register_m2m)

try:
    register()
except Exception as e:
    print(e)
<commit_msg>Version bump<commit_after>__version_info__ = {
    'major': 1,
    'minor': 5,
    'micro': 0,
    'releaselevel': 'final',
    'serial': 1
}

def get_version(short=False):
    assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
    vers = ["%(major)i.%(minor)i" % __version_info__, ]
    if __version_info__['micro'] and not short:
        vers.append(".%(micro)i" % __version_info__)
    if __version_info__['releaselevel'] != 'final' and not short:
        vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
    return ''.join(vers)

__version__ = get_version()

default_app_config = 'categories.apps.CategoriesConfig'

def register():
    from categories import settings
    from categories.registration import (_process_registry, registry)
    _process_registry(settings.FK_REGISTRY, registry.register_fk)
    _process_registry(settings.M2M_REGISTRY, registry.register_m2m)

try:
    register()
except Exception as e:
    print(e)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import datetime
from xml.etree import ElementTree
import urllib
import json

TITLE    = 'Sarpurinn'
PREFIX   = '/video/sarpurinn'
PREFIX_AUDIO = "/music/sarpurinn"
ART      = 'art-default.jpg'
ICON     = 'icon-default.png'
STREAM_URL = 'http://smooth.ruv.cache.is/'
INFO_URL = "http://ruv.is/sarpurinn"
SARP_STOR_DAYS = 31

def Start(): # Initialize the plug-in

  Plugin.AddViewGroup("Details", viewMode="InfoList", mediaType="items")
  Plugin.AddViewGroup("List", viewMode="List", mediaType="items")

# Setup the default attributes for the ObjectContainer
  ObjectContainer.title1 = TITLE
  ObjectContainer.view_group = 'List'
  ObjectContainer.art = R(ART)

# Setup the default attributes for the other objects
#DirectoryObject.thumb = R(ICON)
#DirectoryObject.art = R(ART)
#VideoClipObject.thumb = R(ICON)
#VideoClipObject.art = R(ART)

#####################################################################
@handler(PREFIX, TITLE)
def MainMenu():
  oc = ObjectContainer(no_cache = True)
  oc.add(DirectoryObject(key=Callback(LiveMenu), title="Live", thumb = R(ICON)))
  oc.add(DirectoryObject(key=Callback(SarpMenu), title="Sarpurinn", thumb = R(ICON)))

  return oc

@route(PREFIX + '/Createliveobject', include_container = bool)
def CreateLiveObject(url, title, summary, thumb = None, vidCodec = None, audCodec = None, media_container = None, vidRes = None, include_container=False, *args, **kwargs):

	video_object = VideoClipObject(
		key = Callback(CreateLiveObject, url = url, title = title, summary = summary, thumb = thumb, vidCodec = vidCodec, audCodec = audCodec, media_container = media_container, vidRes = vidRes, include_container = True),
		rating_key = url, ### ???????
		title = title,
		summary = summary,
		thumb = thumb,
		items = [
			MediaObject(
				parts = [
					PartObject(
						key = HTTPLiveStreamURL(Callback(PlayVideoLive, url = url))
					)
				],
				video_codec = vidCodec, #VideoCodec.H264,
				audio_codec = audCodec, #AudioCodec.AAC,
				video_resolution = vidRes,
				audio_channels = 2,
				container = media_container, #Container.MP4,
				optimized_for_streaming = True
			)
		]
	)

	if include_container:
		return ObjectContainer(objects = [video_object])
	else:
		return video_object

@route(PREFIX + '/CreateLiveRadioObject', include_container = bool)
def CreateLiveRadioObject(url, title, thumb = None, audCodec = None, media_container = None, channels = None, bit = None, include_container=False, *args, **kwargs):
	Log("Radio URL: "+url)
	track_object = TrackObject(
		key = Callback(CreateLiveRadioObject, url = url, title = title, thumb = thumb, audCodec = audCodec, media_container = media_container, channels = channels, bit = bit,  include_container = True),
		rating_key = title, ### ???????
		title = title,
		thumb = thumb,
	)

	track_object.add(
		MediaObject(
			parts = [
				PartObject(
					key = Callback(PlayMP3, url = url)
				)
			],
			audio_codec = audCodec, #AudioCodec.AAC,
			container = media_container, #Container.MP4,
			audio_channels = channels,
			bitrate = bit
		)
	)

	if include_container:
		return ObjectContainer(objects = [track_object])
	else:
		return track_object

@route(PREFIX + '/PlayAAC.aac')
def PlayAAC(url):
	return PlayAudio(url)

@route(PREFIX + '/PlayMP3.mp3')
def PlayMP3(url):
	return PlayAudio(url)

def PlayAudio(url):
	Log(url)
	return Redirect(url)

@indirect
@route(PREFIX + '/playvideolive.m3u8')
def PlayVideoLive(url):
	return IndirectResponse(VideoClipObject, key=url)

@route(PREFIX, "/livemenu")
def LiveMenu():
	oc = ObjectContainer()
	oc.add(CreateLiveObject(
		url = "http://ruvruv-live.hls.adaptive.level3.net/ruv/ruv/index/stream4.m3u8",
		title = "RÚV",
		summary = "Bein útsending RÚV",
		thumb = R("ruv.png"), #Callback(Thumb, url=thumb),
		vidCodec = VideoCodec.H264,
		audCodec = AudioCodec.AAC,
		media_container = Container.MP4,
		vidRes = "720",
		include_container=False
		)
	)
	oc.add(CreateLiveObject(
		url = "http://ruvruv2-live.hls.adaptive.level3.net/ruv/ruv2/index/stream5.m3u8",
		title = "RÚV 2",
		summary = "Bein útsending RÚV 2",
		thumb = R("ruv2.png"), #Callback(Thumb, url=thumb),
		vidCodec = VideoCodec.H264,
		audCodec = AudioCodec.AAC,
		media_container = Container.MP4,
		vidRes = "1080",
		include_container=False
		)
	)
	oc.add(CreateLiveRadioObject(
		url = "http://sip-live.hds.adaptive.level3.net/hls-live/ruv-ras1/_definst_/live/stream1.m3u8",
		title = "Rás 1",
		#summary = "Bein útsending Rás 1",
		thumb = R(ICON), #Callback(Thumb, url=thumb),
		audCodec = AudioCodec.AAC,
		media_container = Container.MP4,
		channels = 2,
		#bit = 128,
		include_container=False
		)
	)
	oc.add(CreateLiveRadioObject(
		url = "http://wms-1.visir.is/radio/orbBylgjan/playlist.m3u8",
		title = "Bylgjan",
		#summary = "Bein útsending á Bylgjunni",
		thumb = R(ICON), #Callback(Thumb, url=thumb),
		audCodec = AudioCodec.AAC,
		media_container = "mp4",#Container.MP4,
		channels = 2,
		bit = 128,
		include_container=False
		)
	)
	oc.add(CreateLiveRadioObject(
		url = "http://stream.radio.is:443/kiss",
		title = "KissFM",
		#summary = "Bein útsending á KissFM",
		thumb = R(ICON), #Callback(Thumb, url=thumb),
		audCodec = AudioCodec.MP3,
		media_container = Container.MP3,
		channels = 2,
		#bit = 112,
		include_container=False
		)
	)

	return oc

@route(PREFIX + '/createvideoobject', include_container = bool)
def CreateVideoObject(url, title, summary, thumb = None, vidCodec = None, audCodec = None, media_container = None, vidRes = None, include_container=False, *args, **kwargs):

	video_object = VideoClipObject(
		key = Callback(CreateVideoObject, url = url, title = title, summary = summary, thumb = thumb, vidCodec = vidCodec, audCodec = audCodec, media_container = media_container, vidRes = vidRes, include_container = True),
		rating_key = url, ### ???????
		title = title,
		summary = summary,
		thumb = thumb,
		items = [
			MediaObject(
				parts = [
					PartObject(
						key = Callback(PlaySarpVideo, url = url)
					)
				],
				video_codec = vidCodec, #VideoCodec.H264,
				audio_codec = audCodec, #AudioCodec.AAC,
				video_resolution = vidRes,
				audio_channels = 2,
				container = media_container, #Container.MP4,
				optimized_for_streaming = True
			)
		]
	)

	if include_container:
		return ObjectContainer(objects = [video_object])
	else:
		return video_object

@indirect
@route(PREFIX + '/playsarpvideo')
def PlaySarpVideo(url):
	URLS = [
		'lokad/{0}R{1}.mp4',
		'opid/{0}R{1}.mp4',
		'lokad/{0}M{1}.mp4'
	]
	vid_url = ""
	for url_ending in URLS:
		for nr in range(30):
			url_test = STREAM_URL + url_ending.format(url, nr)
			Log("URL TEST: "+url_test)
			if (urllib.urlopen(url_test).getcode() == 200):
				vid_url = url_test
				break
		if (vid_url != ""):
			break
	if (vid_url == ""):
		Log("Not found on server")
		return None

	Log("Final url: " + vid_url)
	return IndirectResponse(VideoClipObject, key=vid_url)

# Get the TV schedule for specified day
@route(PREFIX, "/getschedule")
def GetSchedule(dags):
	schedule = {}
	#schedule['date'] = datetime.date.today()

	url = "http://muninn.ruv.is/files/xml/ruv/" + dags + "/"
	r = urllib.urlopen(url)
	if (r.getcode() != 200):
		print "Could not get schedule"
		return None
	schedule_xml = ElementTree.fromstring(r.read())

	if (schedule_xml is None):
		print "Could not get schedule"
		return None

	for child in schedule_xml.iter("service"):
		# if (not child.tag == "service"):
		#	continue
		#Log(child)
		for entry_xml in child.iter('event'):
			entry = {}
			entry['title'] = entry_xml.find('title').text
			entry['rerun'] = entry_xml.find('rerun').text
			entry['pid'] = entry_xml.get('event-id')
			entry['showtime'] = entry_xml.get('start-time')
			entry['duration'] = entry_xml.get('duration')
			entry['sid'] = entry_xml.get('serie-id')

			# if marked then definitely "/lokad/"
			isl = entry_xml.get('mark')
			if (isl == "yes"):
				entry['isl'] = True
			elif( isl == "no"):
				entry['isl'] = False

			details_basic = entry_xml.find('description')
			if( not details_basic is None):
				entry['desc'] = details_basic.text

			entry_org_title = entry_xml.find('original-title')
			if( not entry_org_title is None ):
				entry['original-title'] = entry_org_title.text

			# If the series id is nothing then it is not a show (e.g. dagskrárlok)
			if( not entry['sid'] ):
				continue

			cat = entry_xml.find('category')
			if(  not cat is None  ):
				entry['catid'] = cat.get('value')
				entry['cat'] = cat.text

			ep = entry_xml.find('episode')
			if( not ep is None ):
				entry['ep_num'] = ep.get('number')
				entry['ep_total'] = ep.get('number-of-episodes')
			if( int(entry['ep_total']) > 1 ):
				# Append the episode number to the show title if it is a real multi-episode show
				entry['title'] = entry['title'] + " ("+entry['ep_num']+" af "+entry['ep_total']+")"
			else:
				# If it isn't a multi episode show then append the date to the title (to avoid overwriting files)
				entry['title'] = str(entry['title'])+ " (" + entry['showtime'][:16] + ")"
			if (entry['rerun'] == "yes"):
				entry['title'] = str(entry['title']) + " (RERUN)"
			#schedule[entry['pid']] = entry
			schedule[str(entry['showtime'])] = entry
	return schedule

@route(PREFIX, "/daysmenu")
def DaysMenu():
	oc = ObjectContainer()
	oc.title1 = TITLE
	oc.title2 = unicode("Veldu dag")
	oc.add(DirectoryObject(key=Callback(SarpMenu), title= unicode("Í dag")))

	for d in range(1,SARP_STOR_DAYS+1):
		dagur = datetime.date.today() - datetime.timedelta(days=d)
		oc.add(DirectoryObject(key=Callback(SarpMenu, dags = str(dagur)), title=str(dagur)))
	return oc

@route(PREFIX, "/sarpmenu")
def SarpMenu(dags = None):
	other = "Fyrri dagar"
	if dags is not None:
		other = unicode("Aðrir dagar")
	else:
		dags = str(datetime.date.today())

	# get schedule
	schedule = GetSchedule(dags)
	#schedule = sorted(schedule, key=itemgetter('showtime'), reverse=True)
	oc = ObjectContainer()
	oc.title2 = dags
	oc.add(DirectoryObject(key=Callback(DaysMenu), title=other, thumb = R(ICON)))
	Log(len(schedule.items()))
	for key, schedule_item in sorted(schedule.items()): # sorted by air time
		if (not 'pid' in schedule_item):
			continue
		titill = schedule_item['title']
		showtime = datetime.datetime.strptime(schedule_item['showtime'], '%Y-%m-%d %H:%M:%S')
		titill = showtime.strftime("%H:%M - ") + titill
		desc = schedule_item["desc"]
		#duration = schedule_item["duration"]
		item_pid = schedule_item["pid"]
		# preUrl = ""
		Log(item_pid)

		oc.add(CreateVideoObject(
			url = item_pid,
			title = titill,
			summary = desc,
			thumb = R(ICON), #Callback(Thumb, url=thumb),
			vidCodec = VideoCodec.H264,
			audCodec = AudioCodec.AAC,
			media_container = Container.MP4,
			vidRes = "576",
			include_container=False
			)
		)

	# oc.add(VideoClipObject(
		# url = STREAM_URL + "lokad/4897620",
		# title = "Rembrandt",
		# summary = "Skemmtilegt",
		# thumb = R(ICON), #Callback(Thumb, url=thumb),
		# duration = 5*60*1000,
		# #  originally_available_at = date
		# )
	# )

	return oc

def Thumb(url):

  try:
    data = HTTP.Request(url, cacheTime = CACHE_1MONTH).content
    return DataObject(data, 'image/jpeg')
  except:
    return Redirect(R(ICON)) <commit_msg>radio fix test<commit_after># -*- coding: utf-8 -*-
import datetime
from xml.etree import ElementTree
import urllib
import json

TITLE    = 'Sarpurinn'
PREFIX   = '/video/sarpurinn'
ART      = 'art-default.jpg'
ICON     = 'icon-default.png'
STREAM_URL = 'http://smooth.ruv.cache.is/'
INFO_URL = "http://ruv.is/sarpurinn"
SARP_STOR_DAYS = 31

def Start(): # Initialize the plug-in

  Plugin.AddViewGroup("Details", viewMode="InfoList", mediaType="items")
  Plugin.AddViewGroup("List", viewMode="List", mediaType="items")

# Setup the default attributes for the ObjectContainer
  ObjectContainer.title1 = TITLE
  ObjectContainer.view_group = 'List'
  ObjectContainer.art = R(ART)

# Setup the default attributes for the other objects
#DirectoryObject.thumb = R(ICON)
#DirectoryObject.art = R(ART)
#VideoClipObject.thumb = R(ICON)
#VideoClipObject.art = R(ART)

#####################################################################
@handler(PREFIX, TITLE)
def MainMenu():
  oc = ObjectContainer(no_cache = True)
  oc.add(DirectoryObject(key=Callback(LiveMenu), title="Live", thumb = R(ICON)))
  oc.add(DirectoryObject(key=Callback(SarpMenu), title="Sarpurinn", thumb = R(ICON)))

  return oc

@route(PREFIX + '/Createliveobject', include_container = bool)
def CreateLiveObject(url, title, summary, thumb = None, vidCodec = None, audCodec = None, media_container = None, vidRes = None, include_container=False, *args, **kwargs):

	video_object = VideoClipObject(
		key = Callback(CreateLiveObject, url = url, title = title, summary = summary, thumb = thumb, vidCodec = vidCodec, audCodec = audCodec, media_container = media_container, vidRes = vidRes, include_container = True),
		rating_key = url, ### ???????
		title = title,
		summary = summary,
		thumb = thumb,
		items = [
			MediaObject(
				parts = [
					PartObject(
						key = HTTPLiveStreamURL(Callback(PlayVideoLive, url = url))
					)
				],
				video_codec = vidCodec, #VideoCodec.H264,
				audio_codec = audCodec, #AudioCodec.AAC,
				video_resolution = vidRes,
				audio_channels = 2,
				container = media_container, #Container.MP4,
				optimized_for_streaming = True
			)
		]
	)

	if include_container:
		return ObjectContainer(objects = [video_object])
	else:
		return video_object

@route(PREFIX + '/CreateLiveRadioObject', include_container = bool)
def CreateLiveRadioObject(url, title, thumb = None, audCodec = None, media_container = None, channels = None, bit = None, include_container=False, *args, **kwargs):
	Log("Radio URL: "+url)
	track_object = TrackObject(
		key = Callback(CreateLiveRadioObject, url = url, title = title, thumb = thumb, audCodec = audCodec, media_container = media_container, channels = channels, bit = bit,  include_container = True),
		rating_key = title, ### ???????
		title = title,
		thumb = thumb,
	)

	track_object.add(
		MediaObject(
			parts = [
				PartObject(
					key = Callback(PlayMP3, url = url)
				)
			],
			audio_codec = audCodec, #AudioCodec.AAC,
			container = media_container, #Container.MP4,
			audio_channels = channels,
			bitrate = bit
		)
	)

	if include_container:
		return ObjectContainer(objects = [track_object])
	else:
		return track_object

@route(PREFIX + '/PlayAudio')
def PlayAudio(url):
	Log(url)
	return Redirect(url)

@indirect
@route(PREFIX + '/playvideolive.m3u8')
def PlayVideoLive(url):
	return IndirectResponse(VideoClipObject, key=url)

@route(PREFIX, "/livemenu")
def LiveMenu():
	oc = ObjectContainer()
	oc.add(CreateLiveObject(
		url = "http://ruvruv-live.hls.adaptive.level3.net/ruv/ruv/index/stream4.m3u8",
		title = "RÚV",
		summary = "Bein útsending RÚV",
		thumb = R("ruv.png"), #Callback(Thumb, url=thumb),
		vidCodec = VideoCodec.H264,
		audCodec = AudioCodec.AAC,
		media_container = Container.MP4,
		vidRes = "720",
		include_container=False
		)
	)
	oc.add(CreateLiveObject(
		url = "http://ruvruv2-live.hls.adaptive.level3.net/ruv/ruv2/index/stream5.m3u8",
		title = "RÚV 2",
		summary = "Bein útsending RÚV 2",
		thumb = R("ruv2.png"), #Callback(Thumb, url=thumb),
		vidCodec = VideoCodec.H264,
		audCodec = AudioCodec.AAC,
		media_container = Container.MP4,
		vidRes = "1080",
		include_container=False
		)
	)
	oc.add(CreateLiveRadioObject(
		url = "http://sip-live.hds.adaptive.level3.net/hls-live/ruv-ras1/_definst_/live/stream1.m3u8",
		title = "Rás 1",
		#summary = "Bein útsending Rás 1",
		thumb = R(ICON), #Callback(Thumb, url=thumb),
		audCodec = AudioCodec.AAC,
		media_container = Container.MP4,
		channels = 2,
		#bit = 128,
		include_container=False
		)
	)
	oc.add(CreateLiveRadioObject(
		url = "http://wms-1.visir.is/radio/orbBylgjan/playlist.m3u8",
		title = "Bylgjan",
		#summary = "Bein útsending á Bylgjunni",
		thumb = R(ICON), #Callback(Thumb, url=thumb),
		audCodec = AudioCodec.AAC,
		media_container = "mp4",#Container.MP4,
		channels = 2,
		bit = 128,
		include_container=False
		)
	)
	oc.add(CreateLiveRadioObject(
		url = "http://stream.radio.is:443/kiss",
		title = "KissFM",
		#summary = "Bein útsending á KissFM",
		thumb = R(ICON), #Callback(Thumb, url=thumb),
		audCodec = AudioCodec.MP3,
		media_container = Container.MP3,
		channels = 2,
		#bit = 112,
		include_container=False
		)
	)

	return oc

@route(PREFIX + '/createvideoobject', include_container = bool)
def CreateVideoObject(url, title, summary, thumb = None, vidCodec = None, audCodec = None, media_container = None, vidRes = None, include_container=False, *args, **kwargs):

	video_object = VideoClipObject(
		key = Callback(CreateVideoObject, url = url, title = title, summary = summary, thumb = thumb, vidCodec = vidCodec, audCodec = audCodec, media_container = media_container, vidRes = vidRes, include_container = True),
		rating_key = url, ### ???????
		title = title,
		summary = summary,
		thumb = thumb,
		items = [
			MediaObject(
				parts = [
					PartObject(
						key = Callback(PlaySarpVideo, url = url)
					)
				],
				video_codec = vidCodec, #VideoCodec.H264,
				audio_codec = audCodec, #AudioCodec.AAC,
				video_resolution = vidRes,
				audio_channels = 2,
				container = media_container, #Container.MP4,
				optimized_for_streaming = True
			)
		]
	)

	if include_container:
		return ObjectContainer(objects = [video_object])
	else:
		return video_object

@indirect
@route(PREFIX + '/playsarpvideo')
def PlaySarpVideo(url):
	URLS = [
		'lokad/{0}R{1}.mp4',
		'opid/{0}R{1}.mp4',
		'lokad/{0}M{1}.mp4'
	]
	vid_url = ""
	for url_ending in URLS:
		for nr in range(30):
			url_test = STREAM_URL + url_ending.format(url, nr)
			Log("URL TEST: "+url_test)
			if (urllib.urlopen(url_test).getcode() == 200):
				vid_url = url_test
				break
		if (vid_url != ""):
			break
	if (vid_url == ""):
		Log("Not found on server")
		return None

	Log("Final url: " + vid_url)
	return IndirectResponse(VideoClipObject, key=vid_url)

# Get the TV schedule for specified day
@route(PREFIX, "/getschedule")
def GetSchedule(dags):
	schedule = {}
	#schedule['date'] = datetime.date.today()

	url = "http://muninn.ruv.is/files/xml/ruv/" + dags + "/"
	r = urllib.urlopen(url)
	if (r.getcode() != 200):
		print "Could not get schedule"
		return None
	schedule_xml = ElementTree.fromstring(r.read())

	if (schedule_xml is None):
		print "Could not get schedule"
		return None

	for child in schedule_xml.iter("service"):
		# if (not child.tag == "service"):
		#	continue
		#Log(child)
		for entry_xml in child.iter('event'):
			entry = {}
			entry['title'] = entry_xml.find('title').text
			entry['rerun'] = entry_xml.find('rerun').text
			entry['pid'] = entry_xml.get('event-id')
			entry['showtime'] = entry_xml.get('start-time')
			entry['duration'] = entry_xml.get('duration')
			entry['sid'] = entry_xml.get('serie-id')

			# if marked then definitely "/lokad/"
			isl = entry_xml.get('mark')
			if (isl == "yes"):
				entry['isl'] = True
			elif( isl == "no"):
				entry['isl'] = False

			details_basic = entry_xml.find('description')
			if( not details_basic is None):
				entry['desc'] = details_basic.text

			entry_org_title = entry_xml.find('original-title')
			if( not entry_org_title is None ):
				entry['original-title'] = entry_org_title.text

			# If the series id is nothing then it is not a show (e.g. dagskrárlok)
			if( not entry['sid'] ):
				continue

			cat = entry_xml.find('category')
			if(  not cat is None  ):
				entry['catid'] = cat.get('value')
				entry['cat'] = cat.text

			ep = entry_xml.find('episode')
			if( not ep is None ):
				entry['ep_num'] = ep.get('number')
				entry['ep_total'] = ep.get('number-of-episodes')
			if( int(entry['ep_total']) > 1 ):
				# Append the episode number to the show title if it is a real multi-episode show
				entry['title'] = entry['title'] + " ("+entry['ep_num']+" af "+entry['ep_total']+")"
			else:
				# If it isn't a multi episode show then append the date to the title (to avoid overwriting files)
				entry['title'] = str(entry['title'])+ " (" + entry['showtime'][:16] + ")"
			if (entry['rerun'] == "yes"):
				entry['title'] = str(entry['title']) + " (RERUN)"
			#schedule[entry['pid']] = entry
			schedule[str(entry['showtime'])] = entry
	return schedule

@route(PREFIX, "/daysmenu")
def DaysMenu():
	oc = ObjectContainer()
	oc.title1 = TITLE
	oc.title2 = unicode("Veldu dag")
	oc.add(DirectoryObject(key=Callback(SarpMenu), title= unicode("Í dag")))

	for d in range(1,SARP_STOR_DAYS+1):
		dagur = datetime.date.today() - datetime.timedelta(days=d)
		oc.add(DirectoryObject(key=Callback(SarpMenu, dags = str(dagur)), title=str(dagur)))
	return oc

@route(PREFIX, "/sarpmenu")
def SarpMenu(dags = None):
	other = "Fyrri dagar"
	if dags is not None:
		other = unicode("Aðrir dagar")
	else:
		dags = str(datetime.date.today())

	# get schedule
	schedule = GetSchedule(dags)
	#schedule = sorted(schedule, key=itemgetter('showtime'), reverse=True)
	oc = ObjectContainer()
	oc.title2 = dags
	oc.add(DirectoryObject(key=Callback(DaysMenu), title=other, thumb = R(ICON)))
	Log(len(schedule.items()))
	for key, schedule_item in sorted(schedule.items()): # sorted by air time
		if (not 'pid' in schedule_item):
			continue
		titill = schedule_item['title']
		showtime = datetime.datetime.strptime(schedule_item['showtime'], '%Y-%m-%d %H:%M:%S')
		titill = showtime.strftime("%H:%M - ") + titill
		desc = schedule_item["desc"]
		#duration = schedule_item["duration"]
		item_pid = schedule_item["pid"]
		# preUrl = ""
		Log(item_pid)

		oc.add(CreateVideoObject(
			url = item_pid,
			title = titill,
			summary = desc,
			thumb = R(ICON), #Callback(Thumb, url=thumb),
			vidCodec = VideoCodec.H264,
			audCodec = AudioCodec.AAC,
			media_container = Container.MP4,
			vidRes = "576",
			include_container=False
			)
		)

	# oc.add(VideoClipObject(
		# url = STREAM_URL + "lokad/4897620",
		# title = "Rembrandt",
		# summary = "Skemmtilegt",
		# thumb = R(ICON), #Callback(Thumb, url=thumb),
		# duration = 5*60*1000,
		# #  originally_available_at = date
		# )
	# )

	return oc

def Thumb(url):

  try:
    data = HTTP.Request(url, cacheTime = CACHE_1MONTH).content
    return DataObject(data, 'image/jpeg')
  except:
    return Redirect(R(ICON)) <|endoftext|>


<commit_before># Blackjack - A text-based thrill-ride
# Copyright 2015 Jeff Walters

# for shuffling
import random

# Create wallet, betting amount, running gain/loss tally, and wallet and tally update function
wallet = 100
tally = 0

def updateWin():
    global wallet
    global tally
    global bet
    wallet += bet
    tally += bet
    print('Your wallet increased by ', bet, '!')
    print('Your current sessions winnings(losses) are ', tally, '.')

def updateLose():
    global wallet
    global tally
    global bet
    wallet -= bet
    tally -= bet
    print('Your wallet decreased by ', bet, '!')
    print('Your current sessions winnings(losses) are ', tally, '.')

# Create list of every card in a deck, with possible values as second component,
# in a tuple.  Aces all have a third item in the tuple as the alternate low value.
suits = ['Clubs', 'Spades', 'Diamonds', 'Hearts']
cards = [('Ace', 11, 1), ('Two', 2, 2), ('Three', 3, 3), ('Four', 4, 4),
         ('Five', 5, 5), ('Six', 6, 6), ('Seven', 7, 7), ('Eight', 8, 8),
         ('Nine', 9, 9), ('Ten', 10, 10), ('Jack', 10, 10), ('Queen', 10, 10),
         ('King', 10, 10)]
deck = [(card[0] + ' of '+ suit, card[1], card[2]) for
        card in cards for suit in suits]

# Create line of dashes
LINE_OF_DASHES = '-' * 50

# Create spacing
LINE_OF_SPACES = ' ' * 25

# Create function to print player's opening hand as well as the dealer's hand
# (only one dealer card turned over)
def handDisplay():
    print('\n\n', LINE_OF_DASHES,'\nYour hand:\n', sep='')
    for x in player_hand:
        print(LINE_OF_SPACES, x[0])
    print("\n\nDealer's hand:\n")
    print(LINE_OF_SPACES, opponent_hand[0][0])
    print(LINE_OF_SPACES, 'Unknown')
    print(LINE_OF_DASHES)

# Create function to print player's full hand as well as the dealer's full
# hand
def fullhandDisplay():
    print('\n\n', LINE_OF_DASHES,'\nYour hand:\n', sep='')
    for x in player_hand:
        print(LINE_OF_SPACES, x[0])
    print("\n\nDealer's hand:\n")
    for x in opponent_hand:
        print(LINE_OF_SPACES, x[0])
    print(LINE_OF_DASHES)

# Wrap everything in a while loop
while True:

    # Show current wallet and prompt for betting amount
    print('\nCurrent wallet: ', '$', wallet)
    print('\nGain or loss for this session: ', '$', tally, '\n')
    bet = input('Please enter an amount to bet: ')

    # Catch for anything that is either not a digit or is not between 1 and the current wallet
    while True:
        try:
            bet = int(bet)
            while bet < 1 or bet > wallet:
                print('Your current wallet is ', wallet, '.')
                bet = int(input('Please enter a bet between 1 and your current wallet: '))
            break
        except:
            bet = input('Please enter a digit between 1 and your current wallet: ')
            continue

    # Create clean copy of deck to be used for game.
    game_deck = deck.copy()

    # Initiate empty hands for player and dealer.
    player_hand = []
    opponent_hand = []

    # Begin by shuffling entire deck.
    random.shuffle(game_deck)

    # Take 4 cards away from game deck, two to player, and the other two to dealer.
    for _ in range(2):
        player_hand.append(game_deck.pop(0))
        opponent_hand.append(game_deck.pop(0))

    # Print opening hands for both sides
    handDisplay()

    # Look at values of each card in both sides' hands, build them into lists, and
    # then sum the lists.
    l = []
    for x in range(len(player_hand)):
        l.append(player_hand[x][1])

    if sum(l) > 21:
        l.sort()
        if l[-1] == 11:
            l[-1] = 1

    m = []
    for x in range(len(opponent_hand)):
        m.append(opponent_hand[x][1])

    if sum(m) > 21:
        m.sort()
        if m[-1] == 11:
            m[-1] = 1

    L = sum(l)
    M = sum(m)

    print('\n\nYour hand is worth', L, 'points.')
    print('\nDealer\'s hand so far shows', opponent_hand[0][1], 'points.')

    # This code prompts the player to hit or to stay.  If the player elects to hit, another card is popped off
    # the game deck and put into the player's hand.  There are "if tests" to detect if the card is an Ace.  If the
    # card is detected as being an Ace, it is set to a low Ace if the current hand points total is higher than 12,
    # to avoid busting.
    while L < 22:
        decision = input('\nType "H" to hit.  Type "S" to stand.')
        if decision.upper() == 'H':
            player_hand.append(game_deck.pop(0))
            print('\nYou draw', player_hand[-1][0])
            if player_hand[-1][1] == 11:
                if L > 12:
                    l.append(player_hand[-1][2])
                else:
                    l.append(player_hand[-1][1])
            else:
                l.append(player_hand[-1][1])
            if sum(l) > 21:
                l.sort()
                if l[-1] == 11:
                    l[-1] = 1

            L = sum(l)
            handDisplay()
            print('\nYour hand is now worth', L, 'points.')
        elif decision.upper() == 'S':
            print('\nStanding with:', L, 'points.')
            input('Press enter to continue...')
            break
        L = sum(l)

    # If, after all of the preceding events have left a player with a hand over 21, this prints a "losing" message.
    if L > 21:
        print('With', L, 'points, you bust!')

    else:
        print('\nDealer\'s other card is a', opponent_hand[1][0])
        fullhandDisplay()
        print('Dealer\'s full hand shows', M, 'points.')
        print('\n')
        input('Press enter to continue...')

        print('\n')

        # This section of code evaluates and prints out pertinent details of the dealer's hand.  The dealer will hit on hands
        # below 18.  This code also accounts for low and high values of aces, and will adjust them accordingly for the highest point
        # total possible without busting.
        while M < 22:
            if M > 17:
                print('Dealer stands.')
                print('Dealer\'s final hand shows', M, 'points against your hand of', L, 'points.')
                break
            elif M > 21:
                print('Dealer busts!')
                break
            opponent_hand.append(game_deck.pop(0))
            print('Dealer draws', opponent_hand[-1][0])
            fullhandDisplay()
            if opponent_hand[-1][1] == 11:
                if M > 12:
                    m.append(opponent_hand[-1][2])
                else:
                    m.append(opponent_hand[-1][1])
            else:
                m.append(opponent_hand[-1][1])

            if sum(m) > 21:
                m.sort()
                if m[-1] == 11:
                    m[-1] = 1

            M = sum(m)
            print('Dealer\'s hand now shows', M, 'points against your hand of', L, 'points.')
            input('\nPress enter to continue...\n')

    # This code evaluates final scores once more and prints an appropriate message.
    if 22 > L == M:
        print('\nPush!')
    elif 22 > L > M:
        print('\nYou win!!!')
        updateWin()
    elif 22 > M > L:
        print('\nYou lose...')
        updateLose()
    elif L > 21:
        print('\nYou lose...')
        updateLose()
    elif M > 21:
        print('\nDealer busts! You win!!!')
        updateWin()

    # Once the hand is finished, your wallet is checked to see if it is still positive.  If not, you are ejected from the game...

    if wallet < 1:
        print('You have nothing left in your wallet. \nThe bouncer will now show you to the door...')
        print('Thanks for playing!')
        break

    # Finally, the game asks if you wish to continue and exits on a 'q' or a 'Q'.
    another = input('\nWant to quit? If so, type "Q".  Press enter to continue with another game.')
    if another.upper() == 'Q':
        print('You end the game with a total gain(loss) of: ', tally, '...')
        print('Your wallet amount ends at: ', wallet, '...')
        print('Thanks for playing!')
        break

<commit_msg>This would create a new player class and shelving scheme that would preserve player data (name, single session high scores, and cumulative wallet) between sessions.<commit_after># Blackjack - A text-based thrill-ride
# Copyright 2015 Jeff Walters

# To store high scores and data
import shelve

# For shuffling
import random

# Create player class
class Player:
    def __init__(self, name, score=0, wallet=100):
        self.name = name
        self.score = score
        self.wallet = wallet

# Create function to update player's top single-session score and cumulative wallet
def updateDb():
    global wallet, tally
    db = shelve.open('highscores')
    if player.score < tally:
        player.score = tally
    player.wallet = wallet
    db[name] = player
    db.close()

# Create function to display player history and scores
def displayDb():
    db = shelve.open('highscores')
    print('\nPlayers that have played:\n')
    print(LINE_OF_DASHES)
    for player in db:
        print('Player name: ', player, '\t', 'Wallet: ', db[player].wallet,
              '\t', 'Single session high score: ', db[player].score)
    print(LINE_OF_DASHES)
    db.close()

# Create functions to updated running gain/loss tally and wallet, win or lose
def updateWin():
    global wallet, tally, bet
    wallet += bet
    tally += bet
    print('Your wallet increased by ', bet, '!')
    print('Your current sessions winnings(losses) are ', tally, '.')

def updateLose():
    global wallet, tally, bet
    wallet -= bet
    tally -= bet
    print('Your wallet decreased by ', bet, '!')
    print('Your current sessions winnings(losses) are ', tally, '.')

# Create player name and create class instance
tally = 0
name = input('Please enter your name: ')
db = shelve.open('highscores')
if name not in list(db.keys()):
    player = Player(name)
    print('Welcome, ', name, '!',sep='')
    wallet = player.wallet
    print('As a new player, your wallet will start at: ', wallet, '.', sep='')
else:
    player = db[name]
    print('Welcome back, ', name, '!', sep='')
    wallet = player.wallet
    print('Carrying over from last time, your wallet is: ', wallet, '.', sep='')
db.close()

# Create list of every card in a deck, with possible values as second component,
# in a tuple.  Aces all have a third item in the tuple as the alternate low value.
suits = ['Clubs', 'Spades', 'Diamonds', 'Hearts']
cards = [('Ace', 11, 1), ('Two', 2, 2), ('Three', 3, 3), ('Four', 4, 4),
         ('Five', 5, 5), ('Six', 6, 6), ('Seven', 7, 7), ('Eight', 8, 8),
         ('Nine', 9, 9), ('Ten', 10, 10), ('Jack', 10, 10), ('Queen', 10, 10),
         ('King', 10, 10)]
deck = [(card[0] + ' of '+ suit, card[1], card[2]) for
        card in cards for suit in suits]

# Create line of dashes
LINE_OF_DASHES = '-' * 71

# Create spacing
LINE_OF_SPACES = ' ' * 25

# Create function to print player's opening hand as well as the dealer's hand
# (only one dealer card turned over)
def handDisplay():
    print('\n\n', LINE_OF_DASHES,'\nYour hand:\n', sep='')
    for x in player_hand:
        print(LINE_OF_SPACES, x[0])
    print("\n\nDealer's hand:\n")
    print(LINE_OF_SPACES, opponent_hand[0][0])
    print(LINE_OF_SPACES, 'Unknown')
    print(LINE_OF_DASHES)

# Create function to print player's full hand as well as the dealer's full
# hand
def fullhandDisplay():
    print('\n\n', LINE_OF_DASHES,'\nYour hand:\n', sep='')
    for x in player_hand:
        print(LINE_OF_SPACES, x[0])
    print("\n\nDealer's hand:\n")
    for x in opponent_hand:
        print(LINE_OF_SPACES, x[0])
    print(LINE_OF_DASHES)

# Wrap everything in a while loop
while True:

    # Show current wallet and prompt for betting amount
    print('\nCurrent wallet: ', '$', wallet)
    print('\nGain or loss for this session: ', '$', tally, '\n')
    bet = input('Please enter an amount to bet: ')

    # Catch for anything that is either not a digit or is not between 1 and the current wallet
    while True:
        try:
            bet = int(bet)
            while bet < 1 or bet > wallet:
                print('Your current wallet is ', wallet, '.')
                bet = int(input('Please enter a bet between 1 and your current wallet: '))
            break
        except:
            bet = input('Please enter a digit between 1 and your current wallet: ')
            continue

    # Create clean copy of deck to be used for game.
    game_deck = deck.copy()

    # Initiate empty hands for player and dealer.
    player_hand = []
    opponent_hand = []

    # Begin by shuffling entire deck.
    random.shuffle(game_deck)

    # Take 4 cards away from game deck, two to player, and the other two to dealer.
    for _ in range(2):
        player_hand.append(game_deck.pop(0))
        opponent_hand.append(game_deck.pop(0))

    # Look at values of each card in both sides' hands, build them into lists, and
    # then sum the lists.
    l = []
    for x in range(len(player_hand)):
        l.append(player_hand[x][1])

    if sum(l) > 21:
        l.sort()
        if l[-1] == 11:
            l[-1] = 1

    m = []
    for x in range(len(opponent_hand)):
        m.append(opponent_hand[x][1])

    if sum(m) > 21:
        m.sort()
        if m[-1] == 11:
            m[-1] = 1

    L = sum(l)
    M = sum(m)

    # Look for blackjack in player and dealer hands
    player_blackjack = False
    opponent_blackjack = False

    for x in player_hand:
        if 'Ace' in x[0]:
            for y in player_hand:
                if 'Jack' in y[0]:
                    player_blackjack = True

    for x in opponent_hand:
        if 'Ace' in x[0]:
            for y in opponent_hand:
                if 'Jack' in y[0]:
                    opponent_blackjack = True

    if player_blackjack and opponent_blackjack:
        fullhandDisplay()
        print('All hands are blackjack... Push!!!')

    elif player_blackjack:
        fullhandDisplay()
        print('You win with a blackjack!!!')
        updateWin()
    elif opponent_blackjack:
        fullhandDisplay()
        print('Dealer has blackjack... you lose!!!')
        updateLose()
    else:
        #Print opening hands for both sides
        handDisplay()

        print('\n\nYour hand is worth', L, 'points.')
        print('\nDealer\'s hand so far shows', opponent_hand[0][1], 'points.')

        # This code prompts the player to hit or to stay.  If the player elects to hit, another card is popped off
        # the game deck and put into the player's hand.  There are "if tests" to detect if the card is an Ace.  If the
        # card is detected as being an Ace, it is set to a low Ace if the current hand points total is higher than 12,
        # to avoid busting.
        while L < 22:
            decision = input('\nType "H" to hit.  Type "S" to stand.')
            if decision.upper() == 'H':
                player_hand.append(game_deck.pop(0))
                print('\nYou draw', player_hand[-1][0])
                if player_hand[-1][1] == 11:
                    if L > 12:
                        l.append(player_hand[-1][2])
                    else:
                        l.append(player_hand[-1][1])
                else:
                    l.append(player_hand[-1][1])
                if sum(l) > 21:
                    l.sort()
                    if l[-1] == 11:
                        l[-1] = 1

                L = sum(l)
                handDisplay()
                print('\nYour hand is now worth', L, 'points.')
            elif decision.upper() == 'S':
                print('\nStanding with:', L, 'points.')
                input('Press enter to continue...')
                break
            L = sum(l)

        # If, after all of the preceding events have left a player with a hand over 21, this prints a "losing" message.
        if L > 21:
            print('With', L, 'points, you bust!')

        else:
            print('\nDealer\'s other card is a', opponent_hand[1][0])
            fullhandDisplay()
            print('Dealer\'s full hand shows', M, 'points.')
            print('\n')
            input('Press enter to continue...')

            print('\n')

            # This section of code evaluates and prints out pertinent details of the dealer's hand.  The dealer will hit on hands
            # below 18.  This code also accounts for low and high values of aces, and will adjust them accordingly for the highest point
            # total possible without busting.
            while M < 22:
                if M > 17:
                    print('Dealer stands.')
                    print('Dealer\'s final hand shows', M, 'points against your hand of', L, 'points.')
                    break
                elif M > 21:
                    print('Dealer busts!')
                    break
                opponent_hand.append(game_deck.pop(0))
                print('Dealer draws', opponent_hand[-1][0])
                fullhandDisplay()
                if opponent_hand[-1][1] == 11:
                    if M > 12:
                        m.append(opponent_hand[-1][2])
                    else:
                        m.append(opponent_hand[-1][1])
                else:
                    m.append(opponent_hand[-1][1])

                if sum(m) > 21:
                    m.sort()
                    if m[-1] == 11:
                        m[-1] = 1

                M = sum(m)
                print('Dealer\'s hand now shows', M, 'points against your hand of', L, 'points.')
                input('\nPress enter to continue...\n')

        # This code evaluates final scores once more and prints an appropriate message.
        if 22 > L == M:
            print('\nPush!')
        elif 22 > L > M:
            print('\nYou win!!!')
            updateWin()
        elif 22 > M > L:
            print('\nYou lose...')
            updateLose()
        elif L > 21:
            print('\nYou lose...')
            updateLose()
        elif M > 21:
            print('\nDealer busts! You win!!!')
            updateWin()

    # Once the hand is finished, your wallet is checked to see if it is still positive.  If not, you are ejected from the game...

    if wallet < 1:
        print('You have nothing left in your wallet. \nThe bouncer will now show you to the door...')
        print('\nThanks for playing ', name, '!', sep='')
        updateDb()
        displayDb()
        break

    # Finally, the game asks if you wish to continue and exits on a 'q' or a 'Q'.
    another = input('\nWant to quit? If so, type "Q".  Press enter to continue with another game.')
    if another.upper() == 'Q':
        print('You end the game with a total gain(loss) of: ', tally, '...')
        print('Your wallet amount ends at: ', wallet, '...')
        print('\nThanks for playing ', name,'!', sep='')
        updateDb()
        displayDb()
        break
<|endoftext|>


<commit_before>#from __future__ import print_function # good idea for python < 3
#from __future__ import division # good idea for python < 3
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
'''
reads in a PHOENIX model spectrum (FITS format)
makes a continuum flattened (normalized) spectrum over a specified wavelength range
saves the result to a text file

'specfile' is the FITS HiRes PHOENIX spectrum file which lives in directory 'dir'
'outtxt' is the new text file that will be written
'idxstart' and 'idxend' set the index of the wavelengths that are written out
(you can set the indices to 0 and -1, but that's a much bigger wavelength range than APOGEE)

you can get PHOENIX spectra from here: http://phoenix.astro.physik.uni-goettingen.de
(click "version 2.0 of the spectral library" and login as a guest when prompted)
'''

def moving_average(series, window=100, sigma=50):
    '''
    Calculates the moving average of a series by using a Gaussian kernel to smooth it.
    This function is used by continuumFlattenSpec.
    Borrowed from http://www.nehalemlabs.net/prototype/blog/2014/04/12/how-to-fix-scipys-interpolating-spline-default-behavior/

    Input: series or array, window size, and Gaussian width (sigma).
    Returns: the smoothed data and the smoothed variance.
    '''
    from scipy.signal import gaussian
    from scipy.ndimage import filters
    b = gaussian(window, sigma)
    average = filters.convolve1d(series, b/b.sum())
    var = filters.convolve1d(np.power(series-average,2), b/b.sum())
    return average, var

def continuumFlattenSpec(waves, fluxes, win=50, varwin=60, varsig=100, weight=1.0, fitplot=True):
    '''
    Fits a spline to a spectrum and divides to continuum flatten it.
    Weighting inspired by http://www.nehalemlabs.net/prototype/blog/2014/04/12/how-to-fix-scipys-interpolating-spline-default-behavior/

    !!WARNING!! this function is not one-size-fits-all and the input parameters will
    probably need to be significantly tweaked for your specific case! It is VERY EASY
    to accidentally overfit or underfit your spectrum and get a poor continuum fit!

    More specifically, this function traces the shape of the spectrum in two ways:
    (1) the maximum values of a rolling window function with size 'win'
        --> this traces the TOP of the spectrum and may be an overestimate if it's spikey
    (2) a Gaussian-smoothed version of the spectrum with window size 'varwin' and Gaussian width 'varsig'
        --> this traces the spectrum's shape but is systematically LOWER than the continuum
        --> the variance of the spectrum is also saved during this step

    Then, scipy's UnivariateSpline function is used to fit a 5th order spline to either
    (1) OR a combination of (1) and (2). In both cases, the fit is weighted by
    by 'weight' divided by the square root of /sqrt(variance).
    This kind of weighting helps balance overfitting vs. underfitting, as described
    at the link above, but it is not perfect.

    Finally, a plot of the result is shown (assuming 'fitplot' is True) so the user can
    decide if the continuum fit is acceptable or not.

    Input: wavelength array, flux array, and the parameters described above
    Returns: a pair of numpy arrays corresponding to wavelengths and flattened fluxes.
    Each array has length = original_length - 2*window.
    '''
    from scipy.interpolate import UnivariateSpline
    import pandas as pd
    from PyAstronomy import pyasl
    # Fit the continuum
    window = win
    specsmooth_top = pd.Series(fluxes).rolling(window=window, center=True).max()
    specsmooth_bot, variance = np.array(moving_average(fluxes, window=varwin, sigma=varsig))
    variance = variance[window/2:-window/2]
    w = weight/np.sqrt(variance)
    specsmooth = []
    for top in np.array(specsmooth_top)[window/2:-window/2]:
        specsmooth.append(top) # BETTER CHOICE IF SPECTRUM IS NOT SPIKEY
        #specsmooth.append((top + bot) / 2.) # BETTER CHOICE IF SPECTRUM IS SPIKEY
    waves = waves[window/2:-window/2]
    fluxes = fluxes[window/2:-window/2]
    continuum = UnivariateSpline(waves, specsmooth, k=5, w=w)(waves)
    # Plot the result
    if fitplot == True:
        fig = plt.figure()
        fig.add_subplot(211)
        plt.plot(waves, fluxes, 'b-', label='spectrum')
        plt.plot(waves, np.array(specsmooth_top)[window/2:-window/2], 'k:')
        plt.plot(waves, np.array(specsmooth_bot)[window/2:-window/2], 'k:')
        plt.plot(waves, specsmooth, 'k-', label='smoothed')
        plt.plot(waves, continuum, 'r-', label='continuum')
        plt.legend()
        fig.add_subplot(212)
        plt.plot(waves, fluxes/continuum, 'b-', label='flattened')
        plt.axhline(y=1, ls=':', color='k')
        plt.legend()
        plt.show()
    return waves, fluxes/continuum # numpy arrays

### MAIN PROGRAM BEGINS HERE ###

#######################
## edit values below ##
#######################
# directory where wavelength file lives:
#wavedir = '../../../PHOENIX/PHOENIX-ACES-AGSS-COND-2011/'
# directory where spectrum file lives:
#specdir = wavedir + 'Z-0.0/'
# spectrum file you want to run the program on:
#specfile = 'lte07000-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'
#specfile = 'lte04800-2.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'
specfile = '/Users/revhalzoo/SDSS/A4851217/lte07000-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #A4851217
#specfile = '/Users/revhalzoo/SDSS/B5285607/lte06400-5.00-0.0.Alpha=-0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #B5285607
#specfile = '/Users/revhalzoo/SDSS/C6449358/lte06500-4.50-0.0.Alpha=+0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #C6449358

# wavelength region that will be fit with a spline:
#wavestart = 4318; waveend = 7200
wavestart = 670; waveend = 2470
#wavestart = 14000; waveend = 18000
# wavelength region that will be saved (must be no longer than the above):
truncstart = 700; truncend = 2500
#truncstart = 15000; truncend = 17000
# spline fitting parameters (final result is VERY SENSITIVE to these!!):
splinewindow = 100
variancewindow = 70 #60
variancesigma = 200 #150
splineweight = 0.9
#######################
## edit values above ##
#######################

wavefits = '/Users/revhalzoo/SDSS/A4851217/lte07000-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #A4851217
#wavefits = '/Users/revhalzoo/SDSS/B5285607/lte06400-5.00-0.0.Alpha=-0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #B5285607
#wavefits = '/Users/revhalzoo/SDSS/C6449358/lte06500-4.50-0.0.Alpha=+0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #C6449358
#infits = 'lte05000-3.00+0.5.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'
#infits = wavedir + specfile
#infits = specdir + specfile
infits = '/Users/revhalzoo/SDSS/A4851217/lte07000-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #A4851217
#infits = '/Users/revhalzoo/SDSS/B5285607/lte06400-5.00-0.0.Alpha=-0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #B5285607
#infits = '/Users/revhalzoo/SDSS/C6449358/lte06500-4.50-0.0.Alpha=+0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #C6449358
outtxt = specfile[:-5] + '_' + str(truncstart) + '-' + str(truncend) + '-norm.txt'

# read in PHOENIX FITS spectrum and corresponding wavelength FITS file
hdu = fits.open(infits)
spec = hdu[0].data
hduwave = fits.open(wavefits)
wave = hduwave[0].data

# put the wavelength array in goddamn air units
# reference: Huswer et al. 2013
wave = wave / (1.0 + 0.05792105/(238.0185-(1e4/wave)**2) + 0.00167917/(57.362-(1e4/wave)**2))

# truncate spectrum to the range you want to fit
idxstart = np.where(wave > wavestart)[0][0]
idxend = np.where(wave > waveend)[0][0]
wavechunk = wave[idxstart:idxend]
specchunk = spec[idxstart:idxend]

# measure the continuum level and divide by it to flatten the spectrum
print('Flattening spectrum...')
wavenorm, specnorm = continuumFlattenSpec(wavechunk, specchunk, win=splinewindow,
                                            varwin=variancewindow, varsig=variancesigma,
                                            weight=splineweight, fitplot=True)

# truncate the flattened spectrum to final desired wavelength range
idxtruncstart = np.where(wavenorm > truncstart-100)[0][0]
idxtruncend = np.where(wavenorm > truncend+100)[0][0]
wavenorm = wavenorm[idxtruncstart:idxtruncend]
specnorm = specnorm[idxtruncstart:idxtruncend]

# plot the final spectrum
plt.plot(wavenorm, specnorm, ls='None', marker='.', label='final flattened spectrum')
plt.legend()
plt.show()

# write the result to a text file
f = open(outtxt, 'w')
for wentry, sentry in zip(wavenorm, specnorm):
    print(wentry, sentry, file=f)
f.close()
print('New spectrum written to {0}'.format(outtxt))<commit_msg>Edited wavelength to near IR<commit_after>#from __future__ import print_function # good idea for python < 3
#from __future__ import division # good idea for python < 3
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
'''
reads in a PHOENIX model spectrum (FITS format)
makes a continuum flattened (normalized) spectrum over a specified wavelength range
saves the result to a text file

'specfile' is the FITS HiRes PHOENIX spectrum file which lives in directory 'dir'
'outtxt' is the new text file that will be written
'idxstart' and 'idxend' set the index of the wavelengths that are written out
(you can set the indices to 0 and -1, but that's a much bigger wavelength range than APOGEE)

you can get PHOENIX spectra from here: http://phoenix.astro.physik.uni-goettingen.de
(click "version 2.0 of the spectral library" and login as a guest when prompted)
'''

def moving_average(series, window=100, sigma=50):
    '''
    Calculates the moving average of a series by using a Gaussian kernel to smooth it.
    This function is used by continuumFlattenSpec.
    Borrowed from http://www.nehalemlabs.net/prototype/blog/2014/04/12/how-to-fix-scipys-interpolating-spline-default-behavior/

    Input: series or array, window size, and Gaussian width (sigma).
    Returns: the smoothed data and the smoothed variance.
    '''
    from scipy.signal import gaussian
    from scipy.ndimage import filters
    b = gaussian(window, sigma)
    average = filters.convolve1d(series, b/b.sum())
    var = filters.convolve1d(np.power(series-average,2), b/b.sum())
    return average, var

def continuumFlattenSpec(waves, fluxes, win=50, varwin=60, varsig=100, weight=1.0, fitplot=True):
    '''
    Fits a spline to a spectrum and divides to continuum flatten it.
    Weighting inspired by http://www.nehalemlabs.net/prototype/blog/2014/04/12/how-to-fix-scipys-interpolating-spline-default-behavior/

    !!WARNING!! this function is not one-size-fits-all and the input parameters will
    probably need to be significantly tweaked for your specific case! It is VERY EASY
    to accidentally overfit or underfit your spectrum and get a poor continuum fit!

    More specifically, this function traces the shape of the spectrum in two ways:
    (1) the maximum values of a rolling window function with size 'win'
        --> this traces the TOP of the spectrum and may be an overestimate if it's spikey
    (2) a Gaussian-smoothed version of the spectrum with window size 'varwin' and Gaussian width 'varsig'
        --> this traces the spectrum's shape but is systematically LOWER than the continuum
        --> the variance of the spectrum is also saved during this step

    Then, scipy's UnivariateSpline function is used to fit a 5th order spline to either
    (1) OR a combination of (1) and (2). In both cases, the fit is weighted by
    by 'weight' divided by the square root of /sqrt(variance).
    This kind of weighting helps balance overfitting vs. underfitting, as described
    at the link above, but it is not perfect.

    Finally, a plot of the result is shown (assuming 'fitplot' is True) so the user can
    decide if the continuum fit is acceptable or not.

    Input: wavelength array, flux array, and the parameters described above
    Returns: a pair of numpy arrays corresponding to wavelengths and flattened fluxes.
    Each array has length = original_length - 2*window.
    '''
    from scipy.interpolate import UnivariateSpline
    import pandas as pd
    from PyAstronomy import pyasl
    # Fit the continuum
    window = win
    specsmooth_top = pd.Series(fluxes).rolling(window=window, center=True).max()
    specsmooth_bot, variance = np.array(moving_average(fluxes, window=varwin, sigma=varsig))
    variance = variance[window/2:-window/2]
    w = weight/np.sqrt(variance)
    specsmooth = []
    for top in np.array(specsmooth_top)[window/2:-window/2]:
        specsmooth.append(top) # BETTER CHOICE IF SPECTRUM IS NOT SPIKEY
        #specsmooth.append((top + bot) / 2.) # BETTER CHOICE IF SPECTRUM IS SPIKEY
    waves = waves[window/2:-window/2]
    fluxes = fluxes[window/2:-window/2]
    continuum = UnivariateSpline(waves, specsmooth, k=5, w=w)(waves)
    # Plot the result
    if fitplot == True:
        fig = plt.figure()
        fig.add_subplot(211)
        plt.plot(waves, fluxes, 'b-', label='spectrum')
        plt.plot(waves, np.array(specsmooth_top)[window/2:-window/2], 'k:')
        plt.plot(waves, np.array(specsmooth_bot)[window/2:-window/2], 'k:')
        plt.plot(waves, specsmooth, 'k-', label='smoothed')
        plt.plot(waves, continuum, 'r-', label='continuum')
        plt.legend()
        fig.add_subplot(212)
        plt.plot(waves, fluxes/continuum, 'b-', label='flattened')
        plt.axhline(y=1, ls=':', color='k')
        plt.legend()
        plt.show()
    return waves, fluxes/continuum # numpy arrays

### MAIN PROGRAM BEGINS HERE ###

#######################
## edit values below ##
#######################
# directory where wavelength file lives:
#wavedir = '../../../PHOENIX/PHOENIX-ACES-AGSS-COND-2011/'
# directory where spectrum file lives:
#specdir = wavedir + 'Z-0.0/'
# spectrum file you want to run the program on:
#specfile = 'lte07000-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'
#specfile = 'lte04800-2.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'
specfile = '/Users/revhalzoo/SDSS/A4851217/lte07000-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #A4851217
#specfile = '/Users/revhalzoo/SDSS/B5285607/lte06400-5.00-0.0.Alpha=-0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #B5285607
#specfile = '/Users/revhalzoo/SDSS/C6449358/lte06500-4.50-0.0.Alpha=+0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #C6449358

# wavelength region that will be fit with a spline:
#wavestart = 4318; waveend = 7200
#wavestart = 670; waveend = 2470
wavestart = 14000; waveend = 18000
# wavelength region that will be saved (must be no longer than the above):
#truncstart = 700; truncend = 2500
truncstart = 15000; truncend = 17000
# spline fitting parameters (final result is VERY SENSITIVE to these!!):
splinewindow = 100
variancewindow = 70 #60
variancesigma = 200 #150
splineweight = 0.9
#######################
## edit values above ##
#######################

wavefits = '/Users/revhalzoo/SDSS/A4851217/lte07000-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #A4851217
#wavefits = '/Users/revhalzoo/SDSS/B5285607/lte06400-5.00-0.0.Alpha=-0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #B5285607
#wavefits = '/Users/revhalzoo/SDSS/C6449358/lte06500-4.50-0.0.Alpha=+0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #C6449358
#infits = 'lte05000-3.00+0.5.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'
#infits = wavedir + specfile
#infits = specdir + specfile
infits = '/Users/revhalzoo/SDSS/A4851217/lte07000-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #A4851217
#infits = '/Users/revhalzoo/SDSS/B5285607/lte06400-5.00-0.0.Alpha=-0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #B5285607
#infits = '/Users/revhalzoo/SDSS/C6449358/lte06500-4.50-0.0.Alpha=+0.20.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits' #C6449358
outtxt = specfile[:-5] + '_' + str(truncstart) + '-' + str(truncend) + '-norm.txt'

# read in PHOENIX FITS spectrum and corresponding wavelength FITS file
hdu = fits.open(infits)
spec = hdu[0].data
hduwave = fits.open(wavefits)
wave = hduwave[0].data

# put the wavelength array in goddamn air units
# reference: Huswer et al. 2013
wave = wave / (1.0 + 0.05792105/(238.0185-(1e4/wave)**2) + 0.00167917/(57.362-(1e4/wave)**2))

# truncate spectrum to the range you want to fit
idxstart = np.where(wave > wavestart)[0][0]
idxend = np.where(wave > waveend)[0][0]
wavechunk = wave[idxstart:idxend]
specchunk = spec[idxstart:idxend]

# measure the continuum level and divide by it to flatten the spectrum
print('Flattening spectrum...')
wavenorm, specnorm = continuumFlattenSpec(wavechunk, specchunk, win=splinewindow,
                                            varwin=variancewindow, varsig=variancesigma,
                                            weight=splineweight, fitplot=True)

# truncate the flattened spectrum to final desired wavelength range
idxtruncstart = np.where(wavenorm > truncstart-100)[0][0]
idxtruncend = np.where(wavenorm > truncend+100)[0][0]
wavenorm = wavenorm[idxtruncstart:idxtruncend]
specnorm = specnorm[idxtruncstart:idxtruncend]

# plot the final spectrum
plt.plot(wavenorm, specnorm, ls='None', marker='.', label='final flattened spectrum')
plt.legend()
plt.show()

# write the result to a text file
f = open(outtxt, 'w')
for wentry, sentry in zip(wavenorm, specnorm):
    print(wentry, sentry, file=f)
f.close()
print('New spectrum written to {0}'.format(outtxt))<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2017-2018 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.
import numpy
from openquake.baselib.python3compat import decode
from openquake.baselib.general import countby
from openquake.commonlib import writers
from openquake.risklib import scientific

def get_loss_builder(dstore, return_periods=None, loss_dt=None):
    """
    :param dstore: datastore for an event based risk calculation
    :returns: a LossesByPeriodBuilder instance
    """
    oq = dstore['oqparam']
    weights = dstore['csm_info'].rlzs['weight']
    eff_time = oq.investigation_time * oq.ses_per_logic_tree_path
    num_events = countby(dstore['events'].value, 'rlz')
    periods = return_periods or oq.return_periods or scientific.return_periods(
        eff_time, max(num_events.values()))
    return scientific.LossesByPeriodBuilder(
        numpy.array(periods), loss_dt or oq.loss_dt(), weights, num_events,
        eff_time, oq.investigation_time)

class LossCurveExporter(object):
    """
    Exporter for the loss curves. The most important method is
    `.export(export_type, what)` where `export_type` is a string like 'csv',
    and `what` is a string called export specifier. Here are some examples
    for the export specifier:

    rlzs/sid-42   # export loss curves of site #42 for all realizations
    rlz-003/sid-42   # export all loss curves of site #42, realization #3
    stats/sid-42   # export statistical loss curves of site #42
    mean/sid-42   # export mean loss curves of site #42
    quantile-0.1/sid-42   # export quantile loss curves of site #42

    rlzs/ref-a1         # export loss curves of asset a1 for all realizations
    rlz-003/ref-a1      # export loss curves of asset a1, realization 3
    stats/ref-a1        # export statistical loss curves of asset a1
    mean/ref-a1         # export mean loss curves of asset a1
    quantile-0.1/ref-a1 # export quantile loss curves of asset a1
    """
    def __init__(self, dstore):
        self.dstore = dstore
        try:
            self.builder = get_loss_builder(dstore)
        except KeyError:  # no 'events' for non event_based_risk
            pass
        self.assetcol = dstore['assetcol']
        arefs = [decode(aref) for aref in self.assetcol.asset_refs]
        self.str2asset = dict(zip(arefs, self.assetcol))
        self.asset_refs = arefs
        oqparam = dstore['oqparam']
        self.loss_types = dstore.get_attr(oqparam.risk_model, 'loss_types')
        self.R = dstore['csm_info'].get_num_rlzs()

    def parse(self, what):
        """
        :param what:
            can be 'rlz-1/ref-asset1', 'rlz-2/sid-1', ...
        """
        if '/' not in what:
            key, spec = what, ''
        else:
            key, spec = what.split('/')
        if spec and not spec.startswith(('ref-', 'sid-')):
            raise ValueError('Wrong specification in %s' % what)
        elif spec == '':  # export losses for all assets
            aids = []
            arefs = []
            for aid, rec in enumerate(self.assetcol.array):
                aids.append(aid)
                arefs.append(self.asset_refs[aid])
        elif spec.startswith('sid-'):  # passed the site ID
            sid = int(spec[4:])
            aids = []
            arefs = []
            for aid, rec in enumerate(self.assetcol.array):
                if rec['site_id'] == sid:
                    aids.append(aid)
                    arefs.append(self.asset_refs[aid])
        elif spec.startswith('ref-'):  # passed the asset name
            arefs = [spec[4:]]
            aids = [self.str2asset[arefs[0]].ordinal]
        else:
            raise ValueError('Wrong specification in %s' % what)
        return aids, arefs, spec, key

    def export_csv(self, spec, asset_refs, curves_dict):
        """
        :param asset_ref: name of the asset
        :param curves_dict: a dictionary tag -> loss curves
        """
        writer = writers.CsvWriter(fmt=writers.FIVEDIGITS)
        ebr = hasattr(self, 'builder')
        for key in sorted(curves_dict):
            recs = curves_dict[key]
            data = [['asset', 'loss_type', 'loss', 'period' if ebr else 'poe']]
            for li, loss_type in enumerate(self.loss_types):
                if ebr:  # event_based_risk
                    array = recs[:, :, li]  # shape (A, P, LI)
                    periods = self.builder.return_periods
                    for aref, losses in zip(asset_refs, array):
                        for period, loss in zip(periods, losses):
                            data.append((aref, loss_type, loss, period))
                else:  # classical_risk
                    array = recs[loss_type]  # shape (A,) loss_curve_dt
                    for aref, losses, poes in zip(
                            asset_refs, array['losses'], array['poes']):
                        for loss, poe in zip(losses, poes):
                            data.append((aref, loss_type, loss, poe))
            dest = self.dstore.build_fname(
                'loss_curves', '%s-%s' % (spec, key) if spec else key, 'csv')
            writer.save(data, dest)
        return writer.getsaved()

    def export(self, export_type, what):
        """
        :param export_type: 'csv', 'json', ...
        :param what: string describing what to export
        :returns: list of exported file names
        """
        aids, arefs, spec, key = self.parse(what)
        if key.startswith('rlz'):
            curves = self.export_curves_rlzs(aids, key)
        else:  # statistical exports
            curves = self.export_curves_stats(aids, key)
        return getattr(self, 'export_' + export_type)(spec, arefs, curves)

    def export_curves_rlzs(self, aids, key):
        """
        :returns: a dictionary key -> record of dtype loss_curve_dt
        """
        if 'loss_curves-stats' in self.dstore:  # classical_risk
            if self.R == 1:
                data = self.dstore['loss_curves-stats'][aids]  # shape (A, 1)
            else:
                data = self.dstore['loss_curves-rlzs'][aids]  # shape (A, R)
            if key.startswith('rlz-'):
                rlzi = int(key[4:])
                return {key: data[:, rlzi]}
            # else key == 'rlzs', returns all data
            return {'rlz-%03d' % rlzi: data[:, rlzi] for rlzi in range(self.R)}

        # otherwise event_based
        curves = self.dstore['curves-rlzs'][aids]  # shape (A, R, P)
        if key.startswith('rlz-'):
            rlzi = int(key[4:])
            return {'rlz-%03d' % rlzi: curves[:, rlzi]}
        else:  # key is 'rlzs', return a dictionary will all realizations
            # this may be disabled in the future unless an asset is specified
            dic = {}
            for rlzi in range(self.R):
                dic['rlz-%03d' % rlzi] = curves[:, rlzi]
            return dic

    def export_curves_stats(self, aids, key):
        """
        :returns: a dictionary rlzi -> record of dtype loss_curve_dt
        """
        oq = self.dstore['oqparam']
        stats = oq.hazard_stats().items()  # pair (name, func)
        stat2idx = {stat[0]: s for s, stat in enumerate(stats)}
        if 'loss_curves-stats' in self.dstore:  # classical_risk
            dset = self.dstore['loss_curves-stats']
            data = dset[aids]  # shape (A, S)
            if key == 'stats':
                return {stat[0]: data[:, s] for s, stat in enumerate(stats)}
            else:  # a specific statistics
                return {key: data[:, stat2idx[key]]}
        elif 'curves-stats' in self.dstore:  # event_based_risk
            dset = self.dstore['curves-stats']
            data = dset[aids]
            if key == 'stats':
                return {stat[0]: data[:, s] for s, stat in enumerate(stats)}
            else:  # a specific statistics
                return {key: data[:, stat2idx[key]]}
        else:
            raise KeyError('no loss curves in %s' % self.dstore)
<commit_msg>Fix a mistake in the calculation of loss maps from loss curves<commit_after># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2017-2018 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.
import numpy
from openquake.baselib.python3compat import decode
from openquake.baselib.general import countby
from openquake.commonlib import writers
from openquake.risklib import scientific

def get_loss_builder(dstore, return_periods=None, loss_dt=None):
    """
    :param dstore: datastore for an event based risk calculation
    :returns: a LossesByPeriodBuilder instance
    """
    oq = dstore['oqparam']
    weights = dstore['csm_info'].rlzs['weight']
    eff_time = oq.investigation_time * oq.ses_per_logic_tree_path
    num_events = countby(dstore['events'].value, 'rlz')
    periods = return_periods or oq.return_periods or scientific.return_periods(
        eff_time, max(num_events.values()))
    return scientific.LossesByPeriodBuilder(
        numpy.array(periods), loss_dt or oq.loss_dt(), weights, num_events,
        eff_time, oq.risk_investigation_time)

class LossCurveExporter(object):
    """
    Exporter for the loss curves. The most important method is
    `.export(export_type, what)` where `export_type` is a string like 'csv',
    and `what` is a string called export specifier. Here are some examples
    for the export specifier:

    rlzs/sid-42   # export loss curves of site #42 for all realizations
    rlz-003/sid-42   # export all loss curves of site #42, realization #3
    stats/sid-42   # export statistical loss curves of site #42
    mean/sid-42   # export mean loss curves of site #42
    quantile-0.1/sid-42   # export quantile loss curves of site #42

    rlzs/ref-a1         # export loss curves of asset a1 for all realizations
    rlz-003/ref-a1      # export loss curves of asset a1, realization 3
    stats/ref-a1        # export statistical loss curves of asset a1
    mean/ref-a1         # export mean loss curves of asset a1
    quantile-0.1/ref-a1 # export quantile loss curves of asset a1
    """
    def __init__(self, dstore):
        self.dstore = dstore
        try:
            self.builder = get_loss_builder(dstore)
        except KeyError:  # no 'events' for non event_based_risk
            pass
        self.assetcol = dstore['assetcol']
        arefs = [decode(aref) for aref in self.assetcol.asset_refs]
        self.str2asset = dict(zip(arefs, self.assetcol))
        self.asset_refs = arefs
        oqparam = dstore['oqparam']
        self.loss_types = dstore.get_attr(oqparam.risk_model, 'loss_types')
        self.R = dstore['csm_info'].get_num_rlzs()

    def parse(self, what):
        """
        :param what:
            can be 'rlz-1/ref-asset1', 'rlz-2/sid-1', ...
        """
        if '/' not in what:
            key, spec = what, ''
        else:
            key, spec = what.split('/')
        if spec and not spec.startswith(('ref-', 'sid-')):
            raise ValueError('Wrong specification in %s' % what)
        elif spec == '':  # export losses for all assets
            aids = []
            arefs = []
            for aid, rec in enumerate(self.assetcol.array):
                aids.append(aid)
                arefs.append(self.asset_refs[aid])
        elif spec.startswith('sid-'):  # passed the site ID
            sid = int(spec[4:])
            aids = []
            arefs = []
            for aid, rec in enumerate(self.assetcol.array):
                if rec['site_id'] == sid:
                    aids.append(aid)
                    arefs.append(self.asset_refs[aid])
        elif spec.startswith('ref-'):  # passed the asset name
            arefs = [spec[4:]]
            aids = [self.str2asset[arefs[0]].ordinal]
        else:
            raise ValueError('Wrong specification in %s' % what)
        return aids, arefs, spec, key

    def export_csv(self, spec, asset_refs, curves_dict):
        """
        :param asset_ref: name of the asset
        :param curves_dict: a dictionary tag -> loss curves
        """
        writer = writers.CsvWriter(fmt=writers.FIVEDIGITS)
        ebr = hasattr(self, 'builder')
        for key in sorted(curves_dict):
            recs = curves_dict[key]
            data = [['asset', 'loss_type', 'loss', 'period' if ebr else 'poe']]
            for li, loss_type in enumerate(self.loss_types):
                if ebr:  # event_based_risk
                    array = recs[:, :, li]  # shape (A, P, LI)
                    periods = self.builder.return_periods
                    for aref, losses in zip(asset_refs, array):
                        for period, loss in zip(periods, losses):
                            data.append((aref, loss_type, loss, period))
                else:  # classical_risk
                    array = recs[loss_type]  # shape (A,) loss_curve_dt
                    for aref, losses, poes in zip(
                            asset_refs, array['losses'], array['poes']):
                        for loss, poe in zip(losses, poes):
                            data.append((aref, loss_type, loss, poe))
            dest = self.dstore.build_fname(
                'loss_curves', '%s-%s' % (spec, key) if spec else key, 'csv')
            writer.save(data, dest)
        return writer.getsaved()

    def export(self, export_type, what):
        """
        :param export_type: 'csv', 'json', ...
        :param what: string describing what to export
        :returns: list of exported file names
        """
        aids, arefs, spec, key = self.parse(what)
        if key.startswith('rlz'):
            curves = self.export_curves_rlzs(aids, key)
        else:  # statistical exports
            curves = self.export_curves_stats(aids, key)
        return getattr(self, 'export_' + export_type)(spec, arefs, curves)

    def export_curves_rlzs(self, aids, key):
        """
        :returns: a dictionary key -> record of dtype loss_curve_dt
        """
        if 'loss_curves-stats' in self.dstore:  # classical_risk
            if self.R == 1:
                data = self.dstore['loss_curves-stats'][aids]  # shape (A, 1)
            else:
                data = self.dstore['loss_curves-rlzs'][aids]  # shape (A, R)
            if key.startswith('rlz-'):
                rlzi = int(key[4:])
                return {key: data[:, rlzi]}
            # else key == 'rlzs', returns all data
            return {'rlz-%03d' % rlzi: data[:, rlzi] for rlzi in range(self.R)}

        # otherwise event_based
        curves = self.dstore['curves-rlzs'][aids]  # shape (A, R, P)
        if key.startswith('rlz-'):
            rlzi = int(key[4:])
            return {'rlz-%03d' % rlzi: curves[:, rlzi]}
        else:  # key is 'rlzs', return a dictionary will all realizations
            # this may be disabled in the future unless an asset is specified
            dic = {}
            for rlzi in range(self.R):
                dic['rlz-%03d' % rlzi] = curves[:, rlzi]
            return dic

    def export_curves_stats(self, aids, key):
        """
        :returns: a dictionary rlzi -> record of dtype loss_curve_dt
        """
        oq = self.dstore['oqparam']
        stats = oq.hazard_stats().items()  # pair (name, func)
        stat2idx = {stat[0]: s for s, stat in enumerate(stats)}
        if 'loss_curves-stats' in self.dstore:  # classical_risk
            dset = self.dstore['loss_curves-stats']
            data = dset[aids]  # shape (A, S)
            if key == 'stats':
                return {stat[0]: data[:, s] for s, stat in enumerate(stats)}
            else:  # a specific statistics
                return {key: data[:, stat2idx[key]]}
        elif 'curves-stats' in self.dstore:  # event_based_risk
            dset = self.dstore['curves-stats']
            data = dset[aids]
            if key == 'stats':
                return {stat[0]: data[:, s] for s, stat in enumerate(stats)}
            else:  # a specific statistics
                return {key: data[:, stat2idx[key]]}
        else:
            raise KeyError('no loss curves in %s' % self.dstore)
<|endoftext|>


<commit_before>import csv
import logging
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from models import *
from urlparse import urljoin

# Fetch credentials
from gcloud import datastore
ds = datastore.Client(project="andersen-lab")

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, date):
        serial = obj.isoformat()
        return serial
    raise TypeError("Type not serializable")

def autoconvert(s):
    for fn in (int, float):
        try:
            return fn(s)
        except ValueError:
            pass
    return s

app = Flask(__name__, static_url_path='/static')
app.config['SECRET_KEY'] = os.getenv("SECRET_KEY")
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
if os.getenv('SERVER_SOFTWARE') and \
        os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/'):
    app.debug = False
else:
    app.debug = True
    app.config['SECRET_KEY'] = "test"
    toolbar = DebugToolbarExtension(app)

from views import *
from cegwas import *<commit_msg>check datetime<commit_after>import csv
import logging
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from models import *
from datetime import date, datetime
from urlparse import urljoin

# Fetch credentials
from gcloud import datastore
ds = datastore.Client(project="andersen-lab")

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, date):
        serial = obj.isoformat()
        return serial
    raise TypeError("Type not serializable")

def autoconvert(s):
    for fn in (int, float):
        try:
            return fn(s)
        except ValueError:
            pass
    return s

app = Flask(__name__, static_url_path='/static')
app.config['SECRET_KEY'] = os.getenv("SECRET_KEY")
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
if os.getenv('SERVER_SOFTWARE') and \
        os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/'):
    app.debug = False
else:
    app.debug = True
    app.config['SECRET_KEY'] = "test"
    toolbar = DebugToolbarExtension(app)

from views import *
from cegwas import *<|endoftext|>