<commit_before>#!/usr/bin/env python
""" twitch_channels.py - Queries Twitch for channels of interest.
    Used in conjunction with livestreamer-completion.

    Usage examples:

      ./twitch_channels.py --follows myname
      ./twitch_channels.py --team eg --team teamliquid

"""

from __future__ import print_function

from argparse import ArgumentParser
from functools import partial
from itertools import chain

import requests

API_BASE_URL = "api.twitch.tv"

def api(path, *args, **params):
    insecure = params.pop("insecure", False)
    proto = insecure and "http://" or "https://"
    url = proto + API_BASE_URL + path.format(*args)
    res = requests.get(url, params=params)

    return res.json()

def page_result(res):
    for key, values in res.items():
        if not key.startswith("_"):
            return values

    return []

def iterate_pages(func, limit=25):
    offset, total = 0, limit

    while offset < total:
        res = func(limit=limit, offset=offset)
        values = page_result(res)

        offset += len(values)
        total = res.get("_total")

        yield values

def iterate_pages_result(*args, **kwargs):
    return chain.from_iterable(iterate_pages(*args, **kwargs))

# Twitch APIs
team_channels = partial(api, "/api/team/{0}/all_channels.json", insecure=True)
user_follows = partial(api, "/kraken/users/{0}/follows/channels")

parser = ArgumentParser()
parser.add_argument("-f", "--follows", action="append", default=[],
                    metavar="user", help="channels a user is following",)
parser.add_argument("-t", "--team", action="append", default=[],
                    metavar="team", help="channels that are part of a team")

def main():
    args = parser.parse_args()
    if not (args.follows or args.team):
        return parser.print_help()

    for user in args.follows:
        myuser_follows = partial(user_follows, user)

        for channel in iterate_pages_result(myuser_follows, limit=100):
            channel_name = channel.get("channel").get("name")
            print("twitch.tv/{0}".format(channel_name))

    for team in args.team:
        channels = team_channels(team).get("channels", [])
        for channel in channels:
            channel_name = channel.get("channel").get("name")
            print("twitch.tv/{0}".format(channel_name))

if __name__ == "__main__":
    main()

<commit_msg>Add a --online option to the Twitch helper.<commit_after>#!/usr/bin/env python
""" twitch_channels.py - Queries Twitch for channels of interest.
    Used in conjunction with livestreamer-completion.

    Usage examples:

      ./twitch_channels.py --follows myname
      ./twitch_channels.py --team eg --team teamliquid

"""

from __future__ import print_function

from argparse import ArgumentParser
from functools import partial
from itertools import chain

import requests

API_BASE_URL = "api.twitch.tv"

def api(path, *args, **params):
    insecure = params.pop("insecure", False)
    proto = insecure and "http://" or "https://"
    url = proto + API_BASE_URL + path.format(*args)
    res = requests.get(url, params=params)

    return res.json()

def page_result(res):
    for key, values in res.items():
        if not key.startswith("_"):
            return values

    return []

def iterate_pages(func, limit=25):
    offset, total = 0, limit

    while offset < total:
        res = func(limit=limit, offset=offset)
        values = page_result(res)

        offset += len(values)
        total = res.get("_total")

        yield values

def iterate_pages_result(*args, **kwargs):
    return chain.from_iterable(iterate_pages(*args, **kwargs))

def print_channels(channels):
    for channel in channels:
        channel_name = channel.get("channel").get("name")
        print("twitch.tv/{0}".format(channel_name))

# Twitch APIs
team_channels = partial(api, "/api/team/{0}/all_channels.json", insecure=True)
streams = partial(api, "/kraken/streams")
user_follows = partial(api, "/kraken/users/{0}/follows/channels")

parser = ArgumentParser()
parser.add_argument("-f", "--follows", action="append", default=[],
                    metavar="user", help="channels a user is following",)
parser.add_argument("-t", "--team", action="append", default=[],
                    metavar="team", help="channels that are part of a team")
parser.add_argument("-o", "--online", action="store_true",
                    help="Only return the channels that are online")

def main():
    args = parser.parse_args()
    if not (args.follows or args.team):
        return parser.print_help()

    channels = []
    for user in args.follows:
        myuser_follows = partial(user_follows, user)
        channels += iterate_pages_result(myuser_follows, limit=100)

    for team in args.team:
        channels += team_channels(team).get("channels", [])

    if args.online:
        channel_list = ",".join(c.get("channel").get("name") for c in channels)
        online_channels = streams(channel=channel_list).get("streams")
        if online_channels:
            print_channels(online_channels)
    else:
        print_channels(channels)

if __name__ == "__main__":
    main()

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import
import atexit
import os
import signal
import sys
# Import .settings before twitter due to local development of python-twitter
from .settings import (CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,
                       ACCESS_TOKEN_SECRET, COUNT_PER_GET, MEDIA_SIZES)
from .utils import download, create_directory
from .command import parse_args
import twitter

class TwitterPhotos(object):
    def __init__(self, user=None, list_slug=None, outdir=None):
        """
        :param user: The screen_name of the user whom to return results for
        :param list_slug: The slug identifying the list owned by the `user`
        :param outdir: The output directory (absolute path)
        """
        self.user = user
        self.list_slug = list_slug
        self.outdir = outdir
        self.api = twitter.Api(consumer_key=CONSUMER_KEY,
                               consumer_secret=CONSUMER_SECRET,
                               access_token_key=ACCESS_TOKEN,
                               access_token_secret=ACCESS_TOKEN_SECRET)
        self.photos = {}
        self._downloaded = 0
        self._total = 0

    def get(self, count=None, since_id=None):
        """
        Get all photos from the user or members of the list
        :param count: Number of tweets to try and retrieve. If None, return
            all photos since `since_id`
        :param since_id: An integer specifying the oldest id
        """
        self.auth_user = self.verify_credentials().screen_name
        for user in self.users:
            self.photos[user] = self.load(user=user,
                                          count=count,
                                          since_id=since_id)
            self._total += len(self.photos[user])
        return self.photos

    def load(self, user=None, count=None, max_id=None,
             since_id=None, photos=[]):
        statuses = self.api.GetUserTimeline(screen_name=user,
                                            count=count or COUNT_PER_GET,
                                            max_id=max_id,
                                            since_id=since_id,
                                            exclude_replies=True)
        if statuses:
            min_id = statuses[-1].id

        fetched_photos = [
            (s.media[0]['id'],
             s.media[0]['media_url']) for s in statuses
            if s.media and s.media[0]['type'] == 'photo'
        ]

        if statuses and count is None:
            return self.load(count=None,
                             max_id=min_id - 1,
                             since_id=since_id,
                             photos=photos + fetched_photos)
        else:
            return photos + fetched_photos

    def download(self, size=None):
        if size is None:
            size = 'large'
        if size not in MEDIA_SIZES:
            raise Exception('Invalid media size %s' % size)
        for user in self.photos:
            d = os.path.join(self.outdir or '', user)
            # Create intermediate directory
            create_directory(d)
            for photo in self.photos[user]:
                media_url = photo[1]
                self._print_progress(user, media_url)
                f = download(media_url, size, d)
                self._downloaded += 1
                #print(f)

    @property
    def users(self):
        members = None
        if self.list_slug:
            owner = self.user or self.auth_user
            print(owner)
            print(self.list_slug)
            _members = self.api.GetListMembers(list_id=None,
                                               slug=self.list_slug,
                                               owner_screen_name=owner)
            members = [member.screen_name for member in _members]
        else:
            members = [self.auth_user]
        return members

    def verify_credentials(self):
        return self.api.VerifyCredentials()

    def print_urls(self):
        for user in self.photos:
            photos = self.photos[user]
            for photo in photos:
                line = '%s %s %s' % (user, photos[0], photo[1])
                print(line)

    def _get_progress(self, user, media_url):
        m = 'Downloading %(media_url)s from %(user)s: %(index)s/%(total)s'
        d = {
            'media_url': os.path.basename(media_url),
            'user': user,
            'index': self._downloaded + 1,
            'total': self._total,
        }
        msg = m % d
        return msg

    def _print_progress(self, user, media_url):
        sys.stdout.write('\r%s' % self._get_progress(user, media_url))
        sys.stdout.flush()

def new_line():
    sys.stdout.write('\n')

def main():
    args = parse_args()
    twphotos = TwitterPhotos(user=args.user,
                             list_slug=args.list_slug,
                             outdir=args.outdir)
    twphotos.verify_credentials()
    twphotos.get()
    if args.print:
        twphotos.print_urls()
    else:
        twphotos.download()

# Register cleanup functions
atexit.register(new_line)
signal.signal(signal.SIGINT, new_line)
<commit_msg>Fix TwitterPhotos.users when specifying user only<commit_after># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import
import atexit
import os
import sys
# Import .settings before twitter due to local development of python-twitter
from .settings import (CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,
                       ACCESS_TOKEN_SECRET, COUNT_PER_GET, MEDIA_SIZES)
from .utils import download, create_directory
from .command import parse_args
import twitter

class TwitterPhotos(object):
    def __init__(self, user=None, list_slug=None, outdir=None):
        """
        :param user: The screen_name of the user whom to return results for
        :param list_slug: The slug identifying the list owned by the `user`
        :param outdir: The output directory (absolute path)
        """
        self.user = user
        self.list_slug = list_slug
        self.outdir = outdir
        self.api = twitter.Api(consumer_key=CONSUMER_KEY,
                               consumer_secret=CONSUMER_SECRET,
                               access_token_key=ACCESS_TOKEN,
                               access_token_secret=ACCESS_TOKEN_SECRET)
        self.photos = {}
        self._downloaded = 0
        self._total = 0

    def get(self, count=None, since_id=None):
        """
        Get all photos from the user or members of the list
        :param count: Number of tweets to try and retrieve. If None, return
            all photos since `since_id`
        :param since_id: An integer specifying the oldest id
        """
        self.auth_user = self.verify_credentials().screen_name
        for user in self.users:
            self.photos[user] = self.load(user=user,
                                          count=count,
                                          since_id=since_id)
            self._total += len(self.photos[user])
        return self.photos

    def load(self, user=None, count=None, max_id=None,
             since_id=None, photos=[]):
        statuses = self.api.GetUserTimeline(screen_name=user,
                                            count=count or COUNT_PER_GET,
                                            max_id=max_id,
                                            since_id=since_id,
                                            exclude_replies=True)
        if statuses:
            min_id = statuses[-1].id

        fetched_photos = [
            (s.media[0]['id'],
             s.media[0]['media_url']) for s in statuses
            if s.media and s.media[0]['type'] == 'photo'
        ]

        if statuses and count is None:
            return self.load(count=None,
                             max_id=min_id - 1,
                             since_id=since_id,
                             photos=photos + fetched_photos)
        else:
            return photos + fetched_photos

    def download(self, size=None):
        if size is None:
            size = 'large'
        if size not in MEDIA_SIZES:
            raise Exception('Invalid media size %s' % size)
        for user in self.photos:
            d = os.path.join(self.outdir or '', user)
            # Create intermediate directory
            create_directory(d)
            for photo in self.photos[user]:
                media_url = photo[1]
                self._print_progress(user, media_url)
                f = download(media_url, size, d)
                self._downloaded += 1
                #print(f)

    @property
    def users(self):
        members = None
        if self.list_slug:
            owner = self.user or self.auth_user
            print(owner)
            print(self.list_slug)
            _members = self.api.GetListMembers(list_id=None,
                                               slug=self.list_slug,
                                               owner_screen_name=owner)
            members = [member.screen_name for member in _members]
        else:
            if self.user:
                members = [self.user]
            else:
                members = [self.auth_user]
        return members

    def verify_credentials(self):
        return self.api.VerifyCredentials()

    def print_urls(self):
        for user in self.photos:
            photos = self.photos[user]
            for photo in photos:
                line = '%s %s %s' % (user, photos[0], photo[1])
                print(line)

    def _get_progress(self, user, media_url):
        m = 'Downloading %(media_url)s from %(user)s: %(index)s/%(total)s'
        d = {
            'media_url': os.path.basename(media_url),
            'user': user,
            'index': self._downloaded + 1,
            'total': self._total,
        }
        msg = m % d
        return msg

    def _print_progress(self, user, media_url):
        sys.stdout.write('\r%s' % self._get_progress(user, media_url))
        sys.stdout.flush()

def new_line():
    sys.stdout.write('\n')

def main():
    args = parse_args()
    print(args)
    twphotos = TwitterPhotos(user=args.user,
                             list_slug=args.list_slug,
                             outdir=args.outdir)
    twphotos.verify_credentials()
    twphotos.get()
    if args.print:
        twphotos.print_urls()
    else:
        twphotos.download()

# Register cleanup functions
atexit.register(new_line)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Copyright (c), 2011, the txYoga authors. See the LICENSE file for details.
"""
Resources providing the REST API to some objects.
"""
from urllib import urlencode
from urlparse import urlsplit, urlunsplit

from twisted.web.resource import IResource, Resource
from twisted.web import http

from txyoga import errors
from txyoga.serializers import json

class RESTErrorPage(Resource):
    """
    An alternative to C{ErrorPage} for REST APIs.

    Wraps a L{SerializableError}, and produces a pretty serializable form.
    """
    def __init__(self, exception, encoder, contentType):
        Resource.__init__(self)

        self.exception = exception
        self.encoder = encoder
        self.contentType = contentType

    def render(self, request):
        request.setHeader("Content-Type", self.contentType)
        request.setResponseCode(self.exception.responseCode)
        return self.encoder(self.exception)

class RESTResourceJSONEncoder(json.JSONEncoder):
    """
    A JSON encoder for REST resources.

    Equivalent to L{json.JSONEncoder}, except it also encodes
    L{SerializableError}s.
    """
    def default(self, obj):
        if isinstance(obj, errors.SerializableError):
            return {"errorMessage": obj.message, "errorDetails": obj.details}
        return json.JSONEncoder.default(self, obj)

def jsonEncode(obj):
    return json.dumps(obj, cls=RESTResourceJSONEncoder)

class Deleted(Resource):
    """
    A resource returned when an element has been successfully deleted.
    """
    def render(self, request):
        request.setResponseCode(http.NO_CONTENT)
        return ""

class EncodingResource(Resource):
    """
    A resource that understands content types.
    """
    encoders = {"application/json": jsonEncode}
    decoders = {"application/json": json.loads}
    defaultMimeType = "application/json"

    def _getEncoder(self, request):
        accept = request.getHeader("Accept") or self.defaultMimeType
        accepted = [mimeType.lower() for mimeType, _ in _parseAccept(accept)]

        for mimeType in accepted:
            try:
                encoder = self.encoders[mimeType]
                request.setHeader("Content-Type", mimeType)
                return encoder, mimeType
            except KeyError:
                continue

        raise errors.UnacceptableRequestError(self.encoders.keys(), accepted)

    def _getDecoder(self, request):
        contentType = request.getHeader("Content-Type")
        if contentType is None:
            supportedTypes = self.decoders.keys()
            raise errors.MissingContentType(supportedTypes)

        try:
            decoder = self.decoders[contentType]
            return decoder, contentType
        except KeyError:
            supportedTypes = self.decoders.keys()
            raise errors.UnsupportedContentTypeError(supportedTypes,
                                                     contentType)

class CollectionResource(EncodingResource):
    """
    A resource representing a REST collection.
    """
    def __init__(self, collection):
        Resource.__init__(self)
        self._collection = collection

    def getChild(self, path, request):
        try:
            if request.method == "DELETE" and not request.postpath:
                # Request wants to delete a child of this collection
                return self._deleteChild(path, request)

            return IResource(self._collection[path])
        except KeyError:
            return self._missingChild(path, request)

    def _deleteChild(self, identifier, request):
       self._collection.removeByIdentifier(identifier)
       return Deleted()

    def _missingChild(self, element, request):
        e = errors.MissingResourceError("no such element %s" % (element,))

        try:
            encoder, contentType = self._getEncoder(request)
        except errors.UnacceptableRequestError:
            contentType = self.defaultMimeType
            encoder = self.encoders[contentType]

        return RESTErrorPage(e, encoder, contentType)

    def render_GET(self, request):
        mimeType = self.defaultMimeType
        encoder = self.encoders[mimeType]

        try:
            encoder, mimeType = self._getEncoder(request)

            start, stop = self._getBounds(request)
            url = request.prePathURL()
            prevURL, nextURL = self._getPaginationURLs(url, start, stop)

            elements = self._collection[start:stop]
            attrs = self._collection.exposedElementAttributes
            results = [element.toState(attrs) for element in elements]
        except errors.SerializableError, e:
            errorResource = RESTErrorPage(e, encoder, mimeType)
            return errorResource.render(request)

        if (stop - start) > len(elements):
            # Not enough elements -> end of the collection
            nextURL = None

        response = {"results": results, "prev": prevURL, "next": nextURL}
        return encoder(response)

    def _getBounds(self, request):
        """
        Gets the start and stop bounds out of the query.
        """
        try:
            start, = request.args["start"]
        except KeyError:
            start = 0
        except ValueError:
            raise errors.PaginationError("More than one start in query")

        try:
            stop, = request.args["stop"]
        except KeyError:
            stop = self._collection.pageSize
        except ValueError:
            raise errors.PaginationError("More than one stop in query")

        try:
            start = int(start)
        except ValueError:
            raise errors.PaginationError("Start not an integer")

        try:
            stop = int(stop)
        except ValueError:
            raise errors.PaginationError("Stop not an integer")

        return start, stop

    def _getPaginationURLs(self, thisURL, start, stop):
        """
        Produces the URLs for the next page and the previous one.
        """
        scheme, netloc, path, _, _ = urlsplit(thisURL)
        def buildURL(start, stop):
            query = urlencode([("start", start), ("stop", stop)])
            return urlunsplit((scheme, netloc, path, query, ""))

        pageSize = stop - start

        if pageSize < 0:
            raise errors.PaginationError("Requested page size is negative")

        if pageSize > self._collection.maxPageSize:
            raise errors.PaginationError("Requested page size too large")

        prevStart, prevStop = max(0, start - pageSize), start
        if prevStart != prevStop:
            prevURL = buildURL(prevStart, prevStop)
        else:
            prevURL = None

        nextURL = buildURL(stop, stop + pageSize)

        return prevURL, nextURL

class ElementResource(EncodingResource):
    """
    A resource representing an element in a collection.
    """
    encoders = {"application/json": jsonEncode}

    def __init__(self, element):
        Resource.__init__(self)

        self._element = element

        for childName in element.children:
            child = getattr(element, childName)
            self.putChild(childName, IResource(child))

    def render_GET(self, request):
        contentType = self.defaultMimeType
        encoder = self.encoders[self.defaultMimeType]

        try:
            encoder, contentType = self._getEncoder(request)
            state = self._element.toState()
            return encoder(state)
        except errors.SerializableError, e:
            errorResource = RESTErrorPage(e, encoder, contentType)
            return errorResource.render(request)

    def render_PUT(self, request):
        try:
            decoder, contentType = self._getDecoder(request)
            state = decoder(request.body)
            self._element.update(state)
            return ""
        except errors.SerializableError, e:
            contentType = self.defaultMimeType
            encoder = self.encoders[contentType]
            errorResource = RESTErrorPage(e, encoder, contentType)
            return errorResource.render(request)

def _parseAccept(header):
    accepted = []

    for part in header.strip(".").split(","):
        part = part.strip()

        if not part:
            continue # Begone, vile hellspawn!

        elements = part.split(";")
        mimeType, rawParams = elements[0].strip(), elements[1:]
        params = dict(map(str.strip, p.split("=")) for p in rawParams)

        accepted.append((mimeType, params))

    return accepted
<commit_msg>Refactored bounds extraction<commit_after># -*- coding: utf-8 -*-
# Copyright (c), 2011, the txYoga authors. See the LICENSE file for details.
"""
Resources providing the REST API to some objects.
"""
from urllib import urlencode
from urlparse import urlsplit, urlunsplit

from twisted.web.resource import IResource, Resource
from twisted.web import http

from txyoga import errors
from txyoga.serializers import json

class RESTErrorPage(Resource):
    """
    An alternative to C{ErrorPage} for REST APIs.

    Wraps a L{SerializableError}, and produces a pretty serializable form.
    """
    def __init__(self, exception, encoder, contentType):
        Resource.__init__(self)

        self.exception = exception
        self.encoder = encoder
        self.contentType = contentType

    def render(self, request):
        request.setHeader("Content-Type", self.contentType)
        request.setResponseCode(self.exception.responseCode)
        return self.encoder(self.exception)

class RESTResourceJSONEncoder(json.JSONEncoder):
    """
    A JSON encoder for REST resources.

    Equivalent to L{json.JSONEncoder}, except it also encodes
    L{SerializableError}s.
    """
    def default(self, obj):
        if isinstance(obj, errors.SerializableError):
            return {"errorMessage": obj.message, "errorDetails": obj.details}
        return json.JSONEncoder.default(self, obj)

def jsonEncode(obj):
    return json.dumps(obj, cls=RESTResourceJSONEncoder)

class Deleted(Resource):
    """
    A resource returned when an element has been successfully deleted.
    """
    def render(self, request):
        request.setResponseCode(http.NO_CONTENT)
        return ""

class EncodingResource(Resource):
    """
    A resource that understands content types.
    """
    encoders = {"application/json": jsonEncode}
    decoders = {"application/json": json.loads}
    defaultMimeType = "application/json"

    def _getEncoder(self, request):
        accept = request.getHeader("Accept") or self.defaultMimeType
        accepted = [mimeType.lower() for mimeType, _ in _parseAccept(accept)]

        for mimeType in accepted:
            try:
                encoder = self.encoders[mimeType]
                request.setHeader("Content-Type", mimeType)
                return encoder, mimeType
            except KeyError:
                continue

        raise errors.UnacceptableRequestError(self.encoders.keys(), accepted)

    def _getDecoder(self, request):
        contentType = request.getHeader("Content-Type")
        if contentType is None:
            supportedTypes = self.decoders.keys()
            raise errors.MissingContentType(supportedTypes)

        try:
            decoder = self.decoders[contentType]
            return decoder, contentType
        except KeyError:
            supportedTypes = self.decoders.keys()
            raise errors.UnsupportedContentTypeError(supportedTypes,
                                                     contentType)

class CollectionResource(EncodingResource):
    """
    A resource representing a REST collection.
    """
    def __init__(self, collection):
        Resource.__init__(self)
        self._collection = collection

    def getChild(self, path, request):
        try:
            if request.method == "DELETE" and not request.postpath:
                # Request wants to delete a child of this collection
                return self._deleteChild(path, request)

            return IResource(self._collection[path])
        except KeyError:
            return self._missingChild(path, request)

    def _deleteChild(self, identifier, request):
       self._collection.removeByIdentifier(identifier)
       return Deleted()

    def _missingChild(self, element, request):
        e = errors.MissingResourceError("no such element %s" % (element,))

        try:
            encoder, contentType = self._getEncoder(request)
        except errors.UnacceptableRequestError:
            contentType = self.defaultMimeType
            encoder = self.encoders[contentType]

        return RESTErrorPage(e, encoder, contentType)

    def render_GET(self, request):
        mimeType = self.defaultMimeType
        encoder = self.encoders[mimeType]

        try:
            encoder, mimeType = self._getEncoder(request)

            start, stop = self._getBounds(request)
            url = request.prePathURL()
            prevURL, nextURL = self._getPaginationURLs(url, start, stop)

            elements = self._collection[start:stop]
            attrs = self._collection.exposedElementAttributes
            results = [element.toState(attrs) for element in elements]
        except errors.SerializableError, e:
            errorResource = RESTErrorPage(e, encoder, mimeType)
            return errorResource.render(request)

        if (stop - start) > len(elements):
            # Not enough elements -> end of the collection
            nextURL = None

        response = {"results": results, "prev": prevURL, "next": nextURL}
        return encoder(response)

    def _getBounds(self, request):
        """
        Gets the start and stop bounds out of the query.
        """
        start = _getBound(request.args, "start")
        stop = _getBound(request.args, "stop", self._collection.pageSize)
        return start, stop

    def _getPaginationURLs(self, thisURL, start, stop):
        """
        Produces the URLs for the next page and the previous one.
        """
        scheme, netloc, path, _, _ = urlsplit(thisURL)
        def buildURL(start, stop):
            query = urlencode([("start", start), ("stop", stop)])
            return urlunsplit((scheme, netloc, path, query, ""))

        pageSize = stop - start

        if pageSize < 0:
            raise errors.PaginationError("Requested page size is negative")

        if pageSize > self._collection.maxPageSize:
            raise errors.PaginationError("Requested page size too large")

        prevStart, prevStop = max(0, start - pageSize), start
        if prevStart != prevStop:
            prevURL = buildURL(prevStart, prevStop)
        else:
            prevURL = None

        nextURL = buildURL(stop, stop + pageSize)

        return prevURL, nextURL

def _getBound(args, key, default=0):
    """
    Gets a particular start or stop bound from the given args.
    """
    try:
        values = args[key]
        if len(values) != 1:
            raise errors.PaginationError("duplicate key %s in query" % (key,))

        return int(values[0])
    except KeyError:
        return default
    except ValueError:
        raise errors.PaginationError("key %s not an integer" % (key,))

class ElementResource(EncodingResource):
    """
    A resource representing an element in a collection.
    """
    encoders = {"application/json": jsonEncode}

    def __init__(self, element):
        Resource.__init__(self)

        self._element = element

        for childName in element.children:
            child = getattr(element, childName)
            self.putChild(childName, IResource(child))

    def render_GET(self, request):
        contentType = self.defaultMimeType
        encoder = self.encoders[self.defaultMimeType]

        try:
            encoder, contentType = self._getEncoder(request)
            state = self._element.toState()
            return encoder(state)
        except errors.SerializableError, e:
            errorResource = RESTErrorPage(e, encoder, contentType)
            return errorResource.render(request)

    def render_PUT(self, request):
        try:
            decoder, contentType = self._getDecoder(request)
            state = decoder(request.body)
            self._element.update(state)
            return ""
        except errors.SerializableError, e:
            contentType = self.defaultMimeType
            encoder = self.encoders[contentType]
            errorResource = RESTErrorPage(e, encoder, contentType)
            return errorResource.render(request)

def _parseAccept(header):
    accepted = []

    for part in header.strip(".").split(","):
        part = part.strip()

        if not part:
            continue # Begone, vile hellspawn!

        elements = part.split(";")
        mimeType, rawParams = elements[0].strip(), elements[1:]
        params = dict(map(str.strip, p.split("=")) for p in rawParams)

        accepted.append((mimeType, params))

    return accepted
<|endoftext|>


<commit_before>#!/usr/bin/env python

"""tzwhere.py - time zone computation from latitude/longitude.

Ordinarily this is loaded as a module and instances of the tzwhere
class are instantiated and queried directly, but the module can be run
as a script too, in which case it operates as follows:

Usage:
  tzwhere.py [options]

Options:
  --json_file=<file>    Path to the json input file [default: tz_world_compact.json].
  --pickle_file=<file>  Path to the pickle input file [default: tz_world.pickle].
  --read_pickle         Read pickle data instead of json [default: False].
  --write_pickle        Whether to output a pickle file [default: False].
  -h, --help            Show this help.

"""

try:
    import json
except ImportError:
    import simplejson as json
import datetime
import math
import os
import pickle

class tzwhere(object):
    SHORTCUT_DEGREES_LATITUDE = 1
    SHORTCUT_DEGREES_LONGITUDE = 1
    # By default, use the data file in our package directory
    DEFAULT_FILENAME = os.path.join(os.path.dirname(__file__),
        'tz_world_compact.json')
    PICKLE_FILENAME = os.path.join(os.path.dirname(__file__),
        'tz_world.pickle')

    def __init__(self, filename=DEFAULT_FILENAME, read_pickle=False,
            write_pickle=False):

        input_file = open(filename, 'r')

        if read_pickle:
            print 'Reading pickle input file: %s' % filename
            featureCollection = pickle.load(input_file)
        else:
            print 'Reading json input file: %s' % filename
            featureCollection = json.load(input_file)

        input_file.close()

        if write_pickle:
            print 'Writing pickle output file: %s' % self.PICKLE_FILENAME
            f = open(self.PICKLE_FILENAME, 'w')
            pickle.dump(featureCollection, f, pickle.HIGHEST_PROTOCOL)
            f.close()

        self.timezoneNamesToPolygons = {}
        for feature in featureCollection['features']:

            tzname = feature['properties']['TZID']
            if feature['geometry']['type'] == 'Polygon':
                polys = feature['geometry']['coordinates']
                if polys and not (tzname in self.timezoneNamesToPolygons):
                    self.timezoneNamesToPolygons[tzname] = []

                for raw_poly in polys:
                    # WPS84 coordinates are [long, lat], while many
                    # conventions are [lat, long] Our data is in
                    # WPS84.  Convert to an explicit format which
                    # geolib likes.
                    assert len(raw_poly) % 2 == 0
                    poly = []
                    while raw_poly:
                        lat = raw_poly.pop()
                        lng = raw_poly.pop()
                        poly.append({'lat': lat, 'lng': lng})
                    self.timezoneNamesToPolygons[tzname].append(tuple(poly))

        self.timezoneLongitudeShortcuts = {}
        self.timezoneLatitudeShortcuts = {}
        for tzname in self.timezoneNamesToPolygons:
            for polyIndex, poly in enumerate(self.timezoneNamesToPolygons[tzname]):
                lats = [x['lat'] for x in poly]
                lngs = [x['lng'] for x in poly]
                minLng = (math.floor(min(lngs) / self.SHORTCUT_DEGREES_LONGITUDE)
                          * self.SHORTCUT_DEGREES_LONGITUDE)
                maxLng = (math.floor(max(lngs) / self.SHORTCUT_DEGREES_LONGITUDE)
                          * self.SHORTCUT_DEGREES_LONGITUDE)
                minLat = (math.floor(min(lats) / self.SHORTCUT_DEGREES_LATITUDE)
                          * self.SHORTCUT_DEGREES_LATITUDE)
                maxLat = (math.floor(max(lats) / self.SHORTCUT_DEGREES_LATITUDE)
                          * self.SHORTCUT_DEGREES_LATITUDE)
                degree = minLng
                while degree <= maxLng:
                    if degree not in self.timezoneLongitudeShortcuts:
                        self.timezoneLongitudeShortcuts[degree] = {}

                    if tzname not in self.timezoneLongitudeShortcuts[degree]:
                        self.timezoneLongitudeShortcuts[degree][tzname] = []

                    self.timezoneLongitudeShortcuts[degree][tzname].append(polyIndex)
                    degree = degree + self.SHORTCUT_DEGREES_LONGITUDE

                degree = minLat
                while degree <= maxLat:
                    if degree not in self.timezoneLatitudeShortcuts:
                        self.timezoneLatitudeShortcuts[degree] = {}

                    if tzname not in self.timezoneLatitudeShortcuts[degree]:
                        self.timezoneLatitudeShortcuts[degree][tzname] = []

                    self.timezoneLatitudeShortcuts[degree][tzname].append(polyIndex)
                    degree = degree + self.SHORTCUT_DEGREES_LATITUDE

        # Convert things to tuples to save memory
        for tzname in self.timezoneNamesToPolygons.keys():
            self.timezoneNamesToPolygons[tzname] = \
                tuple(self.timezoneNamesToPolygons[tzname])
        for degree in self.timezoneLatitudeShortcuts:
            for tzname in self.timezoneLatitudeShortcuts[degree].keys():
                self.timezoneLatitudeShortcuts[degree][tzname] = \
                    tuple(self.timezoneLatitudeShortcuts[degree][tzname])
        for degree in self.timezoneLongitudeShortcuts.keys():
            for tzname in self.timezoneLongitudeShortcuts[degree].keys():
                self.timezoneLongitudeShortcuts[degree][tzname] = \
                    tuple(self.timezoneLongitudeShortcuts[degree][tzname])

    def _point_inside_polygon(self, x, y, poly):
        n = len(poly)
        inside = False

        p1x, p1y = poly[0]['lng'], poly[0]['lat']
        for i in range(n + 1):
            p2x, p2y = poly[i % n]['lng'], poly[i % n]['lat']
            if y > min(p1y, p2y):
                if y <= max(p1y, p2y):
                    if x <= max(p1x, p2x):
                        if p1y != p2y:
                            xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
                        if p1x == p2x or x <= xinters:
                            inside = not inside
            p1x, p1y = p2x, p2y

        return inside

    def tzNameAt(self, latitude, longitude):
        latTzOptions = self.timezoneLatitudeShortcuts[
            (math.floor(latitude / self.SHORTCUT_DEGREES_LATITUDE)
             * self.SHORTCUT_DEGREES_LATITUDE)
        ]
        latSet = set(latTzOptions.keys())
        lngTzOptions = self.timezoneLongitudeShortcuts[
            (math.floor(longitude / self.SHORTCUT_DEGREES_LONGITUDE)
             * self.SHORTCUT_DEGREES_LONGITUDE)
        ]
        lngSet = set(lngTzOptions.keys())
        possibleTimezones = lngSet.intersection(latSet)
        if possibleTimezones:
            if False and len(possibleTimezones) == 1:
                return possibleTimezones.pop()
            else:
                for tzname in possibleTimezones:
                    polyIndices = set(latTzOptions[tzname]).intersection(set(lngTzOptions[tzname]))
                    for polyIndex in polyIndices:
                        poly = self.timezoneNamesToPolygons[tzname][polyIndex]
                        if self._point_inside_polygon(longitude, latitude, poly):
                            return tzname

def main():
    import docopt

    args = docopt.docopt(__doc__)
    if args['--read_pickle']:
        filename = args['--pickle_file']
    else:
        filename = args['--json_file']

    start = datetime.datetime.now()
    w = tzwhere(filename, args['--read_pickle'], args['--write_pickle'])
    end = datetime.datetime.now()
    print 'Initialized in: ',
    print end - start
    print w.tzNameAt(float(35.295953), float(-89.662186))  # Arlington, TN
    print w.tzNameAt(float(33.58), float(-85.85))  # Memphis, TN
    print w.tzNameAt(float(61.17), float(-150.02))  # Anchorage, AK
    print w.tzNameAt(float(44.12), float(-123.22))  # Eugene, OR
    print w.tzNameAt(float(42.652647), float(-73.756371))  # Albany, NY

if __name__ == "__main__":
    main()
<commit_msg>Tidied and refactored choices around pickle vs json<commit_after>#!/usr/bin/env python

"""tzwhere.py - time zone computation from latitude/longitude.

Ordinarily this is loaded as a module and instances of the tzwhere
class are instantiated and queried directly, but the module can be run
as a script too, in which case it operates as follows:

Usage:
  tzwhere.py [options]

Options:
  --json_file=<file>    Path to the json input file [default: tz_world_compact.json].
  --pickle_file=<file>  Path to the pickle input file [default: tz_world.pickle].
  --read_pickle         Read pickle data instead of json [default: False].
  --write_pickle        Whether to output a pickle file [default: False].
  -h, --help            Show this help.

"""

try:
    import json
except ImportError:
    import simplejson as json
import datetime
import math
import os
import pickle

class tzwhere(object):

    SHORTCUT_DEGREES_LATITUDE = 1
    SHORTCUT_DEGREES_LONGITUDE = 1
    # By default, use the data file in our package directory
    DEFAULT_JSON = os.path.join(os.path.dirname(__file__),
        'tz_world_compact.json')
    DEFAULT_PICKLE = os.path.join(os.path.dirname(__file__),
        'tz_world.pickle')

    def __init__(self, filename=None, read_pickle=False,
                 write_pickle_path=None):

        reader = self._read_json if not read_pickle else self._read_pickle
        featureCollection = reader(filename)

        if write_pickle_path is not None:
            self._write_pickle(write_pickle_path, featureCollection)

        self._construct_polygon_map(featureCollection)
        self._construct_shortcuts()

    def _read_json(self, path=DEFAULT_JSON):
        print('Reading json input file: %s' % path)
        with open(path, 'r') as f:
            featureCollection = json.load(f)
        return featureCollection

    def _read_pickle(self, path=DEFAULT_PICKLE):
        print('Reading pickle input file: %s' % path)
        with open(path, 'r') as f:
            featureCollection = pickle.load(f)
        return featureCollection

    def _write_pickle(self, path, featureCollection):
        print 'Writing pickle output file: %s' % path
        with open(path, 'w') as f:
            pickle.dump(featureCollection, f, pickle.HIGHEST_PROTOCOL)

    def _construct_polygon_map(self, featureCollection):

        self.timezoneNamesToPolygons = {}
        for feature in featureCollection['features']:

            tzname = feature['properties']['TZID']
            if feature['geometry']['type'] == 'Polygon':
                polys = feature['geometry']['coordinates']
                if polys and not (tzname in self.timezoneNamesToPolygons):
                    self.timezoneNamesToPolygons[tzname] = []

                for raw_poly in polys:
                    # WPS84 coordinates are [long, lat], while many
                    # conventions are [lat, long] Our data is in
                    # WPS84.  Convert to an explicit format which
                    # geolib likes.
                    assert len(raw_poly) % 2 == 0
                    poly = []
                    while raw_poly:
                        lat = raw_poly.pop()
                        lng = raw_poly.pop()
                        poly.append({'lat': lat, 'lng': lng})
                    self.timezoneNamesToPolygons[tzname].append(tuple(poly))

        # Convert things to tuples to save memory
        for tzname in self.timezoneNamesToPolygons.keys():
            self.timezoneNamesToPolygons[tzname] = \
                tuple(self.timezoneNamesToPolygons[tzname])

    def _construct_shortcuts(self):

        self.timezoneLongitudeShortcuts = {}
        self.timezoneLatitudeShortcuts = {}
        for tzname in self.timezoneNamesToPolygons:
            for polyIndex, poly in enumerate(self.timezoneNamesToPolygons[tzname]):
                lats = [x['lat'] for x in poly]
                lngs = [x['lng'] for x in poly]
                minLng = (math.floor(min(lngs) / self.SHORTCUT_DEGREES_LONGITUDE)
                          * self.SHORTCUT_DEGREES_LONGITUDE)
                maxLng = (math.floor(max(lngs) / self.SHORTCUT_DEGREES_LONGITUDE)
                          * self.SHORTCUT_DEGREES_LONGITUDE)
                minLat = (math.floor(min(lats) / self.SHORTCUT_DEGREES_LATITUDE)
                          * self.SHORTCUT_DEGREES_LATITUDE)
                maxLat = (math.floor(max(lats) / self.SHORTCUT_DEGREES_LATITUDE)
                          * self.SHORTCUT_DEGREES_LATITUDE)
                degree = minLng
                while degree <= maxLng:
                    if degree not in self.timezoneLongitudeShortcuts:
                        self.timezoneLongitudeShortcuts[degree] = {}

                    if tzname not in self.timezoneLongitudeShortcuts[degree]:
                        self.timezoneLongitudeShortcuts[degree][tzname] = []

                    self.timezoneLongitudeShortcuts[degree][tzname].append(polyIndex)
                    degree = degree + self.SHORTCUT_DEGREES_LONGITUDE

                degree = minLat
                while degree <= maxLat:
                    if degree not in self.timezoneLatitudeShortcuts:
                        self.timezoneLatitudeShortcuts[degree] = {}

                    if tzname not in self.timezoneLatitudeShortcuts[degree]:
                        self.timezoneLatitudeShortcuts[degree][tzname] = []

                    self.timezoneLatitudeShortcuts[degree][tzname].append(polyIndex)
                    degree = degree + self.SHORTCUT_DEGREES_LATITUDE

        # Convert things to tuples to save memory
        for degree in self.timezoneLatitudeShortcuts:
            for tzname in self.timezoneLatitudeShortcuts[degree].keys():
                self.timezoneLatitudeShortcuts[degree][tzname] = \
                    tuple(self.timezoneLatitudeShortcuts[degree][tzname])
        for degree in self.timezoneLongitudeShortcuts.keys():
            for tzname in self.timezoneLongitudeShortcuts[degree].keys():
                self.timezoneLongitudeShortcuts[degree][tzname] = \
                    tuple(self.timezoneLongitudeShortcuts[degree][tzname])

    def _point_inside_polygon(self, x, y, poly):
        n = len(poly)
        inside = False

        p1x, p1y = poly[0]['lng'], poly[0]['lat']
        for i in range(n + 1):
            p2x, p2y = poly[i % n]['lng'], poly[i % n]['lat']
            if y > min(p1y, p2y):
                if y <= max(p1y, p2y):
                    if x <= max(p1x, p2x):
                        if p1y != p2y:
                            xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
                        if p1x == p2x or x <= xinters:
                            inside = not inside
            p1x, p1y = p2x, p2y

        return inside

    def tzNameAt(self, latitude, longitude):
        latTzOptions = self.timezoneLatitudeShortcuts[
            (math.floor(latitude / self.SHORTCUT_DEGREES_LATITUDE)
             * self.SHORTCUT_DEGREES_LATITUDE)
        ]
        latSet = set(latTzOptions.keys())
        lngTzOptions = self.timezoneLongitudeShortcuts[
            (math.floor(longitude / self.SHORTCUT_DEGREES_LONGITUDE)
             * self.SHORTCUT_DEGREES_LONGITUDE)
        ]
        lngSet = set(lngTzOptions.keys())
        possibleTimezones = lngSet.intersection(latSet)
        if possibleTimezones:
            if False and len(possibleTimezones) == 1:
                return possibleTimezones.pop()
            else:
                for tzname in possibleTimezones:
                    polyIndices = set(latTzOptions[tzname]).intersection(set(lngTzOptions[tzname]))
                    for polyIndex in polyIndices:
                        poly = self.timezoneNamesToPolygons[tzname][polyIndex]
                        if self._point_inside_polygon(longitude, latitude, poly):
                            return tzname

def main():
    try:
        import docopt
    except ImportError:
        print("Please install the docopt package to use tzwhere.py as a script.")
        import sys
        sys.exit(1)

    args = docopt.docopt(__doc__)
    if args['--read_pickle']:
        filename = args['--pickle_file']
    else:
        filename = args['--json_file']

    if args['--write_pickle']:
        write_pickle_path = args['--pickle_file']
    else:
        write_pickle_path = None

    start = datetime.datetime.now()
    w = tzwhere(filename, args['--read_pickle'], write_pickle_path)
    end = datetime.datetime.now()
    print 'Initialized in: ',
    print end - start
    print w.tzNameAt(float(35.295953), float(-89.662186))  # Arlington, TN
    print w.tzNameAt(float(33.58), float(-85.85))  # Memphis, TN
    print w.tzNameAt(float(61.17), float(-150.02))  # Anchorage, AK
    print w.tzNameAt(float(44.12), float(-123.22))  # Eugene, OR
    print w.tzNameAt(float(42.652647), float(-73.756371))  # Albany, NY

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>from currencies.models import Currency

def currencies(request):
    currencies = Currency.objects.all()

    if not request.session.get('currency'):
        request.session['currency'] = Currency.objects.get(is_default__exact=True)

    return {
        'CURRENCIES': currencies,
        'CURRENCY': request.session['currency']
    }
<commit_msg>Serialize the currency_id rather than the currency, to work with Django 1.6 JSON serialization<commit_after>from currencies.models import Currency

def currencies(request):
    currencies = Currency.objects.all()

    if not request.session.get('currency_id'):
        request.session['currency_id'] = Currency.objects.get(is_default__exact=True).id

    return {
        'CURRENCIES': currencies,
        'CURRENCY': Currency.objects.get(pk=request.session['currency_id'])
    }
<|endoftext|>


<commit_before>from currencies.models import Currency

def currencies(request):
    currencies = Currency.objects.all()

    if not request.session.get('currency'):
        request.session['currency'] = Currency.objects.get(is_default__exact=True)

    return {
        'CURRENCIES': currencies,
        'currency': request.session['currency'],  # DEPRECATED
        'CURRENCY': request.session['currency']
    }
<commit_msg>Remove the deprecated 'currency' context<commit_after>from currencies.models import Currency

def currencies(request):
    currencies = Currency.objects.all()

    if not request.session.get('currency'):
        request.session['currency'] = Currency.objects.get(is_default__exact=True)

    return {
        'CURRENCIES': currencies,
        'CURRENCY': request.session['currency']
    }
<|endoftext|>


<commit_before>from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.contrib.auth.models import User

from utils.classes import LoggedInUser

class EquipeAtendimento(models.Model):
    nome = models.CharField(
        db_index=True,
        max_length=20,
    )
    slug = models.SlugField()
    descricao = models.CharField(
        'Descrição',
        max_length=250,
        null=True,
        blank=True,
    )

    def __str__(self):
        return self.nome

    class Meta:
        db_table = 'fo2_serv_equipe'
        verbose_name = 'Equipe de atendimento'
        verbose_name_plural = 'Equipes de atendimento'

    def save(self, *args, **kwargs):
        self.slug = slugify(self.nome)
        if not self.descricao:
            self.descricao = self.nome
        super(EquipeAtendimento, self).save(*args, **kwargs)

class TipoFuncaoExercida(models.Model):
    nome = models.CharField(
        db_index=True,
        max_length=20,
    )
    slug = models.SlugField()
    # nivel_operacional:
    # -5: diretor
    # -4: gerente
    # -3: chefe
    # -2: usuário
    # -1: auxiliar
    # 1: auxiliar
    # 2: executor
    # 3: chefe
    # 4: supervisor
    # 5: supervisor geral
    nivel_operacional = models.IntegerField(
        'Nível operacional',
        default=0,
    )

    def __str__(self):
        return self.nome

    class Meta:
        db_table = 'fo2_serv_tp_funcao_exer'
        verbose_name = 'Tipo de função exercida'
        verbose_name_plural = 'Tipos de função exercida'

    def save(self, *args, **kwargs):
        self.slug = slugify(self.nome)
        super(TipoFuncaoExercida, self).save(*args, **kwargs)

class PapelUsuario(models.Model):
    usuario = models.ForeignKey(
        User, on_delete=models.PROTECT,
        verbose_name='usuário')
    funcao = models.ForeignKey(
        TipoFuncaoExercida, on_delete=models.PROTECT,
        verbose_name='função')
    equipe = models.ForeignKey(
        EquipeAtendimento, on_delete=models.PROTECT,
        null=True, blank=True,
        )

    def __str__(self):
        equipe = f" {self.equipe}" if self.equipe else ""
        return f"{self.usuario} ({self.funcao}){equipe}"

    class Meta:
        db_table = "fo2_serv_papel_usuario"
        verbose_name = "Papel de usuário"
        verbose_name_plural = "Papeis de usuário"

class NivelAtendimento(models.Model):
    nome = models.CharField(
        db_index=True,
        max_length=20,
    )
    slug = models.SlugField()
    horas = models.IntegerField(
        default=0,
    )

    def __str__(self):
        return self.nome

    class Meta:
        db_table = 'fo2_serv_nivel_atend'
        verbose_name = 'Nível de atendimento'
        verbose_name_plural = 'Níveis de atendimento'

    def save(self, *args, **kwargs):
        self.slug = slugify(self.nome)
        super(NivelAtendimento, self).save(*args, **kwargs)

class TipoDocumento(models.Model):
    nome = models.CharField(
        max_length=20,
    )
    slug = models.SlugField()

    def __str__(self):
        return f"{self.nome} ({self.slug})"

    class Meta:
        db_table = 'fo2_serv_tipo_doc'
        verbose_name = 'Tipo de documento'
        verbose_name_plural = 'Tipos de documento'

class NumeroDocumento(models.Model):
    tipo = models.ForeignKey(
        TipoDocumento, on_delete=models.PROTECT,
    )
    create_at = models.DateTimeField(
        null=True, blank=True,
        verbose_name='criado em',
    )
    user = models.ForeignKey(
        User, on_delete=models.PROTECT,
        blank=True,
        verbose_name='usuário',
    )
    ativo = models.BooleanField(
        default=False,
    )

    def __str__(self):
        return f"{self.tipo} {self.id}"

    class Meta:
        db_table = 'fo2_serv_num_doc'
        verbose_name = 'Número de documento'
        verbose_name_plural = 'Números de documento'

    def save(self, *args, **kwargs):
        now = timezone.now()
        if not self.id:
            self.create_at = now
        logged_in = LoggedInUser()
        self.user = logged_in.user
        super(NumeroDocumento, self).save(*args, **kwargs)

class TipoEvento(models.Model):
    nome = models.CharField(
        max_length=20,
    )
    slug = models.SlugField()
    ordem = models.IntegerField(
        default=0,
    )

    class Meta:
        db_table = 'fo2_serv_tipo_evento'
        verbose_name = 'Tipo de evento'
        verbose_name_plural = 'Tipos de evento'

class ServicoEvento(models.Model):
    numero = models.ForeignKey(
        NumeroDocumento, on_delete=models.PROTECT,
        verbose_name='Número',
    )
    evento = models.ForeignKey(
        TipoEvento, on_delete=models.PROTECT,
    )
    create_at = models.DateTimeField(
        null=True, blank=True,
        verbose_name='Criado em',
    )
    user = models.ForeignKey(
        User, on_delete=models.PROTECT,
        verbose_name='Usuário',
    )
    nivel = models.ForeignKey(
        NivelAtendimento, on_delete=models.PROTECT,
        verbose_name='Nível de etendimento',
    )
    equipe = models.ForeignKey(
        EquipeAtendimento, on_delete=models.PROTECT,
        verbose_name='Equipe de atendimento',
    )
    descricao = models.CharField(
        'Descrição',
        max_length=2000,
        null=True,
        blank=True,
    )

    class Meta:
        db_table = 'fo2_serv_servico_evento'
        verbose_name = 'Evento relacionado a serviços'
        verbose_name_plural = 'Eventos relacionados a serviços'

    def save(self, *args, **kwargs):
        now = timezone.now()
        if not self.id:
            self.create_at = now
        logged_in = LoggedInUser()
        self.user = logged_in.user
        super(ServicoEvento, self).save(*args, **kwargs)
<commit_msg>model TipoEvento str<commit_after>from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.contrib.auth.models import User

from utils.classes import LoggedInUser

class EquipeAtendimento(models.Model):
    nome = models.CharField(
        db_index=True,
        max_length=20,
    )
    slug = models.SlugField()
    descricao = models.CharField(
        'Descrição',
        max_length=250,
        null=True,
        blank=True,
    )

    def __str__(self):
        return self.nome

    class Meta:
        db_table = 'fo2_serv_equipe'
        verbose_name = 'Equipe de atendimento'
        verbose_name_plural = 'Equipes de atendimento'

    def save(self, *args, **kwargs):
        self.slug = slugify(self.nome)
        if not self.descricao:
            self.descricao = self.nome
        super(EquipeAtendimento, self).save(*args, **kwargs)

class TipoFuncaoExercida(models.Model):
    nome = models.CharField(
        db_index=True,
        max_length=20,
    )
    slug = models.SlugField()
    # nivel_operacional:
    # -5: diretor
    # -4: gerente
    # -3: chefe
    # -2: usuário
    # -1: auxiliar
    # 1: auxiliar
    # 2: executor
    # 3: chefe
    # 4: supervisor
    # 5: supervisor geral
    nivel_operacional = models.IntegerField(
        'Nível operacional',
        default=0,
    )

    def __str__(self):
        return self.nome

    class Meta:
        db_table = 'fo2_serv_tp_funcao_exer'
        verbose_name = 'Tipo de função exercida'
        verbose_name_plural = 'Tipos de função exercida'

    def save(self, *args, **kwargs):
        self.slug = slugify(self.nome)
        super(TipoFuncaoExercida, self).save(*args, **kwargs)

class PapelUsuario(models.Model):
    usuario = models.ForeignKey(
        User, on_delete=models.PROTECT,
        verbose_name='usuário')
    funcao = models.ForeignKey(
        TipoFuncaoExercida, on_delete=models.PROTECT,
        verbose_name='função')
    equipe = models.ForeignKey(
        EquipeAtendimento, on_delete=models.PROTECT,
        null=True, blank=True,
        )

    def __str__(self):
        equipe = f" {self.equipe}" if self.equipe else ""
        return f"{self.usuario} ({self.funcao}){equipe}"

    class Meta:
        db_table = "fo2_serv_papel_usuario"
        verbose_name = "Papel de usuário"
        verbose_name_plural = "Papeis de usuário"

class NivelAtendimento(models.Model):
    nome = models.CharField(
        db_index=True,
        max_length=20,
    )
    slug = models.SlugField()
    horas = models.IntegerField(
        default=0,
    )

    def __str__(self):
        return self.nome

    class Meta:
        db_table = 'fo2_serv_nivel_atend'
        verbose_name = 'Nível de atendimento'
        verbose_name_plural = 'Níveis de atendimento'

    def save(self, *args, **kwargs):
        self.slug = slugify(self.nome)
        super(NivelAtendimento, self).save(*args, **kwargs)

class TipoDocumento(models.Model):
    nome = models.CharField(
        max_length=20,
    )
    slug = models.SlugField()

    def __str__(self):
        return f"{self.nome} ({self.slug})"

    class Meta:
        db_table = 'fo2_serv_tipo_doc'
        verbose_name = 'Tipo de documento'
        verbose_name_plural = 'Tipos de documento'

class NumeroDocumento(models.Model):
    tipo = models.ForeignKey(
        TipoDocumento, on_delete=models.PROTECT,
    )
    create_at = models.DateTimeField(
        null=True, blank=True,
        verbose_name='criado em',
    )
    user = models.ForeignKey(
        User, on_delete=models.PROTECT,
        blank=True,
        verbose_name='usuário',
    )
    ativo = models.BooleanField(
        default=False,
    )

    def __str__(self):
        return f"{self.tipo} {self.id}"

    class Meta:
        db_table = 'fo2_serv_num_doc'
        verbose_name = 'Número de documento'
        verbose_name_plural = 'Números de documento'

    def save(self, *args, **kwargs):
        now = timezone.now()
        if not self.id:
            self.create_at = now
        logged_in = LoggedInUser()
        self.user = logged_in.user
        super(NumeroDocumento, self).save(*args, **kwargs)

class TipoEvento(models.Model):
    nome = models.CharField(
        max_length=20,
    )
    slug = models.SlugField()
    ordem = models.IntegerField(
        default=0,
    )

    def __str__(self):
        return self.nome

    class Meta:
        db_table = 'fo2_serv_tipo_evento'
        verbose_name = 'Tipo de evento'
        verbose_name_plural = 'Tipos de evento'

class ServicoEvento(models.Model):
    numero = models.ForeignKey(
        NumeroDocumento, on_delete=models.PROTECT,
        verbose_name='Número',
    )
    evento = models.ForeignKey(
        TipoEvento, on_delete=models.PROTECT,
    )
    create_at = models.DateTimeField(
        null=True, blank=True,
        verbose_name='Criado em',
    )
    user = models.ForeignKey(
        User, on_delete=models.PROTECT,
        verbose_name='Usuário',
    )
    nivel = models.ForeignKey(
        NivelAtendimento, on_delete=models.PROTECT,
        verbose_name='Nível de etendimento',
    )
    equipe = models.ForeignKey(
        EquipeAtendimento, on_delete=models.PROTECT,
        verbose_name='Equipe de atendimento',
    )
    descricao = models.CharField(
        'Descrição',
        max_length=2000,
        null=True,
        blank=True,
    )

    class Meta:
        db_table = 'fo2_serv_servico_evento'
        verbose_name = 'Evento relacionado a serviços'
        verbose_name_plural = 'Eventos relacionados a serviços'

    def save(self, *args, **kwargs):
        now = timezone.now()
        if not self.id:
            self.create_at = now
        logged_in = LoggedInUser()
        self.user = logged_in.user
        super(ServicoEvento, self).save(*args, **kwargs)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import urllib2
import cookielib

class MeteoScrapper:
	"""
	Class used to retreive meteo data from the internet
	"""

	def __init__(self):
		"""
		Init the meteo scrapper
		"""

		self.city    	 = ""
		self.cityUrl 	 = ""
		self.sky         = ""
		self.temperature = ""
		self.wind        = ""

		self.skyData         = list()
		self.temperatureData = list()
		self.windData        = list()

		self.cookieJar   = cookielib.CookieJar()
		self.opener      = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookieJar))

	def meteoTranslate(self):
		"""
		Method used to translate the meteo data retreived from the website
		"""

		# Sky translation
		if 'Clear' in self.skyData and 'sky' in self.skyData:
			self.sky = u"dégagé".encode('utf-8')

		elif 'Partly' in self.skyData and 'cloudy' in self.skyData:
			self.sky = "partiellement nuageux"

		elif 'Heavy' in self.skyData and 'rain' in self.skyData:
			self.sky = u"très pluvieux".encode('utf-8')

		# Temperature translation
		self.temperature = self.temperatureData.pop()

		# Wind translation
		if 'Gentle' in self.windData and 'breeze' in self.windData:
			self.wind = "douce brise"

		elif 'Light' in self.windData and 'breeze' in self.windData:
			self.wind = u"légère brise ".encode('utf-8')

		elif 'Moderate' in self.windData and 'breeze' in self.windData:
			self.wind = u"moyenne brise ".encode('utf-8')

	def getMeteo(self, city):
		"""
		Get the different meteo parameters for the given city

		Parameters :
			city - The targeted city
		"""

		self.city = city
		self.cityUrl = urllib2.quote(self.city.encode('utf-8'))

		url             = "http://www.yr.no/place/France/%C3%8Ele-de-France/" + self.cityUrl + "/"
		httpRequest     = urllib2.Request(url)
		page            = self.opener.open(httpRequest)
		rawdata         = page.read()
		lines_of_data   = rawdata.split('\n')
		special_lines   = [line for line in lines_of_data if line.find('og:description')>-1]
		info            = special_lines[0].replace('"','').split('content=')[1]
		sections        = info.split(':')
		sectionsRefined = sections[3].split(',')

		self.skyData         = sectionsRefined[0].split(" ")
		self.temperatureData = sectionsRefined[1].split(" ")
		self.windData        = sectionsRefined[3].split(" ")

		self.meteoTranslate()

		# For the debug
		print '-----METEO-DEBUG------'
		print self.skyData
		print self.windData
		print '----------------------'
<commit_msg>Add meteo caracteristic : rain<commit_after># -*- coding: utf-8 -*-

import urllib2
import cookielib

class MeteoScrapper:
	"""
	Class used to retreive meteo data from the internet
	"""

	def __init__(self):
		"""
		Init the meteo scrapper
		"""

		self.city    	 = ""
		self.cityUrl 	 = ""
		self.sky         = ""
		self.temperature = ""
		self.wind        = ""

		self.skyData         = list()
		self.temperatureData = list()
		self.windData        = list()

		self.cookieJar   = cookielib.CookieJar()
		self.opener      = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookieJar))

	def meteoTranslate(self):
		"""
		Method used to translate the meteo data retreived from the website
		"""

		# Sky translation
		if 'Clear' in self.skyData and 'sky' in self.skyData:
			self.sky = u"dégagé".encode('utf-8')

		elif 'Partly' in self.skyData and 'cloudy' in self.skyData:
			self.sky = "partiellement nuageux"

		elif 'Rain' in self.skyData:
			self.sky = "pluvieux"

		elif 'Heavy' in self.skyData and 'rain' in self.skyData:
			self.sky = u"très pluvieux".encode('utf-8')

		# Temperature translation
		self.temperature = self.temperatureData.pop()

		# Wind translation
		if 'Gentle' in self.windData and 'breeze' in self.windData:
			self.wind = "douce brise"

		elif 'Light' in self.windData and 'breeze' in self.windData:
			self.wind = u"légère brise ".encode('utf-8')

		elif 'Moderate' in self.windData and 'breeze' in self.windData:
			self.wind = u"moyenne brise ".encode('utf-8')

	def getMeteo(self, city):
		"""
		Get the different meteo parameters for the given city

		Parameters :
			city - The targeted city
		"""

		self.city = city
		self.cityUrl = urllib2.quote(self.city.encode('utf-8'))

		url             = "http://www.yr.no/place/France/%C3%8Ele-de-France/" + self.cityUrl + "/"
		httpRequest     = urllib2.Request(url)
		page            = self.opener.open(httpRequest)
		rawdata         = page.read()
		lines_of_data   = rawdata.split('\n')
		special_lines   = [line for line in lines_of_data if line.find('og:description')>-1]
		info            = special_lines[0].replace('"','').split('content=')[1]
		sections        = info.split(':')
		sectionsRefined = sections[3].split(',')

		self.skyData         = sectionsRefined[0].split(" ")
		self.temperatureData = sectionsRefined[1].split(" ")
		self.windData        = sectionsRefined[3].split(" ")

		self.meteoTranslate()

		# For the debug
		print '-----METEO-DEBUG------'
		print self.skyData
		print self.windData
		print '----------------------'
<|endoftext|>


<commit_before>import cloud; assert cloud
import db; assert db
import httpfile; assert httpfile

__version__ = '0.84'

# null progress, can be overridden by importers
def _progress(p):
    pass

progress = _progress

# Python2.6 compat
"""Note: We also monkey-patch subprocess for python 2.6 to
give feature parity with later versions.
"""
try:
    from subprocess import STDOUT, check_output, CalledProcessError
except ImportError:  # pragma: no cover
    # python 2.6 doesn't include check_output
    # monkey patch it in!
    import subprocess
    STDOUT = subprocess.STDOUT

    def check_output(*popenargs, **kwargs):
        if 'stdout' in kwargs:  # pragma: no cover
            raise ValueError('stdout argument not allowed, '
                             'it will be overridden.')
        process = subprocess.Popen(stdout=subprocess.PIPE,
                                   *popenargs, **kwargs)
        output, _ = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            raise subprocess.CalledProcessError(retcode, cmd,
                                                output=output)
        return output
    subprocess.check_output = check_output

    # overwrite CalledProcessError due to `output`
    # keyword not being available (in 2.6)
    class CalledProcessError(Exception):

        def __init__(self, returncode, cmd, output=None):
            self.returncode = returncode
            self.cmd = cmd
            self.output = output

        def __str__(self):
            return "Command '%s' returned non-zero exit status %d" % (
                self.cmd, self.returncode)
    subprocess.CalledProcessError = CalledProcessError
<commit_msg>Version 0.85<commit_after>import cloud; assert cloud
import db; assert db
import httpfile; assert httpfile

__version__ = '0.85'

# null progress, can be overridden by importers
def _progress(p):
    pass

progress = _progress

# Python2.6 compat
"""Note: We also monkey-patch subprocess for python 2.6 to
give feature parity with later versions.
"""
try:
    from subprocess import STDOUT, check_output, CalledProcessError
except ImportError:  # pragma: no cover
    # python 2.6 doesn't include check_output
    # monkey patch it in!
    import subprocess
    STDOUT = subprocess.STDOUT

    def check_output(*popenargs, **kwargs):
        if 'stdout' in kwargs:  # pragma: no cover
            raise ValueError('stdout argument not allowed, '
                             'it will be overridden.')
        process = subprocess.Popen(stdout=subprocess.PIPE,
                                   *popenargs, **kwargs)
        output, _ = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            raise subprocess.CalledProcessError(retcode, cmd,
                                                output=output)
        return output
    subprocess.check_output = check_output

    # overwrite CalledProcessError due to `output`
    # keyword not being available (in 2.6)
    class CalledProcessError(Exception):

        def __init__(self, returncode, cmd, output=None):
            self.returncode = returncode
            self.cmd = cmd
            self.output = output

        def __str__(self):
            return "Command '%s' returned non-zero exit status %d" % (
                self.cmd, self.returncode)
    subprocess.CalledProcessError = CalledProcessError
<|endoftext|>


<commit_before>"""Singly-Linked List in Python."""

class Node(object):
    """docstring for LinkedList."""

    def __init__(self, data=None, next_item=None):
        """Init for instance of a node."""
        self.data = data
        self.next_item = next_item

    def update_next(self, new_node):
        """Update the next item in linked list."""
        self.next_item = new_node

class LinkedList(object):
    """Class for head of Linked List."""

    def __init__(self, head=None):
        """Initialize the head node."""
        self.head = head

    def push(self, data=None):
        """Create new node in front of head."""
        new_head = Node(data)
        new_head.update_next(self.head)
        self.head = new_head

    def pop(self):
        """Remove the first value off the head of the list and return it."""
        new_head = self.head.next_item
        old_head = self.head.data
        self.head = new_head
        return old_head

    def size(self):
        """Count the objects in linked list."""
        count = 0
        curr = self.head
        while curr:
            count += 1
            curr = curr.next_item
        return count

    def search(self, val):
        """Iterate through the linked list to find instance containing val."""
        curr = self.head
        result = None
        while val != curr.data:
            curr = curr.next_item
        else:
            result = curr
        return result
<commit_msg>added function to remove list node<commit_after>"""Singly-Linked List in Python."""

class Node(object):
    """docstring for LinkedList."""

    def __init__(self, data=None, next_item=None):
        """Init for instance of a node."""
        self.data = data
        self.next_item = next_item

    def update_next(self, new_node):
        """Update the next item in linked list."""
        self.next_item = new_node

class LinkedList(object):
    """Class for head of Linked List."""

    def __init__(self, head=None):
        """Initialize the head node."""
        self.head = head

    def push(self, data=None):
        """Create new node in front of head."""
        new_head = Node(data)
        new_head.update_next(self.head)
        self.head = new_head

    def pop(self):
        """Remove the first value off the head of the list and return it."""
        new_head = self.head.next_item
        old_head = self.head.data
        self.head = new_head
        return old_head

    def size(self):
        """Count the objects in linked list."""
        count = 0
        curr = self.head
        while curr:
            count += 1
            curr = curr.next_item
        return count

    def search(self, val):
        """Iterate through the linked list to find instance containing val."""
        curr = self.head
        result = None
        while val != curr.data:
            curr = curr.next_item
        else:
            result = curr
        return result

    def remove(self, node):
        """Remove a given node in the list."""
        curr = self.head
        next_node = curr.next_item
        while curr:
            if next_item == node:
                self.head = next_node.next_item
            curr = curr.next_item
            next_node = curr.next_item

<|endoftext|>


<commit_before>import os, pickle, gzip, numpy as np

from __config__.filepath import AUX_DIR

def observe_links(filename, input_dir='meanfield_all', output_dir='meanfield_link', C_index=9):
    """
    Observe connections between meanfield entities, and save observed frequencies to file
    :param filename: filename without file extension
    :param input_dir: directory of meanfield vectors
    :param output_dir: directory to save observed link frequencies
    :param C_index: index of cardinality in filename parameters
    """
    # Parameters

    hyp = filename.split('-')
    D = int(hyp[2])*2
    C = int(hyp[C_index])

    # Load vectors

    with gzip.open(os.path.join(AUX_DIR, input_dir, filename+'.pkl.gz'), 'rb') as f:
        ent = pickle.load(f)

    # Force cardinality
    ent /= (ent.sum(1)/C).reshape((-1, 1))
    np.clip(ent, 0, 1, ent)

    ### Link weights

    # Sum over tuples

    with open(os.path.join(AUX_DIR, '{}-{}-count_pair.pkl'.format(*hyp[:2])), 'rb') as f:
        pairs = pickle.load(f)

    print(len(pairs[0])+len(pairs[1]), "pairs in total")

    link_total = np.zeros((2, D, D))  # Store sum of outer products
    n_total = np.zeros(2)  # Store number of observations

    # Add connections from each tuple
    for label, label_pairs in enumerate(pairs):
        for (verb, noun), n in label_pairs.items():
            link_total[label] += n * np.outer(ent[verb], ent[noun])
            n_total[label] += n

    # Normalise to frequencies
    link_freq = link_total / n_total.reshape((-1, 1, 1))

    # Save all parameters to file

    with gzip.open(os.path.join(AUX_DIR, output_dir, filename+'-raw.pkl.gz'), 'wb') as f:
        pickle.dump(link_freq, f)

if __name__ == "__main__":
    # Command line options
    import argparse
    parser = argparse.ArgumentParser(description="Fit link weights")
    parser.add_argument('filename')
    args = parser.parse_args()

    observe_links(args.filename)<commit_msg>Offset when accumulating links, and use multiprocessing<commit_after>import os, pickle, gzip, numpy as np
from itertools import islice
from multiprocessing import Pool

from __config__.filepath import AUX_DIR

# The following two functions are used by observe_links
def get_work_fn(D, ent, offset):
    "Define a work function in each worker process"
    global work
    def work(data):
        "Observe a set of linked pairs"
        link_subtotal = np.zeros((D,D))
        n_subtotal = 0
        for (verb, noun), n in data:
            link_subtotal += n * (np.outer(ent[verb], ent[noun]) - offset).clip(0)
            n_subtotal += n
        return link_subtotal, n_subtotal

def do_work(data):
    "Use the work function that was initialised"
    return work(data)

def observe_links(filename, offset=0., input_dir='meanfield_all', output_dir='meanfield_link', C_index=9, chunk_size=100, processes=32):
    """
    Observe connections between meanfield entities, and save observed frequencies to file
    :param filename: filename without file extension
    :param input_dir: directory of meanfield vectors
    :param output_dir: directory to save observed link frequencies
    :param C_index: index of cardinality in filename parameters
    """
    # Parameters

    hyp = filename.split('-')
    D = int(hyp[2])*2
    C = int(hyp[C_index])

    # Load vectors

    with gzip.open(os.path.join(AUX_DIR, input_dir, filename+'.pkl.gz'), 'rb') as f:
        ent = pickle.load(f)

    # Force cardinality
    ent /= (ent.sum(1)/C).reshape((-1, 1))
    np.clip(ent, 0, 1, ent)

    ### Link weights

    # Sum over tuples

    with open(os.path.join(AUX_DIR, '{}-{}-count_pair.pkl'.format(*hyp[:2])), 'rb') as f:
        pairs = pickle.load(f)

    print(len(pairs[0])+len(pairs[1]), "pairs in total")

    link_total = np.zeros((2, D, D))  # Store sum of outer products
    n_total = np.zeros(2)  # Store number of observations

    # Multiprocessing to process tuples
    # Chunk pairs
    def chunk(data):
        "Chunk a dictionary into lists of items"
        it = iter(data)
        for _ in range(0, len(data), chunk_size):
            yield [(x, data[x]) for x in islice(it, chunk_size)]
    # Spawn workers
    for label, label_pairs in enumerate(pairs):
        with Pool(processes, get_work_fn, (D, ent, offset)) as p:
            for link_subtotal, n_subtotal in p.imap_unordered(do_work, chunk(label_pairs)):
                link_total[label] += link_subtotal
                n_total[label] += n_subtotal

    # Normalise to frequencies
    link_freq = link_total / n_total.reshape((-1, 1, 1))

    # Save all parameters to file

    fullname = filename + str(offset).replace('.','_').replace('-','~')
    with gzip.open(os.path.join(AUX_DIR, output_dir, fullname+'-raw.pkl.gz'), 'wb') as f:
        pickle.dump(link_freq, f)

if __name__ == "__main__":
    # Command line options
    import argparse
    parser = argparse.ArgumentParser(description="Fit link weights")
    parser.add_argument('filename')
    parser.add_argument('offset', type=float, default=0.)
    args = parser.parse_args()

    observe_links(args.filename, args.offset, output_dir='meanfield_link_offset')
<|endoftext|>


<commit_before>import os as _os
import dash as _dash
import sys as _sys
from .version import __version__

_current_path = _os.path.dirname(_os.path.abspath(__file__))

_components = _dash.development.component_loader.load_components(
    _os.path.join(_current_path, 'metadata.json'),
    'dash_core_components'
)

_this_module = _sys.modules[__name__]

_js_dist = [
    {
        'external_url': 'https://cdn.plot.ly/plotly-1.29.3.min.js',
        'relative_package_path': 'plotly-1.29.3.min.js',
        'namespace': 'dash_core_components'
    },
    {
        "relative_package_path": "bundle.js",
        "external_url": (
            "https://unpkg.com/dash-core-components@{}"
            "/dash_core_components/bundle.js"
        ).format(__version__),
        "namespace": "dash_core_components"
    }
]

_css_dist = [
    {
        "relative_package_path": [
            "rc-slider@6.1.2.css",
            "react-select@1.0.0-rc.3.min.css",
            "react-virtualized@9.9.0.css",
            "react-virtualized-select@3.1.0.css",
            "react-dates@12.3.0.css"
        ],
        "external_url": [
            "https://unpkg.com/react-select@1.0.0-rc.3/dist/react-select.min.css",
            "https://unpkg.com/react-virtualized@9.9.0/styles.css",
            "https://unpkg.com/react-virtualized-select@3.1.0/styles.css",
            "https://unpkg.com/rc-slider@6.1.2/assets/index.css",
            "https://unpkg.com/dash-core-components@{}/dash_core_components/react-dates@12.3.0.css".format(__version__)
        ],
        "namespace": "dash_core_components"
    }
]

for component in _components:
    setattr(_this_module, component.__name__, component)
    setattr(component, '_js_dist', _js_dist)
    setattr(component, '_css_dist', _css_dist)
<commit_msg>swap out version numbers<commit_after>import os as _os
import dash as _dash
import sys as _sys
from .version import __version__

_current_path = _os.path.dirname(_os.path.abspath(__file__))

_components = _dash.development.component_loader.load_components(
    _os.path.join(_current_path, 'metadata.json'),
    'dash_core_components'
)

_this_module = _sys.modules[__name__]

_js_dist = [
    {
        'external_url': 'https://cdn.plot.ly/plotly-1.31.0.min.js',
        'relative_package_path': 'plotly-1.31.0.min.js',
        'namespace': 'dash_core_components'
    },
    {
        "relative_package_path": "bundle.js",
        "external_url": (
            "https://unpkg.com/dash-core-components@{}"
            "/dash_core_components/bundle.js"
        ).format(__version__),
        "namespace": "dash_core_components"
    }
]

_css_dist = [
    {
        "relative_package_path": [
            "rc-slider@6.1.2.css",
            "react-select@1.0.0-rc.3.min.css",
            "react-virtualized@9.9.0.css",
            "react-virtualized-select@3.1.0.css",
            "react-dates@12.3.0.css"
        ],
        "external_url": [
            "https://unpkg.com/react-select@1.0.0-rc.3/dist/react-select.min.css",
            "https://unpkg.com/react-virtualized@9.9.0/styles.css",
            "https://unpkg.com/react-virtualized-select@3.1.0/styles.css",
            "https://unpkg.com/rc-slider@6.1.2/assets/index.css",
            "https://unpkg.com/dash-core-components@{}/dash_core_components/react-dates@12.3.0.css".format(__version__)
        ],
        "namespace": "dash_core_components"
    }
]

for component in _components:
    setattr(_this_module, component.__name__, component)
    setattr(component, '_js_dist', _js_dist)
    setattr(component, '_css_dist', _css_dist)
<|endoftext|>