<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (C) 2011 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com>
#
# This program 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Plugins app consists of core elements such as Plugin class or load_plugins()
function, and set of tools that lets us extend Network Administrator: widgets,
actions and custom options. Below you will find the tutorial that leads
through the process of creating a plugin.

The basic guide for creating a Network Administrator plugin
===========================================================

Here we present you a comprehensive guide to writing plugins for
Network Administrator. Developing these extensions is quite simple, however
there are two requirements you should meet to write them freely:

    * at least basic Python programming skills,
    * basic knowledge of Django template language.

If you don't feel confident about your skills, go to Network Administrator
source and look into the 'installed_plugins' directory, where you will
find code of some plugins that already work. Now let's get to work.

Before you start
----------------

On the very beggining, please go to your project's root directory and
find subdirectory called "installed_plugins"--this is the place where all
plugins live. Don't worry if you can't find it--you can create it any time.
Every package placed there will be recognized as a plugin under one condition:
it has to contain a module called "main.py". Any other file which you are going
to use should be placed in this package to maintain the code clean and
well-organized.

After creating a package with main.py inside, simply edit this file.
At first you should create there a subclass of the Plugin (you will find it
in netadmin.plugins). This subclass will be a starting point for all plugin's features.

Subclassing Plugin class
------------------------

Create a class deriving from the Plugin and define fields "name", "description"
and "author" to provide users with more detailed data about your plugin.
Here is a short example:

    from netadmin.plugins import Plugin

    class MyPlugin(Plugin):
        name = "my first plugin"
        description = "here goes a description of my plugin"
        author = "Me, <me@email.com>"

NOTE: Writing a comprehensive docstring would be a great advantage (it is
possible that in the future these docstrings will be displayed in admin pages).

In fact you can write more than one plugin class. However, if you want a class
to be recognised by Network Administrator, you have to put it on the list
called __plugins__. So lets get back to the example above and define that list:

    __plugins__ = [MyPlugin]

Now, after you created a list with a class object on it, your plugin should be
visible on "Plugins" page, where you can activate it.

Activating and deactivating plugins
-----------------------------------

There are two special methods: activate() and deactivate() which you can override
to run some extra code, respectively when plugin is being activated or deactivated.
These methods don't accept any arguments.

Actions
-------

The basic method of extending Network Administrator is defining actions
that will be called in specific places of templates. Almost every action is
connected with an object which can be modified before rendering. If such an
object exists you can change it or event replace it with another one
(the second solution is not recommended).

To define actions, you have to create method called actions() that have to
return a list of 2-element tuples, where the first element is action's name
and the second one is callback function:

    class MyPlugin(Plugin):

        ...

        def actions(self):
            return [
                ('host_detail_name', lambda hostname: hostname.upper()),
                ('event_detail_event_type', self.display_event_type)
            ]

        def display_event_type(self, event_type):
            return "%s (alert level %i)" % \
                (event_type.name, event_type.alert_level)

The best way to find an action you are looking for is to look into the Network
Administrator templates--the string placed next to "action" tag is action's
name.

Custom options
--------------

Custom options is a simple mechanism that lets you store additional
data for your plugins and widgets. It is based on a set of functions for
getting and setting options, so you don't have to touch the database directly.
You will find all available functions in netadmin.plugins.options module and
below we present only the most important of them.

set_option (name, value, user=None)
    Sets value of an option. If option with given name does not exists, it is
    created.

get_option (name, default, user=None)
    Returns value of an option. If option with given name does not exists, it is
    created and its value is set to default.

It is possible to set option only for a single user--you just have to pass
User instance as a third parameter. When you set option without
passing user object, we call it "global option". Here is a short example:

    >>> host = get_host(id)
    >>> # Accessing option that doesn't exist
    ... a = get_option('A', default='not found', user=host.user)
    >>> print a # option has been created and set to default
    not found
    >>> # Now let's set another option called 'B' and get its value
    >>> set_option('B', 'here goes value', user=host.user)
    >>> b = get_option('B', default='not found', user=host.user)
    >>> print b # option already exists so default value was ignored
    here goes value
    >>> # what happens when we try to access option 'B' without passing a user:
    ... b = get_option('B', default='not found')
    >>> print b
    not found
    >>> # Setting a global option
    ... set_option('C', 123)
    >>> # what happens when we try to access global option 'C' with given user instance:
    ... c = get_option('C', default='not found', user=host.user)
    >>> print c # option 'C' doesn't exist for specified user
    not found

NOTE: In fact every option is stored as a string--its value is converted to string
using str() function. Therefore, what you get using get_option() method is always
a string.

Note on naming
--------------

Generally there are no restrictions in naming custom options. However, we strongly
recommend the following scheme:

    <plugin_or_widget_name>_<option_name>

where both names are written in lowercase and words are separated with a single
underscore. This simple convention prevents the use of the same option name by
different plugins.

Plugin settings page
--------------------

The best plugin is the one that is highly flexible. Therefore you may want to
create a settings page for your plugin. You do this by overriding options()
method. It should return a dictionary where every key-value pair describes
one option and its parameters. Look at the example below:

    class MyPlugin(Plugin):
        ...

        def options(self):
            return {
                'my_plugin_email': {
                    'label': 'Your e-mail address',
                    'type': 'string',
                    'default': ''
                },
                'my_plugin_notify': {
                    'label': 'Send notifications every',
                    'choices': [(1, 'Day'), (7, 'Week')]
                }
            }

Here is the list of available parameters with which you can describe option:

    * label -- a label representing the option
    * type -- a string defining type of option, default: 'string';
      this parameter is omitted if you provide a 'choices' value
    * choices (optional) -- list of choices for this option in
      a Django-style format (https://docs.djangoproject.com/en/dev/ref/models/fields/#field-choices)
    * default (optional) -- default value for this option
    * return_func (optional)-- a function that will be used to convert option's stored value
      from string to any other object; this function have to accept only one
      argument which is a value fetched from database

You can choose option's type from the list below:

    * string (default) -- a string, represented by text input
    * integer -- an integer number, represented by text input
    * bool -- a boolean value, represented by True-False select box

Accessing options inside plugin
-------------------------------

The other way you can access defined options is using get_option() method.
The only thing that differs this method from get_option() function is that
the method uses 'return_func' parameter to convert stored value.
This short example should explain everything:

    class MyPlugin(Plugin):
        ...

        def options(self):
            return {
                'my_plugin_age': {
                    'label': 'Your age',
                    'type': 'integer',
                    'default': '123',
                    'return_func': lambda value: int(value)
                }
            }

    >>> set_option('my_plugin_age', 123)
    >>> plugin = MyPlugin()
    >>> plugin.get_option('my_plugin_age')
    123
    >>> get_option('my_plugin_age', '')
    '123'

Widgets
-------

Developing widgets is pretty like writing plugins. You should start with
writing a class deriving from Widget. It have to override the following
fields: 'name', 'description' and 'template_name'. The first one is a name
for your widget, the second is a description and it depends on you what
user will find there, the last is a name of template file which will be used
to render the widget.

The second step is writing get_title() method. It should return string that
will be displayed on widget's title bar.

Finally, you have to override the context() method. It accepts one argument
called 'widget' which is an instance of widget settings object. You can use
this object, for example, to access user who ownes the widget (for more
details see: netadmin.plugins.models.WidgetSettings documentation). The method
should return a dictionary with context variables. You will be able to use
these variables in widget template. Here is a short example:

    class MyWidget(Widget):
        name = "My first widget"
        description = "This is my first widget"

        template_name = "my_widget.html"

        def get_title(self):
            return "Host list"

        def context(self, widget):
            user = widget.widgets_area.user
            hosts = get_hosts(user=user)
            return {
                'hosts': hosts[:5]
            }

Writing widget template
-----------------------

After you created widget class, it's time to write a template. Everything you
should know about creating templates was written on this page:

https://docs.djangoproject.com/en/dev/topics/templates/

In your template you can use context variables returned by context() method
and request object passed from a template in which the widget is being rendered.
This is how template "my_widget.html" might look like:

{{ request.user.username }}'s hosts

    {% for host in hosts %}

{{ host.name }}, {{ host.ipv4 }}, {{ host.ipv6 }}
    {% endfor %}

Widgets and options
-------------------

Both options() and get_option() methods works the same way like in plugins.
The only difference is additional argument 'widget' which is described above.

Shortcut functions
------------------

You probably noticed that we used in this tutorial several functions like
get_host() or get_hosts(). These are so called 'shortcut functions'. They
were created so you don't have to code or even know how to perform database
queries. There is a whole set of useful functions for getting hosts, networks,
events etc. To read more about shortcuts see documentation of netadmin.shortcuts
module.

NOTE: Shortcut functions were made also for backward compatibility, so you
don't have to change your plugins every time we update the core of NA.

Summary
-------

If you're looking for more information about how Network Administrator works
or how good plugin should be written, see NA's documentation. You may also
contact with the author or Umit Project team.
"""

from core import Plugin
from widgets import Widget
<commit_msg>Plugin tutorial - a little update<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (C) 2011 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com>
#
# This program 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Plugins app consists of core elements such as Plugin class or load_plugins()
function, and set of tools that lets us extend Network Administrator: widgets,
actions and custom options. Below you will find the tutorial that leads
through the process of creating a plugin.

The basic guide for creating a Network Administrator plugin
===========================================================

Here we present you a comprehensive guide to writing plugins for
Network Administrator. Developing these extensions is quite simple, however
there are two requirements you should meet to write them freely:

    * at least basic Python programming skills,
    * basic knowledge of Django template language.

If you don't feel confident about your skills, go to Network Administrator
source and look into the 'installed_plugins' directory, where you will
find code of some plugins that already work. Now let's get to work.

Before you start
----------------

On the very beggining, please go to your project's root directory and
find subdirectory called "installed_plugins"--this is the place where all
plugins live. Don't worry if you can't find it--you can create it any time.
Every package placed there will be recognized as a plugin under one condition:
it has to contain a module called "main.py". Any other file which you are going
to use should be placed in this package to maintain the code clean and
well-organized.

After creating a package with main.py inside, simply edit this file.
At first you should create there a subclass of the Plugin (you will find it
in netadmin.plugins). This subclass will be a starting point for all plugin's features.

Subclassing Plugin class
------------------------

Create a class deriving from the Plugin and define fields "name", "description"
and "author" to provide users with more detailed data about your plugin.
Here is a short example:

    from netadmin.plugins import Plugin

    class MyPlugin(Plugin):
        name = "my first plugin"
        description = "here goes a description of my plugin"
        author = "Me, <me@email.com>"

NOTE: Writing a comprehensive docstring would be a great advantage (it is
possible that in the future these docstrings will be displayed in admin pages).

In fact you can write more than one plugin class. However, if you want a class
to be recognised by Network Administrator, you have to put it on the list
called __plugins__. So lets get back to the example above and define that list:

    __plugins__ = [MyPlugin]

Now, after you created a list with a class object on it, your plugin should be
visible on "Plugins" page, where you can activate it.

Activating and deactivating plugins
-----------------------------------

There are two special methods: activate() and deactivate() which you can override
to run some extra code, respectively when plugin is being activated or deactivated.
These methods don't accept any arguments.

Actions
-------

The basic method of extending Network Administrator is defining actions
that will be called in specific places of templates. Almost every action is
connected with an object which can be modified before rendering. If such an
object exists you can change it or event replace it with another one
(the second solution is not recommended).

To define actions, you have to create method called actions() that have to
return a list of 2-element tuples, where the first element is action's name
and the second one is callback function:

    class MyPlugin(Plugin):

        ...

        def actions(self):
            return [
                ('host_detail_name', lambda hostname: hostname.upper()),
                ('event_detail_event_type', self.display_event_type)
            ]

        def display_event_type(self, event_type):
            return "%s (alert level %i)" % \
                (event_type.name, event_type.alert_level)

The best way to find an action you are looking for is to look into the Network
Administrator templates--the string placed next to "action" tag is action's
name.

Custom options
--------------

Custom options is a simple mechanism that lets you store additional
data for your plugins and widgets. It is based on a set of functions for
getting and setting options, so you don't have to touch the database directly.
You will find all available functions in netadmin.plugins.options module and
below we present only the most important of them.

set_option (name, value, user=None)
    Sets value of an option. If option with given name does not exists, it is
    created.

get_option (name, default, user=None)
    Returns value of an option. If option with given name does not exists, it is
    created and its value is set to default.

It is possible to set option only for a single user--you just have to pass
User instance as a third parameter. When you set option without
passing user object, we call it "global option". Here is a short example:

    >>> host = get_host(id)
    >>> # Accessing option that doesn't exist
    ... a = get_option('A', default='not found', user=host.user)
    >>> print a # option has been created and set to default
    not found
    >>> # Now let's set another option called 'B' and get its value
    >>> set_option('B', 'here goes value', user=host.user)
    >>> b = get_option('B', default='not found', user=host.user)
    >>> print b # option already exists so default value was ignored
    here goes value
    >>> # what happens when we try to access option 'B' without passing a user:
    ... b = get_option('B', default='not found')
    >>> print b
    not found
    >>> # Setting a global option
    ... set_option('C', 123)
    >>> # what happens when we try to access global option 'C' with given user instance:
    ... c = get_option('C', default='not found', user=host.user)
    >>> print c # option 'C' doesn't exist for specified user
    not found

NOTE: In fact every option is stored as a string--its value is converted to string
using str() function. Therefore, what you get using get_option() method is always
a string.

Note on naming
--------------

Generally there are no restrictions in naming custom options. However, we strongly
recommend the following scheme:

    <plugin_or_widget_name>_<option_name>

where both names are written in lowercase and words are separated with a single
underscore. This simple convention prevents the use of the same option name by
different plugins.

Plugin settings page
--------------------

The best plugin is the one that is highly flexible. Therefore you may want to
create a settings page for your plugin. You do this by overriding options()
method. It should return a dictionary where every key-value pair describes
one option and its parameters. Look at the example below:

    class MyPlugin(Plugin):
        ...

        def options(self):
            return {
                'my_plugin_email': {
                    'label': 'Your e-mail address',
                    'type': 'string',
                    'default': ''
                },
                'my_plugin_notify': {
                    'label': 'Send notifications every',
                    'choices': [(1, 'Day'), (7, 'Week')]
                }
            }

Here is the list of available parameters with which you can describe option:

    * label -- a label representing the option
    * type -- a string defining type of option, default: 'string';
      this parameter is omitted if you provide a 'choices' value
    * choices (optional) -- list of choices for this option in
      a Django-style format (https://docs.djangoproject.com/en/dev/ref/models/fields/#field-choices)
    * default (optional) -- default value for this option
    * return_func (optional)-- a function that will be used to convert option's stored value
      from string to any other object; this function have to accept only one
      argument which is a value fetched from database

You can choose option's type from the list below:

    * string (default) -- a string, represented by text input
    * integer -- an integer number, represented by text input
    * bool -- a boolean value, represented by True-False select box

Accessing options inside plugin
-------------------------------

The other way you can access defined options is using get_option() method.
The only thing that differs this method from get_option() function is that
the method uses 'return_func' parameter to convert stored value.
This short example should explain everything:

    class MyPlugin(Plugin):
        ...

        def options(self):
            return {
                'my_plugin_age': {
                    'label': 'Your age',
                    'type': 'integer',
                    'default': '123',
                    'return_func': lambda value: int(value)
                }
            }

    >>> set_option('my_plugin_age', 123)
    >>> plugin = MyPlugin()
    >>> plugin.get_option('my_plugin_age')
    123
    >>> get_option('my_plugin_age', '')
    '123'

Widgets
-------

Developing widgets is pretty like writing plugins. You should start with
writing a class deriving from Widget. It have to override the following
fields: 'name', 'description' and 'template_name'. The first one is a name
for your widget, the second is a description and it depends on you what
user will find there, the last is a name of template file which will be used
to render the widget.

The second step is writing get_title() method. It should return string that
will be displayed on widget's title bar.

Finally, you have to override the context() method. It accepts one argument
called 'widget' which is an instance of widget settings object. You can use
this object, for example, to access user who ownes the widget (for more
details see: netadmin.plugins.models.WidgetSettings documentation). The method
should return a dictionary with context variables. You will be able to use
these variables in widget template. Here is a short example:

    class MyWidget(Widget):
        name = "My first widget"
        description = "This is my first widget"

        template_name = "my_widget.html"

        def get_title(self):
            return "Host list"

        def context(self, widget):
            user = widget.widgets_area.user
            hosts = get_hosts(user=user)
            return {
                'hosts': hosts[:5]
            }

Writing widget template
-----------------------

After you created widget class, it's time to write a template. Everything you
should know about creating templates was written on this page:

https://docs.djangoproject.com/en/dev/topics/templates/

In your template you can use context variables returned by context() method
and request object passed from a template in which the widget is being rendered.
This is how template "my_widget.html" might look like:

{{ request.user.username }}'s hosts

    {% for host in hosts %}

{{ host.name }}, {{ host.ipv4 }}, {{ host.ipv6 }}
    {% endfor %}

Widgets and options
-------------------

Both options() and get_option() methods works the same way like in plugins.
The only difference is additional argument 'widget' which is described above.

Shortcut functions
------------------

You probably noticed that we used in this tutorial several functions like
get_host() or get_hosts(). These are so called 'shortcut functions'. They
were created so you don't have to code or even know how to perform database
queries. There is a whole set of useful functions for getting hosts, networks,
events etc. To read more about shortcuts see documentation of netadmin.shortcuts
module.

NOTE: Shortcut functions were made also for backward compatibility, so you
don't have to change your plugins every time we update the core of NA.

Summary
-------

If you're looking for more information about how Network Administrator works
or how good plugin should be written, see NA's source and documentation.
You may also contact with the author or Umit Project team.
"""

from core import Plugin
from widgets import Widget
<|endoftext|>


<commit_before>from discord.ext import commands
import discord
from cogs.utils import checks
import aiohttp
import asyncio
import pickle

class Twitch:

    def __init__(self, bot):
        self.bot = bot
        self.session = aiohttp.ClientSession(loop=bot.loop)

    def __unload(self):
        self.session.close()

    def read(self):
        with open('cogs/twitch/livestreams.txt', 'rb') as f:
            return pickle.load(f)

    def write(self, livestreams):
        with open('cogs/twitch/livestreams.txt', 'wb') as f:
            pickle.dump(livestreams, f)

    @commands.command()
    @checks.is_owner()
    async def disablealerts(self):
        try:
            self.task.cancel()
            await self.bot.say('Twitch alerts have been disabled.')
        except AttributeError:
            await self.bot.say('Twitch alerts are already disabled.')

    @commands.command()
    @checks.is_owner()
    async def enablealerts(self):
        try:
            self.task.cancel()
            self.task = self.bot.loop.create_task(self.check_streamers())
            await self.bot.say('Twitch alerts are already enabled.')
        except AttributeError:
            self.task = self.bot.loop.create_task(self.check_streamers())
            await self.bot.say('Twitch alerts have been enabled.')

    @commands.command()
    async def removetwitch(self, message: str):
        livestreams = self.read()
        if message.lower() in livestreams:
            livestreams.pop(message, 0)
            self.write(livestreams)
            await self.bot.say(message + ' has been removed from the notify list.')
        else:
            await self.bot.say(message + ' is not on the notify list.')

    @commands.command()
    async def addtwitch(self, message: str):
        livestreams = self.read()
        if message in livestreams:
            await self.bot.say(message + ' is already on the notify list.')
        else:
            livestreams[message.lower()] = 'offline'
            self.write(livestreams)
            await self.bot.say(message + ' has been added to the notify list.')

    @commands.command()
    async def listtwitch(self):
        livestreams = self.read()
        string_list = '\n'.join(livestreams.keys())
        number = str(len(livestreams.keys()))
        await self.bot.say(string_list)

    async def notify_live(self, streamer):
        url = 'https://api.twitch.tv/kraken/streams/' + streamer + '?client_id=' + self.bot.TWITCH_CLIENT_ID
        async with self.session.get(url) as r:
            channel = self.bot.get_channel(self.bot.TWITCH_ALERT_CHANNEL)
            link = 'https://twitch.tv/' + streamer
            msg = streamer + ' has gone live!'
            js = await r.json()
            livestreams = self.read()
            if js['stream'] and (livestreams[streamer] == 'offline'):
                livestreams[streamer] = 'online'
                self.write(livestreams)
                await self.bot.send_message(channel, msg)
                await self.bot.send_message(channel, link)
            elif js['stream'] is None and (livestreams[streamer] == 'online'):
                livestreams[streamer] = 'offline'
                self.write(livestreams)
            else:
                return

    async def check_streamers(self):
        await self.bot.wait_until_ready()
        await asyncio.sleep(5)
        while not self.bot.is_closed:
            livestreams = self.read()
            for key in livestreams.keys():
              await self.notify_live(key)
            await asyncio.sleep(45)

def setup(bot):
    bot.add_cog(Twitch(bot))
<commit_msg>cleaned up listtwitch look<commit_after>from discord.ext import commands
import discord
from cogs.utils import checks
import aiohttp
import asyncio
import pickle

class Twitch:

    def __init__(self, bot):
        self.bot = bot
        self.session = aiohttp.ClientSession(loop=bot.loop)

    def __unload(self):
        self.session.close()

    def read(self):
        with open('cogs/twitch/livestreams.txt', 'rb') as f:
            return pickle.load(f)

    def write(self, livestreams):
        with open('cogs/twitch/livestreams.txt', 'wb') as f:
            pickle.dump(livestreams, f)

    @commands.command()
    @checks.is_owner()
    async def disablealerts(self):
        try:
            self.task.cancel()
            await self.bot.say('Twitch alerts have been disabled.')
        except AttributeError:
            await self.bot.say('Twitch alerts are already disabled.')

    @commands.command()
    @checks.is_owner()
    async def enablealerts(self):
        try:
            self.task.cancel()
            self.task = self.bot.loop.create_task(self.check_streamers())
            await self.bot.say('Twitch alerts are already enabled.')
        except AttributeError:
            self.task = self.bot.loop.create_task(self.check_streamers())
            await self.bot.say('Twitch alerts have been enabled.')

    @commands.command()
    async def removetwitch(self, message: str):
        livestreams = self.read()
        if message.lower() in livestreams:
            livestreams.pop(message, 0)
            self.write(livestreams)
            await self.bot.say(message + ' has been removed from the notify list.')
        else:
            await self.bot.say(message + ' is not on the notify list.')

    @commands.command()
    async def addtwitch(self, message: str):
        livestreams = self.read()
        if message in livestreams:
            await self.bot.say(message + ' is already on the notify list.')
        else:
            livestreams[message.lower()] = 'offline'
            self.write(livestreams)
            await self.bot.say(message + ' has been added to the notify list.')

    @commands.command()
    async def listtwitch(self):
        livestreams = self.read()
        string_list = '\n'.join(livestreams.keys())
        number = str(len(livestreams.keys()))
        embed = discord.Embed(colour=0x8080ff, title='__Streams__', description=string_list)
        await self.bot.say(embed=embed)

    async def notify_live(self, streamer):
        url = 'https://api.twitch.tv/kraken/streams/' + streamer + '?client_id=' + self.bot.TWITCH_CLIENT_ID
        async with self.session.get(url) as r:
            channel = self.bot.get_channel(self.bot.TWITCH_ALERT_CHANNEL)
            link = 'https://twitch.tv/' + streamer
            msg = streamer + ' has gone live!'
            js = await r.json()
            livestreams = self.read()
            if js['stream'] and (livestreams[streamer] == 'offline'):
                livestreams[streamer] = 'online'
                self.write(livestreams)
                await self.bot.send_message(channel, msg)
                await self.bot.send_message(channel, link)
            elif js['stream'] is None and (livestreams[streamer] == 'online'):
                livestreams[streamer] = 'offline'
                self.write(livestreams)
            else:
                return

    async def check_streamers(self):
        await self.bot.wait_until_ready()
        await asyncio.sleep(5)
        while not self.bot.is_closed:
            livestreams = self.read()
            for key in livestreams.keys():
              await self.notify_live(key)
            await asyncio.sleep(45)

def setup(bot):
    bot.add_cog(Twitch(bot))
<|endoftext|>


<commit_before>from chrome_remote_shell import Shell
import json
from subprocess import Popen

# run google chrome with (hopefully) all user interaction and automatic network requests disabled
chrome_proc = Popen('google-chrome --remote-debugging-port=9876 --no-default-browser-check --user-data-dir=/tmp/chrome-profiling --no-first-run --disable-background-networking --disable-client-side-phishing-detection --disable-component-update --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-logging --ignore-certificate-errors --use-mock-keychain --dbus-stub', shell=True)

# create debugging api client instance
s=Shell(port=9876)

# connect to the debugging api
s.connect(0)

# start receiving Page related events (esp. onLoad event)
s.soc.send(json.dumps({"id":0, "method":"Page.enable"}))

# start receiving Network profiling events
s.soc.send(json.dumps({"id":0, "method":"Network.enable"}))

# clear cache
# unneccessary as we have a clean profile
#### s.soc.send(json.dumps({"id":0, "method":"Network.clearBrowserCache"}))

# navigate to the page we want to profile
s.soc.send(json.dumps({"id":0, "method":"Page.navigate", "params":{"url":"https://www.ugb.de"}}))

method = ""

# receive events until the main Page contents are fully loaded
while method != "Page.frameStoppedLoading":
	r = json.loads(s.soc.recv())
	if not 'method' in r: continue
	method = r['method']
	params = r['params']

	# print some information from the profiling event, there is a lot more
	if 'timestamp' in params:
		print str(params['timestamp']) + ': ',
	print method,
	if 'requestId' in params: print '    '+params['requestId'],
	if 'request' in params and 'url' in params['request']: print '    '+params['request']['url'],
	print ""

	# to dump all params, do this:
	# print(params)

# close websocket connection
s.close()

# tell chrome to close itself
s.close_tab(0)

# wait a little, kill it if it's still open
time.sleep(0.1)
chrome_proc.send_signal(9)

# delete temp folder
check_output(['rm', '-r', '/tmp/chrome-profiling'])

<commit_msg>use new api functions, auto-kill chrome<commit_after>from chrome_remote_shell import Shell
import json
from subprocess import Popen, check_output
import time

# run google chrome with (hopefully) all user interaction and automatic network requests disabled
chrome_proc = Popen('google-chrome --remote-debugging-port=9876 --no-default-browser-check --user-data-dir=/tmp/chrome-profiling --no-first-run --disable-background-networking --disable-client-side-phishing-detection --disable-component-update --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-logging --ignore-certificate-errors --use-mock-keychain --dbus-stub about:blank'.split(' '))

def wait_for_chrome():
	print "Waiting for chrome to be ready ",
	for i in range(100):
		print ".",
		try:
			# create debugging api client instance
			s=Shell(port=9876)
			for i,tab in enumerate(s.tablist):
				if tab['type'] == 'page':
					# connect to the debugging api
					s.connect(i)
					print "connected", tab, i
					return s
		except:
			time.sleep(0.1)
			pass
	raise "No chrome found"
time.sleep(1)
s = wait_for_chrome()
time.sleep(1)

# start receiving Page related events (esp. onLoad event)
s.do("Page.enable")

# start receiving Network profiling events
s.do("Network.enable")

# clear cache
# unneccessary as we have a clean profile
#### s.do("Network.clearBrowserCache")

# navigate to the page we want to profile
s.do("Page.navigate", url="https://www.ugb.de")

method = ""

starttime=99999999
endtime=0

# receive events until the main Page contents are fully loaded
while method != "Page.frameStoppedLoading":
	r = json.loads(s.soc.recv())
	if not 'method' in r: continue
	method = r['method']
	params = r['params']

	# print some information from the profiling event, there is a lot more
	if 'timestamp' in params:
		print str(params['timestamp']) + ': ',
		if params['timestamp'] < starttime: starttime = params['timestamp']
		if params['timestamp'] > endtime: endtime = params['timestamp']
	print method,
	if 'requestId' in params: print '    '+params['requestId'],
	if 'request' in params and 'url' in params['request']: print '    '+params['request']['url'],
	print ""
	if method == 'Network.loadingFailed': print(params)
	# to dump all params, do this:
	# print(params)

print "Page load took "+str(endtime-starttime)+" seconds"

# close websocket connection
s.close()

time.sleep(1)

# tell chrome to close itself
print("calling close_tab")
s.close_tab(0)

# wait a little, kill it if it's still open
time.sleep(1)
print("sending TERM signal")
chrome_proc.send_signal(15)

time.sleep(0.5)
print("sending KILL signal")
chrome_proc.send_signal(9)

# delete temp folder
check_output(['rm', '-r', '/tmp/chrome-profiling'])

<|endoftext|>


<commit_before>"""
Django settings for researchman project.

Generated by 'django-admin startproject' using Django 1.8.2.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1=6nm=0^u46j)j$0#ss_=%k4)m2^&u^mf&jp9^8&zgy0zt6frx'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'researchman.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'researchman.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

#HEROKU
import dj_database_url
DATABASES['default'] = dj_database_url.config()

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
<commit_msg>fixing deploy<commit_after>"""
Django settings for researchman project.

Generated by 'django-admin startproject' using Django 1.8.2.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1=6nm=0^u46j)j$0#ss_=%k4)m2^&u^mf&jp9^8&zgy0zt6frx'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'researchman.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'researchman.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

#HEROKU
import dj_database_url
DATABASES['default'] = dj_database_url.config()

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
#HEROKU
STATIC_ROOT = 'staticfiles'<|endoftext|>


<commit_before>from cloudify import ctx
from cloudify import exceptions as cfy_exc
from cloudify.decorators import operation
from vcloud_plugin_common import with_vca_client, get_vcloud_config
from network_plugin import check_ip, save_gateway_configuration, get_vm_ip, isExternalIpAssigned, getFreeIP, CREATE, DELETE, PUBLIC_IP
from network_plugin.network import VCLOUD_NETWORK_NAME

@operation
@with_vca_client
def net_connect_to_nat(vca_client, **kwargs):
    prepare_network_operation(vca_client, CREATE)

@operation
@with_vca_client
def net_disconnect_from_nat(vca_client, **kwargs):
    prepare_network_operation(vca_client, DELETE)

@operation
@with_vca_client
def server_connect_to_nat(vca_client, **kwargs):
    prepare_vm_operation(vca_client, CREATE)

@operation
@with_vca_client
def server_disconnect_from_nat(vca_client, **kwargs):
    prepare_vm_operation(vca_client, DELETE)

def prepare_network_operation(vca_client, operation):
    try:
        network_name = ctx.source.instance.runtime_properties[VCLOUD_NETWORK_NAME]
        vdc_name = get_vcloud_config()['vdc']
        rule_type = ctx.target.node.properties['rules']['type']
        gateway = vca_client.get_gateway(vdc_name,
                                         ctx.target.node.properties['nat']['edge_gateway'])
        public_ip = _get_public_ip(ctx, gateway, operation)
    except KeyError as e:
        raise cfy_exc.NonRecoverableError("Parameter not found: {0}".format(e))
    ip_ranges = _get_network_ip_range(vca_client, vdc_name, network_name)
    ip_ranges.extend(_get_gateway_ip_range(gateway, network_name))
    nat_network_operation(vca_client, gateway, operation, rule_type, public_ip, ip_ranges, "any", "any", "any")

def prepare_vm_operation(vca_client, operation):
    try:
        vdc_name = get_vcloud_config()['vdc']
        rule_type = ctx.target.node.properties['rules']['type']
        gateway = vca_client.get_gateway(vdc_name,
                                         ctx.target.node.properties['nat']['edge_gateway'])
        public_ip = _get_public_ip(ctx, gateway, operation)
        rule_type = ctx.target.node.properties['rules']['type']
        protocol = ctx.target.node.properties['rules']['protocol'] if 'protocol' in ctx.target.node.properties['rules'] else "any"
        original_port = ctx.target.node.properties['rules']['original_port'] if 'original_port' in ctx.target.node.properties['rules'] else "any"
        translated_port = ctx.target.node.properties['rules']['translated_port'] if 'translated_port' in ctx.target.node.properties['rules'] else "any"
    except KeyError as e:
        raise cfy_exc.NonRecoverableError("Parameter not found: {0}".format(e))
    private_ip = check_ip(get_vm_ip(vca_client, ctx))
    nat_network_operation(vca_client, gateway, operation, rule_type, public_ip, [private_ip], original_port, translated_port, protocol)

def nat_network_operation(vca_client, gateway, operation, rule_type, public_ip, private_ip, original_port, translated_port, protocol):
    ctx.logger.info("Public Ip {0}".format(public_ip))
    function = None
    message = None
    if operation == CREATE:
        if isExternalIpAssigned(public_ip, gateway):
            raise cfy_exc.NonRecoverableError("Public IP {0} is already allocated".format(public_ip))
        function = gateway.add_nat_rule
        message = "Create"
    elif operation == DELETE:
        function = gateway.del_nat_rule
        message = "Delete"
    else:
        raise cfy_exc.NonRecoverableError("Unknown operation: {0}".format(operation))

    for rule in rule_type:
        for ip in private_ip:
            ctx.logger.info("{6} NAT rule: original_ip '{0}',"
                            " translated_ip '{1}', rule type '{2},"
                            " protocol {3}, original_port {4}, translated_port {5}'"
                            .format(ip, public_ip, rule, protocol, original_port, translated_port, message))
            if rule == "SNAT":
                # for SNAT type ports and protocol must by "any", because they are not configurable
                function(
                    rule, ip, "any", public_ip, "any", "any")
            if rule == "DNAT":
                function(
                    rule, public_ip, str(original_port), ip, str(translated_port), protocol)
    save_gateway_configuration(gateway, vca_client, "Could not save edge gateway NAT configuration")
    if operation == CREATE:
        ctx.target.instance.runtime_properties[PUBLIC_IP] = public_ip
    else:
        del ctx.target.instance.runtime_properties[PUBLIC_IP]

def _get_network_ip_range(vca_client, vdc_name, network_name):
    networks = vca_client.get_networks(vdc_name)
    scopes = []
    for scope in [net.Configuration.IpScopes.IpScope for net in networks if network_name == net.get_name()]:
        for ip in scope[0].IpRanges.IpRange:
            scopes.append("{0} - {1}".format(ip.get_StartAddress(), ip.get_EndAddress()))
    return scopes

def _get_gateway_ip_range(gateway, network_name):
    scopes = []
    for pool in gateway.get_dhcp_pools():
        if pool.Network.name == network_name:
            scopes.append("{0} - {1}".format(pool.get_LowIpAddress(), pool.get_HighIpAddress()))
    return scopes

def _get_public_ip(ctx, gateway, operation):
    public_ip = None
    if operation == CREATE:
        if PUBLIC_IP in ctx.target.node.properties['nat']:
            public_ip = check_ip(ctx.target.node.properties['nat'][PUBLIC_IP])
        else:
            public_ip = getFreeIP(gateway)
            ctx.logger.info("Assign external IP {0}".format(public_ip))
    elif operation == DELETE:
        if PUBLIC_IP in ctx.target.instance.runtime_properties:
            public_ip = ctx.target.instance.runtime_properties[PUBLIC_IP]
    if not public_ip:
        raise cfy_exc.NonRecoverableError("Can't get public IP")
    return public_ip
<commit_msg>Refactoring code<commit_after>from cloudify import ctx
from cloudify import exceptions as cfy_exc
from cloudify.decorators import operation
from vcloud_plugin_common import with_vca_client, get_vcloud_config
from network_plugin import check_ip, save_gateway_configuration, get_vm_ip, isExternalIpAssigned, getFreeIP, CREATE, DELETE, PUBLIC_IP
from network_plugin.network import VCLOUD_NETWORK_NAME

@operation
@with_vca_client
def net_connect_to_nat(vca_client, **kwargs):
    prepare_network_operation(vca_client, CREATE)

@operation
@with_vca_client
def net_disconnect_from_nat(vca_client, **kwargs):
    prepare_network_operation(vca_client, DELETE)

@operation
@with_vca_client
def server_connect_to_nat(vca_client, **kwargs):
    prepare_vm_operation(vca_client, CREATE)

@operation
@with_vca_client
def server_disconnect_from_nat(vca_client, **kwargs):
    prepare_vm_operation(vca_client, DELETE)

def prepare_network_operation(vca_client, operation):
    try:
        network_name = ctx.source.instance.runtime_properties[VCLOUD_NETWORK_NAME]
        vdc_name = get_vcloud_config()['vdc']
        rule_type = ctx.target.node.properties['rules']['type']
        gateway = vca_client.get_gateway(vdc_name,
                                         ctx.target.node.properties['nat']['edge_gateway'])
        public_ip = _get_public_ip(ctx, gateway, operation)
    except KeyError as e:
        raise cfy_exc.NonRecoverableError("Parameter not found: {0}".format(e))
    ip_ranges = _get_network_ip_range(vca_client, vdc_name, network_name)
    ip_ranges.extend(_get_gateway_ip_range(gateway, network_name))
    nat_network_operation(vca_client, gateway, operation, rule_type, public_ip, ip_ranges, "any", "any", "any")

def prepare_vm_operation(vca_client, operation):
    try:
        vdc_name = get_vcloud_config()['vdc']
        rule_type = ctx.target.node.properties['rules']['type']
        gateway = vca_client.get_gateway(vdc_name,
                                         ctx.target.node.properties['nat']['edge_gateway'])
        public_ip = _get_public_ip(ctx, gateway, operation)
        rule_type = ctx.target.node.properties['rules']['type']
        protocol = ctx.target.node.properties['rules'].get('protocol', "any")
        original_port = ctx.target.node.properties['rules'].get('original_port', "any")
        translated_port = ctx.target.node.properties['rules'].get('translated_port', "any")
    except KeyError as e:
        raise cfy_exc.NonRecoverableError("Parameter not found: {0}".format(e))
    private_ip = check_ip(get_vm_ip(vca_client, ctx))
    nat_network_operation(vca_client, gateway, operation, rule_type, public_ip, [private_ip], original_port, translated_port, protocol)

def nat_network_operation(vca_client, gateway, operation, rule_type, public_ip, private_ip, original_port, translated_port, protocol):
    ctx.logger.info("Public Ip {0}".format(public_ip))
    function = None
    message = None
    if operation == CREATE:
        if isExternalIpAssigned(public_ip, gateway):
            raise cfy_exc.NonRecoverableError("Public IP {0} is already allocated".format(public_ip))
        function = gateway.add_nat_rule
        message = "Create"
    elif operation == DELETE:
        function = gateway.del_nat_rule
        message = "Delete"
    else:
        raise cfy_exc.NonRecoverableError("Unknown operation: {0}".format(operation))

    for rule in rule_type:
        for ip in private_ip:
            ctx.logger.info("{6} NAT rule: original_ip '{0}',"
                            " translated_ip '{1}', rule type '{2},"
                            " protocol {3}, original_port {4}, translated_port {5}'"
                            .format(ip, public_ip, rule, protocol, original_port, translated_port, message))
            if rule == "SNAT":
                # for SNAT type ports and protocol must by "any", because they are not configurable
                function(
                    rule, ip, "any", public_ip, "any", "any")
            if rule == "DNAT":
                function(
                    rule, public_ip, str(original_port), ip, str(translated_port), protocol)
    save_gateway_configuration(gateway, vca_client, "Could not save edge gateway NAT configuration")
    if operation == CREATE:
        ctx.target.instance.runtime_properties[PUBLIC_IP] = public_ip
    else:
        del ctx.target.instance.runtime_properties[PUBLIC_IP]

def _get_network_ip_range(vca_client, vdc_name, network_name):
    networks = vca_client.get_networks(vdc_name)
    scopes = []
    for scope in [net.Configuration.IpScopes.IpScope for net in networks if network_name == net.get_name()]:
        for ip in scope[0].IpRanges.IpRange:
            scopes.append("{0} - {1}".format(ip.get_StartAddress(), ip.get_EndAddress()))
    return scopes

def _get_gateway_ip_range(gateway, network_name):
    scopes = []
    for pool in gateway.get_dhcp_pools():
        if pool.Network.name == network_name:
            scopes.append("{0} - {1}".format(pool.get_LowIpAddress(), pool.get_HighIpAddress()))
    return scopes

def _get_public_ip(ctx, gateway, operation):
    public_ip = None
    if operation == CREATE:
        if PUBLIC_IP in ctx.target.node.properties['nat']:
            public_ip = check_ip(ctx.target.node.properties['nat'][PUBLIC_IP])
        else:
            public_ip = getFreeIP(gateway)
            ctx.logger.info("Assign external IP {0}".format(public_ip))
    elif operation == DELETE:
        if PUBLIC_IP in ctx.target.instance.runtime_properties:
            public_ip = ctx.target.instance.runtime_properties[PUBLIC_IP]
    if not public_ip:
        raise cfy_exc.NonRecoverableError("Can't get public IP")
    return public_ip
<|endoftext|>


<commit_before>from django.db.models.signals import post_save
from django.dispatch import receiver

from resolwe.flow.models import Data
from resolwe.flow.managers import manager

@receiver(post_save, sender=Data)
def manager_post_save_handler(sender, instance, **kwargs):
    if instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR:
        manager.communicate()
<commit_msg>Set verbosity to 0 in signals<commit_after>from django.db.models.signals import post_save
from django.dispatch import receiver

from resolwe.flow.models import Data
from resolwe.flow.managers import manager

@receiver(post_save, sender=Data)
def manager_post_save_handler(sender, instance, **kwargs):
    if instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR:
        manager.communicate(verbosity=0)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from pygame import gfxdraw
import platform

from .core import *
from .write import *
from .image import *

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def line(left_x=-5, left_y=0, right_x=5, right_y=0, line_color="black", thickness=1):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    """
    left_x = Coordinates.to_pygame(x = left_x)
    left_y = Coordinates.to_pygame(y = left_y)
    right_x = Coordinates.to_pygame(x = right_x)
    right_y = Coordinates.to_pygame(y = right_y)

    if left_x == right_x or left_y == right_y:
        pygame.draw.line(screen, color(line_color), (left_x, left_y), (right_x, right_y), thickness)
    else:
        pygame.draw.aaline(screen, color(line_color), (left_x, left_y), (right_x,right_y), thickness)

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def rectangle(x=0, y=0, width=10, height=10, line_color="black", thickness=1, fill_color=None, opacity=225):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    """
    left = Coordinates.to_pygame(x= (x - width / 2))
    top = Coordinates.to_pygame(y= (y + height /2))
    width = Coordinates.to_pygame(distance_x = width)
    height = Coordinates.to_pygame(distance_y = -height)

    if fill_color != None:
        pygame.draw.rect(screen, color(fill_color),(left,top,width,height),0)
    if thickness != 0:
        pygame.draw.rect(screen, color(line_color),(left,top,width,height),thickness)

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def circle(x=0, y=0, size=10, line_color="black", thickness=0, fill_color="white", opacity=225):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    """
    x = Coordinates.to_pygame(x=x)
    y = Coordinates.to_pygame(y=y)
    radius = Coordinates.to_pygame(distance_x = size/2)
    thickness_radius = Coordinates.to_pygame(distance_x = (size-thickness)/2)

    if fill_color == None:
        pygame.gfxdraw.aacircle(screen, x, y, radius, color(line_color))
    else:
        if thickness == None:
            pygame.gfxdraw.filled_circle(screen, x, y, radius, color(fill_color))
        elif thickness == 0:
            pygame.gfxdraw.filled_circle(screen, x, y, radius, color(fill_color))
            pygame.gfxdraw.aacircle(screen, x, y, radius, color(line_color))
        else:
            pygame.gfxdraw.filled_circle(screen, x, y, radius, color(line_color))
            pygame.gfxdraw.aacircle(screen, x, y, radius, color(line_color))
            pygame.gfxdraw.filled_circle(screen, x, y, thickness_radius, color(fill_color))#
            pygame.gfxdraw.aacircle(screen, x, y, thickness_radius, color(fill_color))

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def countdown(style="circle", duration=3000, width=5, reverse=False, background="white", write_seconds=True, write_color="white", write_outline="black", color_fade=False, color_start="red", color_end="green", sound=False, melody=[1000, 1500]):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    - time
    - winsound
    """
    if sound is True:
        import winsound

    original_width=width
    duration_frames = int(duration/(1000/60))

    if reverse == False:
        width=0.6
        width_per_frame = (original_width-width)/duration_frames
    else:
        width_per_frame = original_width/duration_frames

    t0 = builtin_time.clock()
    red, green, blue = color(color_start)

    for i in range(duration_frames):
        time.control(60)
        fill_color = tuple([red,green,blue])
        if style == "rectangle":
            rectangle(fill_color=background, width=original_width, height=original_width, thickness=2)
            rectangle(fill_color=fill_color, width=width, height=width)

        if style == "circle":
            circle(fill_color=background, size=original_width)
            circle(fill_color=fill_color, size=width)
        if write_seconds==True:
            write("%i" %((duration/1000+1)-(builtin_time.clock()-t0)), size = 2, color=write_color,outline=True, outline_color=write_outline)
        refresh()
        if reverse==False:
            width += width_per_frame
        else:
            width -= width_per_frame
        if color_fade==True:
            if color_end == "green":
                if red > 0:
                    red -= int(255/duration_frames)
                if green < 255:
                    green += int(255/duration_frames)

    if sound is True:
        for i in melody:
            winsound.Beep(i, 25)
#            time.wait(50)

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def start_screen(name="test", path="./Logo/", authors="", language="en"):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    - time
    - winsound
    """
    newpage("white", auto_refresh=False)

    # Logo
    try:
        image(path+name, y=2, size=5)
    except:
        write(name, style="bold", y=2, size=5)

    # Authors
    write(authors, style='light', y=-1.75, size=0.6)

    # End
    if language == "fr" or language == "french":
        write('Appuyez sur ENTRER pour commencer.', style='end')
    else:
        write('Press ENTER to start.', style='end')

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def end_screen(name="test", success=True, path="./Logo/", authors="", language="en"):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    - time
    - winsound
    """
    newpage("white", auto_refresh=False)

    # Logo
    try:
        image(path+name, y=7.5, size=4)
    except:
        write(name, style="bold", y=7.5, size=4)

    # Authors
    write(authors, style='light', y=4.25, size=0.6)

    # End
    if language == "fr" or language == "french":
        if success is True:
            write("Enregistrement des données réussi.", color='green')
        else:
            write("Echec de l'enregistrement des données.", color='red')
        write('Appuyez sur ENTRER pour quitter.', style='end')
    else:
        if success is True:
            write("Successful Data Collection.", color='green')
        else:
            write("Failed Data Collection.", color='red')
        write('Press ENTER to quit.', style='end')

<commit_msg>start_screen and end_screen fix<commit_after># -*- coding: utf-8 -*-
from pygame import gfxdraw
import platform

from .core import *
from .write import *
from .image import *

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def line(left_x=-5, left_y=0, right_x=5, right_y=0, line_color="black", thickness=1):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    """
    left_x = Coordinates.to_pygame(x = left_x)
    left_y = Coordinates.to_pygame(y = left_y)
    right_x = Coordinates.to_pygame(x = right_x)
    right_y = Coordinates.to_pygame(y = right_y)

    if left_x == right_x or left_y == right_y:
        pygame.draw.line(screen, color(line_color), (left_x, left_y), (right_x, right_y), thickness)
    else:
        pygame.draw.aaline(screen, color(line_color), (left_x, left_y), (right_x,right_y), thickness)

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def rectangle(x=0, y=0, width=10, height=10, line_color="black", thickness=1, fill_color=None, opacity=225):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    """
    left = Coordinates.to_pygame(x= (x - width / 2))
    top = Coordinates.to_pygame(y= (y + height /2))
    width = Coordinates.to_pygame(distance_x = width)
    height = Coordinates.to_pygame(distance_y = -height)

    if fill_color != None:
        pygame.draw.rect(screen, color(fill_color),(left,top,width,height),0)
    if thickness != 0:
        pygame.draw.rect(screen, color(line_color),(left,top,width,height),thickness)

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def circle(x=0, y=0, size=10, line_color="black", thickness=0, fill_color="white", opacity=225):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    """
    x = Coordinates.to_pygame(x=x)
    y = Coordinates.to_pygame(y=y)
    radius = Coordinates.to_pygame(distance_x = size/2)
    thickness_radius = Coordinates.to_pygame(distance_x = (size-thickness)/2)

    if fill_color == None:
        pygame.gfxdraw.aacircle(screen, x, y, radius, color(line_color))
    else:
        if thickness == None:
            pygame.gfxdraw.filled_circle(screen, x, y, radius, color(fill_color))
        elif thickness == 0:
            pygame.gfxdraw.filled_circle(screen, x, y, radius, color(fill_color))
            pygame.gfxdraw.aacircle(screen, x, y, radius, color(line_color))
        else:
            pygame.gfxdraw.filled_circle(screen, x, y, radius, color(line_color))
            pygame.gfxdraw.aacircle(screen, x, y, radius, color(line_color))
            pygame.gfxdraw.filled_circle(screen, x, y, thickness_radius, color(fill_color))#
            pygame.gfxdraw.aacircle(screen, x, y, thickness_radius, color(fill_color))

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def countdown(style="circle", duration=3000, width=5, reverse=False, background="white", write_seconds=True, write_color="white", write_outline="black", color_fade=False, color_start="red", color_end="green", sound=False, melody=[1000, 1500]):
    """
    Help incomplete, sorry.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    - time
    - winsound
    """
    if sound is True:
        import winsound

    original_width=width
    duration_frames = int(duration/(1000/60))

    if reverse == False:
        width=0.6
        width_per_frame = (original_width-width)/duration_frames
    else:
        width_per_frame = original_width/duration_frames

    t0 = builtin_time.clock()
    red, green, blue = color(color_start)

    for i in range(duration_frames):
        time.control(60)
        fill_color = tuple([red,green,blue])
        if style == "rectangle":
            rectangle(fill_color=background, width=original_width, height=original_width, thickness=2)
            rectangle(fill_color=fill_color, width=width, height=width)

        if style == "circle":
            circle(fill_color=background, size=original_width)
            circle(fill_color=fill_color, size=width)
        if write_seconds==True:
            write("%i" %((duration/1000+1)-(builtin_time.clock()-t0)), size = 2, color=write_color,outline=True, outline_color=write_outline)
        refresh()
        if reverse==False:
            width += width_per_frame
        else:
            width -= width_per_frame
        if color_fade==True:
            if color_end == "green":
                if red > 0:
                    red -= int(255/duration_frames)
                if green < 255:
                    green += int(255/duration_frames)

    if sound is True:
        for i in melody:
            winsound.Beep(i, 25)
#            time.wait(50)

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def start_screen(name="test", path="./Logo/", extension=".png", authors="", language="en"):
    """
    Help incomplete, sorry. Expecting a "Logo_" prefix to the image.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    - time
    - winsound
    """
    newpage("white", auto_refresh=False)

    # Logo
    try:
        image(path + "Logo_" + name + extension, y=2, size=5)
    except:
        write(name, style="bold", y=2, size=5)

    # Authors
    write(authors, style='light', y=-1.75, size=0.6)

    # End
    if language == "fr" or language == "french":
        write('Appuyez sur ENTRER pour commencer.', style='end')
    else:
        write('Press ENTER to start.', style='end')

# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
# ==============================================================================
def end_screen(name="test", success=True, path="./Logo/", authors="", language="en"):
    """
    Help incomplete, sorry. Expecting a "Logo_" prefix to the image.

    Parameters
    ----------
    NA

    Returns
    ----------
    NA

    Example
    ----------
    NA

    Authors
    ----------
    Dominique Makowski

    Dependencies
    ----------
    - pygame 1.9.2
    - pygame.gfxfraw
    - time
    - winsound
    """
    newpage("white", auto_refresh=False)

    # Logo
    try:
        image(path + "Logo_" + name + extension, y=7.5, size=4)
    except:
        write(name, style="bold", y=7.5, size=4)

    # Authors
    write(authors, style='light', y=4.25, size=0.6)

    # End
    if language == "fr" or language == "french":
        if success is True:
            write("Enregistrement des données réussi.", color='green')
        else:
            write("Echec de l'enregistrement des données.", color='red')
        write('Appuyez sur ENTRER pour quitter.', style='end')
    else:
        if success is True:
            write("Successful Data Collection.", color='green')
        else:
            write("Failed Data Collection.", color='red')
        write('Press ENTER to quit.', style='end')

<|endoftext|>


<commit_before>#!/usr/bin/env python2.7
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Generates the appropriate build.json data for all the proto files."""
import yaml
import collections
import os
import re
import sys

def update_deps(key, proto_filename, deps, is_trans, visited):
  if not proto_filename in visited:
    visited.append(proto_filename)
    with open(proto_filename) as inp:
      for line in inp:
        imp = re.search(r'import "([^"]*)"', line)
        if not imp: continue
        imp_proto = imp.group(1)
        if key not in deps: deps[key] = []
        deps[key].append(imp_proto[:-6])
        if is_trans:
          update_deps(key, imp_proto, deps, is_trans, visited)

def main():
  proto_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
  os.chdir(os.path.join(proto_dir, '../..'))

  deps = {}
  deps_trans = {}
  for root, dirs, files in os.walk('src/proto'):
    for f in files:
      if f[-6:] != '.proto': continue
      look_at = os.path.join(root, f)
      deps_for = look_at[:-6]
      update_deps(deps_for, look_at, deps, False, [])      # First level deps
      update_deps(deps_for, look_at, deps_trans, True, []) # Transitive deps

  json = {
    'proto_deps': deps,
    'proto_transitive_deps': deps_trans
  }

  print yaml.dump(json)

if __name__ == '__main__':
  main()
<commit_msg>Handle google/protobuf includes in src/proto<commit_after>#!/usr/bin/env python2.7
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Generates the appropriate build.json data for all the proto files."""
import yaml
import collections
import os
import re
import sys

def update_deps(key, proto_filename, deps, deps_external, is_trans, visited):
  if not proto_filename in visited:
    visited.append(proto_filename)
    with open(proto_filename) as inp:
      for line in inp:
        imp = re.search(r'import "([^"]*)"', line)
        if not imp: continue
        imp_proto = imp.group(1)
        # This indicates an external dependency, which we should handle
        # differently and not traverse recursively
        if imp_proto.startswith('google/'):
          if key not in deps_external:
            deps_external[key] = []
          deps_external[key].append(imp_proto[:-6])
          continue
        if key not in deps: deps[key] = []
        deps[key].append(imp_proto[:-6])
        if is_trans:
          update_deps(key, imp_proto, deps, deps_external, is_trans, visited)

def main():
  proto_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
  os.chdir(os.path.join(proto_dir, '../..'))

  deps = {}
  deps_trans = {}
  deps_external = {}
  deps_external_trans = {}
  for root, dirs, files in os.walk('src/proto'):
    for f in files:
      if f[-6:] != '.proto': continue
      look_at = os.path.join(root, f)
      deps_for = look_at[:-6]
      # First level deps
      update_deps(deps_for, look_at, deps, deps_external, False, [])
      # Transitive deps
      update_deps(deps_for, look_at, deps_trans, deps_external_trans, True, [])

  json = {
    'proto_deps': deps,
    'proto_transitive_deps': deps_trans,
    'proto_external_deps': deps_external,
    'proto_transitive_external_deps': deps_external_trans
  }

  print yaml.dump(json)

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