<commit_before># -*- coding: utf-8 -*-
# pylint: disable=too-many-instance-attributes

"""Functionality to support saving and restoring the current Sonos state.

This is useful for scenarios such as when you want to switch to radio
or an announcement and then back again to what was playing previously.

Warning:
    This class is designed to be created used and destroyed. It is not
    designed to be reused or long lived. The init sets up defaults for
    one use.
"""

class Snapshot(object):
    """A snapshot of the current state.

    Note:
        This does not change anything to do with the configuration
        such as which group the speaker is in, just settings that impact
        what is playing, or how it is played.

        List of sources that may be playing using root of media_uri:

        | ``x-rincon-queue``: playing from Queue
        | ``x-sonosapi-stream``: playing a stream (eg radio)
        | ``x-file-cifs``: playing file
        | ``x-rincon``: slave zone (only change volume etc. rest from
          coordinator)
    """

    def __init__(self, device, snapshot_queue=False):
        """
        Args:
            device (SoCo): The device to snapshot
            snapshot_queue (bool): Whether the queue should be snapshotted.
                Defaults to `False`.

        Warning:
            It is strongly advised that you do not snapshot the queue unless
            you really need to as it takes a very long time to restore large
            queues as it is done one track at a time.
        """
        # The device that will be snapshotted
        self.device = device

        # The values that will be stored
        # For all zones:
        self.media_uri = None
        self.is_coordinator = False
        self.is_playing_queue = False

        self.volume = None
        self.mute = None
        self.bass = None
        self.treble = None
        self.loudness = None

        # For coordinator zone playing from Queue:
        self.play_mode = None
        self.cross_fade = None
        self.playlist_position = 0
        self.track_position = None

        # For coordinator zone playing a Stream:
        self.media_metadata = None

        # For all coordinator zones
        self.transport_state = None

        self.queue = None
        # Only set the queue as a list if we are going to save it
        if snapshot_queue:
            self.queue = []

    def snapshot(self):
        """Record and store the current state of a device.

        Returns:
            bool: `True` if the device is a coordinator, `False` otherwise.
                Useful for determining whether playing an alert on a device
                will ungroup it.
        """
        # get if device coordinator (or slave) True (or False)
        self.is_coordinator = self.device.is_coordinator

        # Get information about the currently playing media
        media_info = self.device.avTransport.GetMediaInfo([('InstanceID', 0)])
        self.media_uri = media_info['CurrentURI']
        # extract source from media uri
        if self.media_uri.split(':')[0] == 'x-rincon-queue':
            self.is_playing_queue = True

        # Save the volume, mute and other sound settings
        self.volume = self.device.volume
        self.mute = self.device.mute
        self.bass = self.device.bass
        self.treble = self.device.treble
        self.loudness = self.device.loudness

        # get details required for what's playing:
        if self.is_playing_queue:
            # playing from queue - save repeat, random, cross fade, track, etc.
            self.play_mode = self.device.play_mode
            self.cross_fade = self.device.cross_fade

            # Get information about the currently playing track
            track_info = self.device.get_current_track_info()
            if track_info is not None:
                position = track_info['playlist_position']
                if position != "":
                    # save as integer
                    self.playlist_position = int(position)
                self.track_position = track_info['position']
        else:
            # playing from a stream - save media metadata
            self.media_metadata = media_info['CurrentURIMetaData']

        # Work out what the playing state is - if a coordinator
        if self.is_coordinator:
            transport_info = self.device.get_current_transport_info()
            if transport_info is not None:
                self.transport_state = transport_info[
                    'current_transport_state']

        # Save of the current queue if we need to
        self._save_queue()

        # return if device is a coordinator (helps usage)
        return self.is_coordinator

    # pylint: disable=too-many-branches
    def restore(self, fade=False):
        """Restore the state of a device to that which was previously saved.

        For coordinator devices restore everything. For slave devices
        only restore volume etc., not transport info (transport info
        comes from the slave's coordinator).

        Args:
            fade (bool): Whether volume should be faded up on restore.
        """

        if self.is_coordinator:
            # Start by ensuring that the speaker is paused as we don't want
            # things all rolling back when we are changing them, as this could
            # include things like audio
            transport_info = self.device.get_current_transport_info()
            if transport_info is not None:
                if transport_info['current_transport_state'] == 'PLAYING':
                    self.device.pause()

            # Check if the queue should be restored
            self._restore_queue()

            # Reinstate what was playing

            if self.is_playing_queue and self.playlist_position > 0:
                # was playing from playlist

                if self.playlist_position is not None:

                    # The position in the playlist returned by
                    # get_current_track_info starts at 1, but when
                    # playing from playlist, the index starts at 0
                    # if position > 0:
                    self.playlist_position -= 1
                    self.device.play_from_queue(self.playlist_position, False)

                if self.track_position is not None:
                    if self.track_position != "":
                        self.device.seek(self.track_position)

                # reinstate track, position, play mode, cross fade
                # Need to make sure there is a proper track selected first
                self.device.play_mode = self.play_mode
                self.device.cross_fade = self.cross_fade
            else:
                # was playing a stream (radio station, file, or nothing)
                # reinstate uri and meta data
                if self.media_uri != "":
                    self.device.play_uri(
                        self.media_uri, self.media_metadata, start=False)

        # For all devices:
        # Reinstate all the properties that are pretty easy to do
        self.device.mute = self.mute
        self.device.bass = self.bass
        self.device.treble = self.treble
        self.device.loudness = self.loudness

        # Reinstate volume
        # Can only change volume on device with fixed volume set to False
        # otherwise get uPnP error, so check first. Before issuing a network
        # command to check, fixed volume always has volume set to 100.
        # So only checked fixed volume if volume is 100.
        if self.volume == 100:
            fixed_vol = self.device.renderingControl.GetOutputFixed(
                [('InstanceID', 0)])['CurrentFixed']
        else:
            fixed_vol = False

        # now set volume if not fixed
        if not fixed_vol:
            if fade:
                # if fade requested in restore
                # set volume to 0 then fade up to saved volume (non blocking)
                self.device.volume = 0
                self.device.ramp_to_volume(self.volume)
            else:
                # set volume
                self.device.volume = self.volume

        # Now everything is set, see if we need to be playing, stopped
        # or paused ( only for coordinators)
        if self.is_coordinator:
            if self.transport_state == 'PLAYING':
                self.device.play()
            elif self.transport_state == 'STOPPED':
                self.device.stop()

    def _save_queue(self):
        """Save the current state of the queue."""
        if self.queue is not None:
            # Maximum batch is 486, anything larger will still only
            # return 486
            batch_size = 400
            total = 0
            num_return = batch_size

            # Need to get all the tracks in batches, but Only get the next
            # batch if all the items requested were in the last batch
            while num_return == batch_size:
                queue_items = self.device.get_queue(total, batch_size)
                # Check how many entries were returned
                num_return = len(queue_items)
                # Make sure the queue is not empty
                if num_return > 0:
                    self.queue.append(queue_items)
                # Update the total that have been processed
                total = total + num_return

    def _restore_queue(self):
        """Restore the previous state of the queue.

        Note:
            The restore currently adds the items back into the queue
            using the URI, for items the Sonos system already knows about
            this is OK, but for other items, they may be missing some of
            their metadata as it will not be automatically picked up.
        """
        if self.queue is not None:
            # Clear the queue so that it can be reset
            self.device.clear_queue()
            # Now loop around all the queue entries adding them
            for queue_group in self.queue:
                for queue_item in queue_group:
                    self.device.add_uri_to_queue(queue_item.uri)
<commit_msg>Prevent error when queue started from Alexa<commit_after># -*- coding: utf-8 -*-
# pylint: disable=too-many-instance-attributes

"""Functionality to support saving and restoring the current Sonos state.

This is useful for scenarios such as when you want to switch to radio
or an announcement and then back again to what was playing previously.

Warning:
    Sonos has introduced control via Amazon Alexa. A new cloud queue is
    created and at present there appears no way to restart this
    queue from snapshot. Currently if a cloud queue was playing it will
    not restart.

Warning:
    This class is designed to be created used and destroyed. It is not
    designed to be reused or long lived. The init sets up defaults for
    one use.
"""

class Snapshot(object):
    """A snapshot of the current state.

    Note:
        This does not change anything to do with the configuration
        such as which group the speaker is in, just settings that impact
        what is playing, or how it is played.

        List of sources that may be playing using root of media_uri:

        | ``x-rincon-queue``: playing from Queue
        | ``x-sonosapi-stream``: playing a stream (eg radio)
        | ``x-file-cifs``: playing file
        | ``x-rincon``: slave zone (only change volume etc. rest from
          coordinator)
    """

    def __init__(self, device, snapshot_queue=False):
        """
        Args:
            device (SoCo): The device to snapshot
            snapshot_queue (bool): Whether the queue should be snapshotted.
                Defaults to `False`.

        Warning:
            It is strongly advised that you do not snapshot the queue unless
            you really need to as it takes a very long time to restore large
            queues as it is done one track at a time.
        """
        # The device that will be snapshotted
        self.device = device

        # The values that will be stored
        # For all zones:
        self.media_uri = None
        self.is_coordinator = False
        self.is_playing_queue = False
        self.is_playing_cloud_queue = False

        self.volume = None
        self.mute = None
        self.bass = None
        self.treble = None
        self.loudness = None

        # For coordinator zone playing from Queue:
        self.play_mode = None
        self.cross_fade = None
        self.playlist_position = 0
        self.track_position = None

        # For coordinator zone playing a Stream:
        self.media_metadata = None

        # For all coordinator zones
        self.transport_state = None

        self.queue = None
        # Only set the queue as a list if we are going to save it
        if snapshot_queue:
            self.queue = []

    def snapshot(self):
        """Record and store the current state of a device.

        Returns:
            bool: `True` if the device is a coordinator, `False` otherwise.
                Useful for determining whether playing an alert on a device
                will ungroup it.
        """
        # get if device coordinator (or slave) True (or False)
        self.is_coordinator = self.device.is_coordinator

        # Get information about the currently playing media
        media_info = self.device.avTransport.GetMediaInfo([('InstanceID', 0)])
        self.media_uri = media_info['CurrentURI']
        # extract source from media uri
        if self.media_uri.split(':')[0] == 'x-rincon-queue':
            # The pylint error below is a false positive, see about removing it
            # in the future
            # pylint: disable=simplifiable-if-statement
            if self.media_uri.split('#')[1] == '0':
                # playing local queue
                self.is_playing_queue = True
            else:
                # playing cloud queue - started from Alexa
                self.is_playing_cloud_queue = True

        # Save the volume, mute and other sound settings
        self.volume = self.device.volume
        self.mute = self.device.mute
        self.bass = self.device.bass
        self.treble = self.device.treble
        self.loudness = self.device.loudness

        # get details required for what's playing:
        if self.is_playing_queue:
            # playing from queue - save repeat, random, cross fade, track, etc.
            self.play_mode = self.device.play_mode
            self.cross_fade = self.device.cross_fade

            # Get information about the currently playing track
            track_info = self.device.get_current_track_info()
            if track_info is not None:
                position = track_info['playlist_position']
                if position != "":
                    # save as integer
                    self.playlist_position = int(position)
                self.track_position = track_info['position']
        else:
            # playing from a stream - save media metadata
            self.media_metadata = media_info['CurrentURIMetaData']

        # Work out what the playing state is - if a coordinator
        if self.is_coordinator:
            transport_info = self.device.get_current_transport_info()
            if transport_info is not None:
                self.transport_state = transport_info[
                    'current_transport_state']

        # Save of the current queue if we need to
        self._save_queue()

        # return if device is a coordinator (helps usage)
        return self.is_coordinator

    # pylint: disable=too-many-branches
    def restore(self, fade=False):
        """Restore the state of a device to that which was previously saved.

        For coordinator devices restore everything. For slave devices
        only restore volume etc., not transport info (transport info
        comes from the slave's coordinator).

        Args:
            fade (bool): Whether volume should be faded up on restore.
        """

        if self.is_coordinator:
            # Start by ensuring that the speaker is paused as we don't want
            # things all rolling back when we are changing them, as this could
            # include things like audio
            transport_info = self.device.get_current_transport_info()
            if transport_info is not None:
                if transport_info['current_transport_state'] == 'PLAYING':
                    self.device.pause()

            # Check if the queue should be restored
            self._restore_queue()

            # Reinstate what was playing

            if self.is_playing_queue and self.playlist_position > 0:
                # was playing from playlist

                if self.playlist_position is not None:
                    # The position in the playlist returned by
                    # get_current_track_info starts at 1, but when
                    # playing from playlist, the index starts at 0
                    # if position > 0:
                    self.playlist_position -= 1
                    self.device.play_from_queue(self.playlist_position, False)

                if self.track_position is not None:
                    if self.track_position != "":
                        self.device.seek(self.track_position)

                # reinstate track, position, play mode, cross fade
                # Need to make sure there is a proper track selected first
                self.device.play_mode = self.play_mode
                self.device.cross_fade = self.cross_fade

            elif self.is_playing_cloud_queue:
                # was playing a cloud queue started by Alexa
                # No way yet to re-start this so prevent it throwing an error!
                pass

            else:
                # was playing a stream (radio station, file, or nothing)
                # reinstate uri and meta data
                if self.media_uri != "":
                    self.device.play_uri(
                        self.media_uri, self.media_metadata, start=False)

        # For all devices:
        # Reinstate all the properties that are pretty easy to do
        self.device.mute = self.mute
        self.device.bass = self.bass
        self.device.treble = self.treble
        self.device.loudness = self.loudness

        # Reinstate volume
        # Can only change volume on device with fixed volume set to False
        # otherwise get uPnP error, so check first. Before issuing a network
        # command to check, fixed volume always has volume set to 100.
        # So only checked fixed volume if volume is 100.
        if self.volume == 100:
            fixed_vol = self.device.renderingControl.GetOutputFixed(
                [('InstanceID', 0)])['CurrentFixed']
        else:
            fixed_vol = False

        # now set volume if not fixed
        if not fixed_vol:
            if fade:
                # if fade requested in restore
                # set volume to 0 then fade up to saved volume (non blocking)
                self.device.volume = 0
                self.device.ramp_to_volume(self.volume)
            else:
                # set volume
                self.device.volume = self.volume

        # Now everything is set, see if we need to be playing, stopped
        # or paused ( only for coordinators)
        if self.is_coordinator:
            if self.transport_state == 'PLAYING':
                self.device.play()
            elif self.transport_state == 'STOPPED':
                self.device.stop()

    def _save_queue(self):
        """Save the current state of the queue."""
        if self.queue is not None:
            # Maximum batch is 486, anything larger will still only
            # return 486
            batch_size = 400
            total = 0
            num_return = batch_size

            # Need to get all the tracks in batches, but Only get the next
            # batch if all the items requested were in the last batch
            while num_return == batch_size:
                queue_items = self.device.get_queue(total, batch_size)
                # Check how many entries were returned
                num_return = len(queue_items)
                # Make sure the queue is not empty
                if num_return > 0:
                    self.queue.append(queue_items)
                # Update the total that have been processed
                total = total + num_return

    def _restore_queue(self):
        """Restore the previous state of the queue.

        Note:
            The restore currently adds the items back into the queue
            using the URI, for items the Sonos system already knows about
            this is OK, but for other items, they may be missing some of
            their metadata as it will not be automatically picked up.
        """
        if self.queue is not None:
            # Clear the queue so that it can be reset
            self.device.clear_queue()
            # Now loop around all the queue entries adding them
            for queue_group in self.queue:
                for queue_item in queue_group:
                    self.device.add_uri_to_queue(queue_item.uri)
<|endoftext|>


<commit_before><commit_msg>adding static get_remaining_cards for Deck, works but still needs the first zone tag-change properly populated on entities<commit_after><|endoftext|>


<commit_before>"""BDR URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
	url(r'^user/', include('user.urls')),
	url(r'^salon/', include('salon.urls')),
	url(r'^core/', include('core.urls')),
    url(r'^admin/', admin.site.urls),
]
<commit_msg>Core passé en page daccueil<commit_after>"""BDR URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
	url(r'^user/', include('user.urls')),
	url(r'^salon/', include('salon.urls')),
	url(r'^', include('core.urls')),
    url(r'^admin/', admin.site.urls),
]
<|endoftext|>


<commit_before>import os.path
import shutil
import sublime
import sublime_plugin
import subprocess

SETTINGS_FILE = "BeautifyRust.sublime-settings"

def which(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        return shutil.which(program)

class BeautifyRustOnSave(sublime_plugin.EventListener):

    def on_post_save(self, view):
        if sublime.load_settings(SETTINGS_FILE).get("run_on_save", False):
            return view.run_command("beautify_rust")
        return

class BeautifyRustCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        self.filename = self.view.file_name()
        self.fname = os.path.basename(self.filename)
        self.settings = sublime.load_settings(SETTINGS_FILE)
        if self.is_rust_file():
            self.run_format(edit)

    def is_rust_file(self):
        return self.fname.endswith(".rs")

    def pipe(self, cmd):
        cwd = os.path.dirname(self.filename)
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        beautifier = subprocess.Popen(
            cmd, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            startupinfo=startupinfo)
        (_, err) = beautifier.communicate()
        return (beautifier.wait(), err.decode('utf8'))

    def run_format(self, edit):
        buffer_region = sublime.Region(0, self.view.size())
        buffer_text = self.view.substr(buffer_region)
        if buffer_text == "":
            return
        rustfmt_bin = which(self.settings.get("rustfmt", "rustfmt"))
        if rustfmt_bin is None:
            return sublime.error_message(
                "Beautify rust: can not find {0} in path.".format(self.settings.get("rustfmt", "rustfmt")))
        cmd_list = [rustfmt_bin, self.filename, "--write-mode=overwrite"] + self.settings.get("args", [])
        self.save_viewport_state()
        (exit_code, err) = self.pipe(cmd_list)
        if exit_code != 0 or (err != "" and not err.startswith("Using rustfmt")):
            self.view.replace(edit, buffer_region, buffer_text)
            print("failed: exit_code: {0}\n{1}".format(exit_code, err))
            if sublime.load_settings(SETTINGS_FILE).get("show_errors", True):
                sublime.error_message(
                    "Beautify rust: rustfmt process call failed. See log (ctrl + `) for details.")
        self.view.window().run_command("reload_all_files")
        self.reset_viewport_state()

    def save_viewport_state(self):
        self.previous_selection = [(region.a, region.b)
                                   for region in self.view.sel()]
        self.previous_position = self.view.viewport_position()

    def reset_viewport_state(self):
        self.view.set_viewport_position((0, 0,), False)
        self.view.set_viewport_position(self.previous_position, False)
        self.view.sel().clear()
        for a, b in self.previous_selection:
            self.view.sel().add(sublime.Region(a, b))
<commit_msg>Remove --write-mode option<commit_after>import os.path
import shutil
import sublime
import sublime_plugin
import subprocess

SETTINGS_FILE = "BeautifyRust.sublime-settings"

def which(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        return shutil.which(program)

class BeautifyRustOnSave(sublime_plugin.EventListener):

    def on_post_save(self, view):
        if sublime.load_settings(SETTINGS_FILE).get("run_on_save", False):
            return view.run_command("beautify_rust")
        return

class BeautifyRustCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        self.filename = self.view.file_name()
        self.fname = os.path.basename(self.filename)
        self.settings = sublime.load_settings(SETTINGS_FILE)
        if self.is_rust_file():
            self.run_format(edit)

    def is_rust_file(self):
        return self.fname.endswith(".rs")

    def pipe(self, cmd):
        cwd = os.path.dirname(self.filename)
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        beautifier = subprocess.Popen(
            cmd, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            startupinfo=startupinfo)
        (_, err) = beautifier.communicate()
        return (beautifier.wait(), err.decode('utf8'))

    def run_format(self, edit):
        buffer_region = sublime.Region(0, self.view.size())
        buffer_text = self.view.substr(buffer_region)
        if buffer_text == "":
            return
        rustfmt_bin = which(self.settings.get("rustfmt", "rustfmt"))
        if rustfmt_bin is None:
            return sublime.error_message(
                "Beautify rust: can not find {0} in path.".format(self.settings.get("rustfmt", "rustfmt")))
        cmd_list = [rustfmt_bin, self.filename] + self.settings.get("args", [])
        self.save_viewport_state()
        (exit_code, err) = self.pipe(cmd_list)
        if exit_code != 0 or (err != "" and not err.startswith("Using rustfmt")):
            self.view.replace(edit, buffer_region, buffer_text)
            print("failed: exit_code: {0}\n{1}".format(exit_code, err))
            if sublime.load_settings(SETTINGS_FILE).get("show_errors", True):
                sublime.error_message(
                    "Beautify rust: rustfmt process call failed. See log (ctrl + `) for details.")
        self.view.window().run_command("reload_all_files")
        self.reset_viewport_state()

    def save_viewport_state(self):
        self.previous_selection = [(region.a, region.b)
                                   for region in self.view.sel()]
        self.previous_position = self.view.viewport_position()

    def reset_viewport_state(self):
        self.view.set_viewport_position((0, 0,), False)
        self.view.set_viewport_position(self.previous_position, False)
        self.view.sel().clear()
        for a, b in self.previous_selection:
            self.view.sel().add(sublime.Region(a, b))
<|endoftext|>


<commit_before>import jwt

from rest_framework import exceptions
from rest_framework.compat import smart_text
from rest_framework.authentication import (BaseAuthentication,
                                           get_authorization_header)

from rest_framework_jwt.settings import api_settings

try:
    from django.contrib.auth import get_user_model
except ImportError:  # Django < 1.5
    from django.contrib.auth.models import User
else:
    User = get_user_model()

jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_user_id_from_payload = api_settings.JWT_PAYLOAD_GET_USER_ID_HANDLER

class JSONWebTokenAuthentication(BaseAuthentication):
    """
    Token based authentication using the JSON Web Token standard.

    Clients should authenticate by passing the token key in the "Authorization"
    HTTP header, prepended with the string "JWT ".  For example:

        Authorization: JWT eyJhbGciOiAiSFMyNTYiLCAidHlwIj
    """
    www_authenticate_realm = 'api'

    def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """
        auth = get_authorization_header(request).split()
        auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()

        if not auth or smart_text(auth[0].lower()) != auth_header_prefix:
            return None

        if len(auth) == 1:
            msg = 'Invalid Authorization header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = ('Invalid Authorization header. Credentials string '
                   'should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            payload = jwt_decode_handler(auth[1])
        except jwt.ExpiredSignature:
            msg = 'Signature has expired.'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = 'Error decoding signature.'
            raise exceptions.AuthenticationFailed(msg)

        user = self.authenticate_credentials(payload)

        return (user, auth[1])

    def authenticate_credentials(self, payload):
        """
        Returns an active user that matches the payload's user id and email.
        """
        try:
            user_id = jwt_get_user_id_from_payload(payload)

            if user_id:
                user = User.objects.get(pk=user_id, is_active=True)
            else:
                msg = 'Invalid payload'
                raise exceptions.AuthenticationFailed(msg)
        except User.DoesNotExist:
            msg = 'Invalid signature'
            raise exceptions.AuthenticationFailed(msg)

        return user

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        return 'JWT realm="{0}"'.format(self.www_authenticate_realm)
<commit_msg>Update block doc about JWT_AUTH_HEADER_PREFIX<commit_after>import jwt

from rest_framework import exceptions
from rest_framework.compat import smart_text
from rest_framework.authentication import (BaseAuthentication,
                                           get_authorization_header)

from rest_framework_jwt.settings import api_settings

try:
    from django.contrib.auth import get_user_model
except ImportError:  # Django < 1.5
    from django.contrib.auth.models import User
else:
    User = get_user_model()

jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_user_id_from_payload = api_settings.JWT_PAYLOAD_GET_USER_ID_HANDLER

class JSONWebTokenAuthentication(BaseAuthentication):
    """
    Token based authentication using the JSON Web Token standard.

    Clients should authenticate by passing the token key in the "Authorization"
    HTTP header, prepended with the string specified in the setting
    `JWT_AUTH_HEADER_PREFIX`. For example:

        Authorization: JWT eyJhbGciOiAiSFMyNTYiLCAidHlwIj
    """
    www_authenticate_realm = 'api'

    def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """
        auth = get_authorization_header(request).split()
        auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()

        if not auth or smart_text(auth[0].lower()) != auth_header_prefix:
            return None

        if len(auth) == 1:
            msg = 'Invalid Authorization header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = ('Invalid Authorization header. Credentials string '
                   'should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            payload = jwt_decode_handler(auth[1])
        except jwt.ExpiredSignature:
            msg = 'Signature has expired.'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = 'Error decoding signature.'
            raise exceptions.AuthenticationFailed(msg)

        user = self.authenticate_credentials(payload)

        return (user, auth[1])

    def authenticate_credentials(self, payload):
        """
        Returns an active user that matches the payload's user id and email.
        """
        try:
            user_id = jwt_get_user_id_from_payload(payload)

            if user_id:
                user = User.objects.get(pk=user_id, is_active=True)
            else:
                msg = 'Invalid payload'
                raise exceptions.AuthenticationFailed(msg)
        except User.DoesNotExist:
            msg = 'Invalid signature'
            raise exceptions.AuthenticationFailed(msg)

        return user

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        return 'JWT realm="{0}"'.format(self.www_authenticate_realm)
<|endoftext|>


<commit_before>"""ShutIt module. See http://shutit.tk
"""
#Copyright (C) 2014 OpenBet Limited
#
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is furnished
#to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from shutit_module import ShutItModule
import util
import os

class template(ShutItModule):
	# Determines whether the module has been built in this container
	# already.
	#
	# Should return True if it is certain it's there, else False.
	def is_installed(self,shutit):
		return shutit.file_exists('/tmp/container_touched.sh') and shutit.file_exists('/tmp/README.md')

	# Run the build part of the module, which should ensure the module
	# has been set up.
	# If is_installed determines that the module is already there,
	# this is not run.
	#
	# Should return True if it has succeeded in building, else False.
	def build(self,shutit):
		# Line number 49 should be the next one (so bash scripts can be inserted properly)

		# DELETE THIS SECTION WHEN UNDERSTOOD - BEGIN
		shutit.send_and_expect('touch /tmp/deleteme')
		shutit.send_and_expect('touch /tmp/container_touched.sh')
		shutit.add_line_to_file('#This line should only appear once in the file','/tmp/container_touched.sh')
		shutit.add_line_to_file('#This line should only appear once in the file','/tmp/container_touched.sh')
		# We add the match_regexp because the string has a quote in it.
		shutit.add_line_to_file('echo "hello container"','/tmp/container_touched.sh',match_regexp='echo .hello container.')
		shutit.add_line_to_file('sleep 10000000 &','/tmp/container_touched.sh')
		shutit.send_and_expect('chmod +x /tmp/container_touched.sh')
		# Make sure passwd is installed
		shutit.install('passwd')
		# Install mlocate
		shutit.install('mlocate')
		# Example of distro-specific password update
		# record_command=False prevents the password being output at the end on debug. However, if it matches a password stored in config,
		# it will automatically redact it.
		if shutit.cfg['container']['install_type'] == 'apt': # apt-based password update
			# "check_exit" checks the exit code of the command you are running.
			# We can't check the exit code as the command will not return when we see 'Retype new' on the terminal.
			shutit.send_and_expect('passwd','Enter new',check_exit=False)
			shutit.send_and_expect(shutit.cfg['container']['password'],'Retype new',check_exit=False,record_command=False)
			shutit.send_and_expect(shutit.cfg['container']['password'])
		elif shutit.cfg['container']['install_type'] == 'yum': # yum-based password update
			# Check_exit checks the exit code of the command you are running.
			# We can't check the exit code as the command will not return when we see 'ew password' on the terminal.
			shutit.send_and_expect('passwd','ew password',check_exit=False)
			shutit.send_and_expect(shutit.cfg['container']['password'],'ew password',check_exit=False,record_command=False)
			shutit.send_and_expect(shutit.cfg['container']['password'])
		# You can put multiple items you might expect in a list and handle accordingly:
		res = shutit.send_and_expect('sudo ls',['assword',shutit.cfg['expect_prompts']['root_prompt']],check_exit=False)
		if res == 0:
			shutit.send_and_expect(shutit.cfg['container']['password'])
		elif res == 1:
			pass
		else:
			# We fail out on this case, as it's not expected.
			util.fail('res: ' + str(res) + ' not handled')
		# example of resource use (simple file, copy README.md into the container)
		shutit.send_file('/tmp/copiedfile',file.read(file(os.path.abspath(os.path.dirname(__file__)) + '/README.md')))
		# example of bespoke config use
		if shutit.cfg[self.module_id]['example_bool']:
			shutit.add_line_to_file('# ' + shutit.cfg[self.module_id]['example'],'/tmp/container_touched.sh')
		# Example of login/logout handling
		# When logging in, use the base prompt to attempt to match all prompts
		# Note that we don't check_exit, because the exit value won't be meaningful.
		shutit.send_and_expect('su',shutit.cfg['expect_prompts']['base_prompt'],check_exit=False)
		# Then call setup_prompt to set and get the bespoke prompt for the session
		shutit.setup_prompt('test_tmp_prompt')
		shutit.set_default_expect(shutit.cfg['expect_prompts']['test_tmp_prompt'])
		shutit.send_and_expect('echo "a command and some output"')
		# Make sure we're expecting the right thing after we exit this subshell
		shutit.set_default_expect(shutit.cfg['expect_prompts']['root_prompt'])
		shutit.send_and_expect('exit')

		# Example of temporary debugging
		orig_debug_val = shutit.cfg['build']['debug']
		shutit.cfg['build']['debug'] = True
		shutit.send_and_expect('echo "Command to look at debug output"')
		shutit.send_and_expect('echo "Another command to look at debug output"')
		shutit.cfg['build']['debug'] = orig_debug_val
		shutit.pause_point("""
				The doubling up of text is expected; try and ignore it :)
				When you're done, "Ctrl" and "]" at the same time.
				You should then see your inputted lines in the output.
				Add them to the module file before the pause_point line as
				"util.send_and_expect" lines (copy and paste), following
				the examples above this one in the file.
				Then "Ctrl" and "]" at the same time again to return to the script.
				Eventually you'll get a docker export to a tar file in your
				configured resources folder.""")
		# DELETE THIS SECTION WHEN UNDERSTOOD - DONE
		return True

	# get_config
	#
	# each object can handle config here
	# OPTIONAL part of lifecycle - uncomment to include
	def get_config(self,shutit):
		cp = shutit.cfg['config_parser']
		# Bring the example config into the config dictionary.
		shutit.cfg[self.module_id]['example']      = cp.get(self.module_id,'example')
		shutit.cfg[self.module_id]['example_bool'] = cp.getboolean(self.module_id,'example_bool')
		return True

	# check_ready
	#
	# Check whether we are ready to build this module.
	#
	# This is called before the build, to ensure modules have
	# their requirements in place (eg files required to be mounted
	# in /resources). Checking whether the build will happen (and
	# therefore whether the check should take place) will be
	# determined by the framework.
	#
	# Should return True if it ready, else False.
	# OPTIONAL part of lifecycle - uncomment to include
	#def check_ready(self,shutit):
	#	return shutit.file_exists('/resources/README.md')

	# start
	#
	# Run when module should be installed (is_installed() or configured to build is true)
	# Run after repo work.
	# OPTIONAL part of lifecycle - uncomment to include
	#def start(self,shutit):
	#	# example of starting something
	#	shutit.send_and_expect('cat /tmp/container_touched.sh')
	#	shutit.send_and_expect('sh /tmp/container_touched.sh')
	#	return True

	# stop
	#
	# Run when module should be stopped.
	# Run before repo work, and before finalize is called.
	# OPTIONAL part of lifecycle - uncomment to include
	#def stop(self,shutit):
	#	# example of stopping something
	#	shutit.send_and_expect("""ps -ef | grep -v grep | grep container_touched.sh | awk '{print $1}' | sed 's/\([0-9][0-9]*\)/kill \\1/' | sh""")
	#	return True

	# cleanup
	#
	# Cleanup the module, ie clear up stuff not needed for the rest of the build, eg tar files removed, apt-get cleans.
	# Should return True if all is OK, else False.
	# Note that this is only run if the build phase was actually run.
	# OPTIONAL part of lifecycle - uncomment to include
	#def cleanup(self,shutit):
	#	shutit.send_and_expect('rm -f /tmp/deleteme')
	#	return True

	# finalize
	#
	# Finalize the module, ie do things that need doing before we exit.
	# OPTIONAL part of lifecycle - uncomment to include
	#def finalize(self,shutit):
	#	# Right at the end we want to ensure the locate db is up to date.
	#	shutit.send_and_expect('updatedb')
	#	return True

	# remove
	#
	# Remove the module, which should ensure the module has been deleted
	# from the system.
	# OPTIONAL part of lifecycle - uncomment to include
	#def remove(self,shutit):
	#	shutit.send_and_expect('rm -f /tmp/container_touched.sh')
	#	shutit.send_and_expect('rm -f /tmp/README.md')
	#	# TODO: remove the installed apps DEPENDS on install tracking being available.
	#	return True

	# test
	#
	# Test the module is OK.
	# Should return True if all is OK, else False.
	# This is run regardless of whether the module is installed or not.
	# OPTIONAL part of lifecycle - uncomment to include
	#def test(self,shutit):
	#	return shutit.package_installed('mlocate') and shutit.package_installed('passwd')

# template(string,float)
# string : Any string you believe to identify this module uniquely,
#          eg com.my_corp.my_module_dir.my_module
# float:   Float value for ordering module builds, must be > 0.0
def module():
	return template(
		GLOBALLY_UNIQUE_STRING, FLOAT,
		depends=['shutit.tk.setup']
	)

<commit_msg>No more util in shutit_module_template<commit_after>"""ShutIt module. See http://shutit.tk
"""
#Copyright (C) 2014 OpenBet Limited
#
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is furnished
#to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from shutit_module import ShutItModule
import os

class template(ShutItModule):
	# Determines whether the module has been built in this container
	# already.
	#
	# Should return True if it is certain it's there, else False.
	def is_installed(self,shutit):
		return shutit.file_exists('/tmp/container_touched.sh') and shutit.file_exists('/tmp/README.md')

	# Run the build part of the module, which should ensure the module
	# has been set up.
	# If is_installed determines that the module is already there,
	# this is not run.
	#
	# Should return True if it has succeeded in building, else False.
	def build(self,shutit):
		# Line number 49 should be the next one (so bash scripts can be inserted properly)

		# DELETE THIS SECTION WHEN UNDERSTOOD - BEGIN
		shutit.send_and_expect('touch /tmp/deleteme')
		shutit.send_and_expect('touch /tmp/container_touched.sh')
		shutit.add_line_to_file('#This line should only appear once in the file','/tmp/container_touched.sh')
		shutit.add_line_to_file('#This line should only appear once in the file','/tmp/container_touched.sh')
		# We add the match_regexp because the string has a quote in it.
		shutit.add_line_to_file('echo "hello container"','/tmp/container_touched.sh',match_regexp='echo .hello container.')
		shutit.add_line_to_file('sleep 10000000 &','/tmp/container_touched.sh')
		shutit.send_and_expect('chmod +x /tmp/container_touched.sh')
		# Make sure passwd is installed
		shutit.install('passwd')
		# Install mlocate
		shutit.install('mlocate')
		# Example of distro-specific password update
		# record_command=False prevents the password being output at the end on debug. However, if it matches a password stored in config,
		# it will automatically redact it.
		if shutit.cfg['container']['install_type'] == 'apt': # apt-based password update
			# "check_exit" checks the exit code of the command you are running.
			# We can't check the exit code as the command will not return when we see 'Retype new' on the terminal.
			shutit.send_and_expect('passwd','Enter new',check_exit=False)
			shutit.send_and_expect(shutit.cfg['container']['password'],'Retype new',check_exit=False,record_command=False)
			shutit.send_and_expect(shutit.cfg['container']['password'])
		elif shutit.cfg['container']['install_type'] == 'yum': # yum-based password update
			# Check_exit checks the exit code of the command you are running.
			# We can't check the exit code as the command will not return when we see 'ew password' on the terminal.
			shutit.send_and_expect('passwd','ew password',check_exit=False)
			shutit.send_and_expect(shutit.cfg['container']['password'],'ew password',check_exit=False,record_command=False)
			shutit.send_and_expect(shutit.cfg['container']['password'])
		# You can put multiple items you might expect in a list and handle accordingly:
		res = shutit.send_and_expect('sudo ls',['assword',shutit.cfg['expect_prompts']['root_prompt']],check_exit=False)
		if res == 0:
			shutit.send_and_expect(shutit.cfg['container']['password'])
		elif res == 1:
			pass
		else:
			# We fail out on this case, as it's not expected.
			shutit.fail('res: ' + str(res) + ' not handled')
		# example of resource use (simple file, copy README.md into the container)
		shutit.send_file('/tmp/copiedfile',file.read(file(os.path.abspath(os.path.dirname(__file__)) + '/README.md')))
		# example of bespoke config use
		if shutit.cfg[self.module_id]['example_bool']:
			shutit.add_line_to_file('# ' + shutit.cfg[self.module_id]['example'],'/tmp/container_touched.sh')
		# Example of login/logout handling
		# When logging in, use the base prompt to attempt to match all prompts
		# Note that we don't check_exit, because the exit value won't be meaningful.
		shutit.send_and_expect('su',shutit.cfg['expect_prompts']['base_prompt'],check_exit=False)
		# Then call setup_prompt to set and get the bespoke prompt for the session
		shutit.setup_prompt('test_tmp_prompt')
		shutit.set_default_expect(shutit.cfg['expect_prompts']['test_tmp_prompt'])
		shutit.send_and_expect('echo "a command and some output"')
		# Make sure we're expecting the right thing after we exit this subshell
		shutit.set_default_expect(shutit.cfg['expect_prompts']['root_prompt'])
		shutit.send_and_expect('exit')

		# Example of temporary debugging
		orig_debug_val = shutit.cfg['build']['debug']
		shutit.cfg['build']['debug'] = True
		shutit.send_and_expect('echo "Command to look at debug output"')
		shutit.send_and_expect('echo "Another command to look at debug output"')
		shutit.cfg['build']['debug'] = orig_debug_val
		shutit.pause_point("""
				The doubling up of text is expected; try and ignore it :)
				When you're done, "Ctrl" and "]" at the same time.
				You should then see your inputted lines in the output.
				Add them to the module file before the pause_point line as
				"shutit.send_and_expect" lines (copy and paste), following
				the examples above this one in the file.
				Then "Ctrl" and "]" at the same time again to return to the script.
				Eventually you'll get a docker export to a tar file in your
				configured resources folder.""")
		# DELETE THIS SECTION WHEN UNDERSTOOD - DONE
		return True

	# get_config
	#
	# each object can handle config here
	# OPTIONAL part of lifecycle - uncomment to include
	def get_config(self,shutit):
		cp = shutit.cfg['config_parser']
		# Bring the example config into the config dictionary.
		shutit.cfg[self.module_id]['example']      = cp.get(self.module_id,'example')
		shutit.cfg[self.module_id]['example_bool'] = cp.getboolean(self.module_id,'example_bool')
		return True

	# check_ready
	#
	# Check whether we are ready to build this module.
	#
	# This is called before the build, to ensure modules have
	# their requirements in place (eg files required to be mounted
	# in /resources). Checking whether the build will happen (and
	# therefore whether the check should take place) will be
	# determined by the framework.
	#
	# Should return True if it ready, else False.
	# OPTIONAL part of lifecycle - uncomment to include
	#def check_ready(self,shutit):
	#	return shutit.file_exists('/resources/README.md')

	# start
	#
	# Run when module should be installed (is_installed() or configured to build is true)
	# Run after repo work.
	# OPTIONAL part of lifecycle - uncomment to include
	#def start(self,shutit):
	#	# example of starting something
	#	shutit.send_and_expect('cat /tmp/container_touched.sh')
	#	shutit.send_and_expect('sh /tmp/container_touched.sh')
	#	return True

	# stop
	#
	# Run when module should be stopped.
	# Run before repo work, and before finalize is called.
	# OPTIONAL part of lifecycle - uncomment to include
	#def stop(self,shutit):
	#	# example of stopping something
	#	shutit.send_and_expect("""ps -ef | grep -v grep | grep container_touched.sh | awk '{print $1}' | sed 's/\([0-9][0-9]*\)/kill \\1/' | sh""")
	#	return True

	# cleanup
	#
	# Cleanup the module, ie clear up stuff not needed for the rest of the build, eg tar files removed, apt-get cleans.
	# Should return True if all is OK, else False.
	# Note that this is only run if the build phase was actually run.
	# OPTIONAL part of lifecycle - uncomment to include
	#def cleanup(self,shutit):
	#	shutit.send_and_expect('rm -f /tmp/deleteme')
	#	return True

	# finalize
	#
	# Finalize the module, ie do things that need doing before we exit.
	# OPTIONAL part of lifecycle - uncomment to include
	#def finalize(self,shutit):
	#	# Right at the end we want to ensure the locate db is up to date.
	#	shutit.send_and_expect('updatedb')
	#	return True

	# remove
	#
	# Remove the module, which should ensure the module has been deleted
	# from the system.
	# OPTIONAL part of lifecycle - uncomment to include
	#def remove(self,shutit):
	#	shutit.send_and_expect('rm -f /tmp/container_touched.sh')
	#	shutit.send_and_expect('rm -f /tmp/README.md')
	#	# TODO: remove the installed apps DEPENDS on install tracking being available.
	#	return True

	# test
	#
	# Test the module is OK.
	# Should return True if all is OK, else False.
	# This is run regardless of whether the module is installed or not.
	# OPTIONAL part of lifecycle - uncomment to include
	#def test(self,shutit):
	#	return shutit.package_installed('mlocate') and shutit.package_installed('passwd')

# template(string,float)
# string : Any string you believe to identify this module uniquely,
#          eg com.my_corp.my_module_dir.my_module
# float:   Float value for ordering module builds, must be > 0.0
def module():
	return template(
		GLOBALLY_UNIQUE_STRING, FLOAT,
		depends=['shutit.tk.setup']
	)

<|endoftext|>


<commit_before>"""
Implementing of comb sort algorith
https://en.wikipedia.org/wiki/Comb_sort
"""

def combsort(lst):
    size = len(lst)
    # set initial gap
    gap = size
    swaps = True

    while gap > 1 or swaps:
        # Minimun gap is 1
        gap = max(1, int(gap / 1.25))
        swaps = False

        for i in range(size - gap):
            j = i + gap

            if lst[i] > lst[j]:
                # swap elements
                lst[i], lst[j] = lst[j], lst[i]
                swaps = True
    return lst

if __name__ in "__main__":

    LIST = [1, 0, 2, 4, 5, 6, 2, 7, 9, 1, 3, 8, -1]
    print('list        :', LIST)
    print('comb sort   :', combsort(LIST), combsort(LIST) == sorted(LIST))
<commit_msg>fix typo<commit_after>"""
Implementation of comb sort algorithm
https://en.wikipedia.org/wiki/Comb_sort
"""

def combsort(lst):
    size = len(lst)
    # set initial gap
    gap = size
    swaps = True

    while gap > 1 or swaps:
        # Minimun gap is 1
        gap = max(1, int(gap / 1.25))
        swaps = False

        for i in range(size - gap):
            j = i + gap

            if lst[i] > lst[j]:
                # swap elements
                lst[i], lst[j] = lst[j], lst[i]
                swaps = True
    return lst

if __name__ in "__main__":

    LIST = [1, 0, 2, 4, 5, 6, 2, 7, 9, 1, 3, 8, -1]
    print('list        :', LIST)
    print('comb sort   :', combsort(LIST), combsort(LIST) == sorted(LIST))
<|endoftext|>


<commit_before>from pages.utils import auto_render
from pages.models import Language, Content, Page, has_page_permission, has_page_add_permission, get_page_valid_targets_queryset
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.db import models
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.utils.encoding import force_unicode, smart_str
from django.utils.translation import ugettext as _
from django.template import loader, Context, TemplateDoesNotExist
from django.template.loader_tags import ExtendsNode
# must be imported like this for isinstance
from django.templatetags.pages import PlaceholderNode
import settings
from mptt.exceptions import InvalidMove
from mptt.forms import MoveNodeForm

def get_placeholders(template_name):
    """Return a list of PlaceholderNode found in the given template"""
    try:
        temp = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return []
    temp.render(Context())
    list = []
    placeholders_recursif(temp.nodelist, list)
    return list

def placeholders_recursif(nodelist, list):
    """Recursively search into a template node list for PlaceholderNode node"""
    for node in nodelist:
        if isinstance(node, PlaceholderNode):
            list.append(node)
            node.render(Context())
        for key in ('nodelist', 'nodelist_true', 'nodelist_false'):
            if hasattr(node, key):
                try:
                    placeholders_recursif(getattr(node, key), list)
                except:
                    pass
    for node in nodelist:
        if isinstance(node, ExtendsNode):
            placeholders_recursif(node.get_parent(Context()).nodelist, list)

def get_form(request, dict=None, current_page=None):
    """Dynamicaly create a form to create/modify a page in the admin interface"""

    language_choices = settings.PAGE_LANGUAGES
    l = Language.get_from_request(request, current_page)
    if hasattr(settings, 'PAGE_TEMPLATES') and settings.PAGE_TEMPLATES:
        template_choices = list(settings.PAGE_TEMPLATES)
        template_choices.insert(0,('',_('Inherit')))
    else:
        template_choices = False

    class PageForm(forms.Form):
        slug = forms.CharField(widget=forms.TextInput(), required=True)
        title = forms.CharField(widget=forms.TextInput(), required=request.POST)
        language = forms.ChoiceField(choices=language_choices, initial=l)
        status = forms.ChoiceField(widget=forms.RadioSelect({'class':'radiolist'}), choices=Page.STATUSES)

        if settings.PAGE_TAGGING:
            from tagging.forms import TagField
            tags = TagField(required=False)

        if template_choices:
            template = forms.ChoiceField(choices=template_choices, required=False)

        def clean_slug(self):
            from django.template.defaultfilters import slugify
            slug = slugify(self.cleaned_data['slug'])
            if settings.PAGE_UNIQUE_SLUG_REQUIRED:
                if current_page and Page.objects.exclude(pk=current_page.id).filter(slug=slug):
                    raise forms.ValidationError('Another page with this slug already exists')
                if current_page is None and Page.objects.filter(slug=slug):
                    raise forms.ValidationError('Another page with this slug already exists')
            return slug

    from django.http import QueryDict

    if dict and type(dict) is not QueryDict:
        dict['language'] = l

    template = settings.DEFAULT_PAGE_TEMPLATE if current_page is None else current_page.get_template()
    for placeholder in get_placeholders(template):
        if placeholder.widget == 'TextInput':
            w = forms.TextInput()
        elif placeholder.widget == 'RichTextarea':
            w = forms.Textarea({'class':'rte'})
        else:
            w = forms.Textarea()
        if placeholder.name != "title":
            PageForm.base_fields[placeholder.name] = forms.CharField(widget=w, required=False)

    if dict:
        p = PageForm(dict)
    else:
        p = PageForm()

    return p

@staff_member_required
@auto_render
def add(request):
    """create a new page for a particular language"""
    if not has_page_add_permission(request):
        raise Http404
    opts = Page._meta
    app_label = _('Pages')
    add = True
    placeholders = get_placeholders(settings.DEFAULT_PAGE_TEMPLATE)
    if(request.POST):
        form = get_form(request, request.POST)
        if form.is_valid():
            status = form.cleaned_data['status']
            slug = form.cleaned_data['slug']
            template = form.cleaned_data.get('template', None)
            page = Page(author=request.user, status=status, slug=slug, template=template)
            page.save()
            if settings.PAGE_TAGGING:
                page.tags = form.cleaned_data['tags']

            language = form.cleaned_data['language']

            if "target" in request.GET:
                target = Page.objects.get(pk=int(request.GET["target"]))
                page.move_to(target, request.GET["position"])

            for placeholder in get_placeholders(page.get_template()):
                if placeholder.name in form.cleaned_data:
                    Content.set_or_create_content(page, language, placeholder.name, form.cleaned_data[placeholder.name])

            msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(page)}
            request.user.message_set.create(message=msg)

            return HttpResponseRedirect("../")
    else:
        form = get_form(request)

    return 'pages/change_form.html', locals()

@staff_member_required
@auto_render
def modify(request, page_id):
    """modifiy a page in a particular language"""
    opts = Page._meta
    app_label = _('Pages')
    change = True
    has_absolute_url = True
    from settings import MEDIA_URL
    page = Page.objects.get(pk=page_id)
    if not has_page_permission(request, page):
        raise Http404
    placeholders = get_placeholders(page.get_template())
    original = page

    if request.POST:

        form = get_form(request, request.POST, page)
        if form.is_valid():
            language = form.cleaned_data['language']
            page.status = form.cleaned_data['status']
            page.slug = form.cleaned_data['slug']
            page.template = form.cleaned_data.get('template', None)
            page.save()
            if settings.PAGE_TAGGING:
                page.tags = form.cleaned_data['tags']

            for placeholder in get_placeholders(page.get_template()):
                if placeholder.name in form.cleaned_data:
                    Content.set_or_create_content(page, language, placeholder.name, form.cleaned_data[placeholder.name])

            msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(page)}
            request.user.message_set.create(message=msg)
            return HttpResponseRedirect("../")
    else:
        l = Language.get_from_request(request)
        traduction_language = settings.PAGE_LANGUAGES
        if settings.PAGE_TAGGING:
            tag_list = ", ".join([str(t) for t in page.tags])
        else:
            tag_list = None
        dict = {'status':page.status, 'slug':page.slug, 'template':page.template, 'tags':tag_list}
        for placeholder in placeholders:
            dict[placeholder.name] = Content.get_content(page, l, placeholder.name)
        form = get_form(request, dict, page)

    return 'pages/change_form.html', locals()

@staff_member_required
@auto_render
def list_pages(request):
    """List root pages"""
    name = _("page")
    app_label = _('Pages')
    from settings import MEDIA_URL
    opts = Page._meta
    has_add_permission = has_page_add_permission(request)
    pages = Page.objects.filter(parent__isnull=True).order_by("tree_id")
    return 'pages/change_list.html', locals()

@staff_member_required
def valid_targets_list(request, page_id):
    """A list of valid targets to move a page"""
    page = Page.objects.get(pk=page_id)
    query = get_page_valid_targets_queryset(request, page)
    return HttpResponse(",".join([str(p.id) for p in query]))

@staff_member_required
def move_page(request, page_id):
    """Move the page to the requested target, at the given position"""
    page = Page.objects.get(pk=int(page_id))
    target = Page.objects.get(pk=int(request.POST['target']))
    page.move_to(target, request.POST['position'])
    return list_pages(request, template_name="pages/change_list_table.html")

@staff_member_required
def change_status(request, page_id):
    """Switch the status of a page"""
    if request.POST:
        page = Page.objects.get(pk=int(page_id))
        if page.status == 0:
            page.status = 1
            page.save()
        elif page.status == 1:
            page.status = 0
            page.save()
        return HttpResponse(page.status)
    else:
        raise Http404

@staff_member_required
@auto_render
def traduction(request, page_id, language_id):
    page = Page.objects.get(pk=page_id)
    context = {}
    lang = language_id
    placeholders = get_placeholders(page.get_template())
    print Content.get_content(page, language_id, "title")
    if Content.get_content(page, language_id, "title") is None:
        language_error = True
    return 'pages/traduction_helper.html', locals()
<commit_msg>Fix minor display bug<commit_after>from pages.utils import auto_render
from pages.models import Language, Content, Page, has_page_permission, has_page_add_permission, get_page_valid_targets_queryset
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.db import models
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.utils.encoding import force_unicode, smart_str
from django.utils.translation import ugettext as _
from django.template import loader, Context, TemplateDoesNotExist
from django.template.loader_tags import ExtendsNode
# must be imported like this for isinstance
from django.templatetags.pages import PlaceholderNode
import settings
from mptt.exceptions import InvalidMove
from mptt.forms import MoveNodeForm

def get_placeholders(template_name):
    """Return a list of PlaceholderNode found in the given template"""
    try:
        temp = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return []
    temp.render(Context())
    list = []
    placeholders_recursif(temp.nodelist, list)
    return list

def placeholders_recursif(nodelist, list):
    """Recursively search into a template node list for PlaceholderNode node"""
    for node in nodelist:
        if isinstance(node, PlaceholderNode):
            list.append(node)
            node.render(Context())
        for key in ('nodelist', 'nodelist_true', 'nodelist_false'):
            if hasattr(node, key):
                try:
                    placeholders_recursif(getattr(node, key), list)
                except:
                    pass
    for node in nodelist:
        if isinstance(node, ExtendsNode):
            placeholders_recursif(node.get_parent(Context()).nodelist, list)

def get_form(request, dict=None, current_page=None):
    """Dynamicaly create a form to create/modify a page in the admin interface"""

    language_choices = settings.PAGE_LANGUAGES
    l = Language.get_from_request(request, current_page)
    if hasattr(settings, 'PAGE_TEMPLATES') and settings.PAGE_TEMPLATES:
        template_choices = list(settings.PAGE_TEMPLATES)
        template_choices.insert(0,('',_('Inherit')))
    else:
        template_choices = False

    class PageForm(forms.Form):
        slug = forms.CharField(widget=forms.TextInput(), required=True)
        title = forms.CharField(widget=forms.TextInput(), required=request.POST)
        language = forms.ChoiceField(choices=language_choices, initial=l)
        status = forms.ChoiceField(widget=forms.RadioSelect({'class':'radiolist'}), choices=Page.STATUSES)

        if settings.PAGE_TAGGING:
            from tagging.forms import TagField
            tags = TagField(required=False)

        if template_choices:
            template = forms.ChoiceField(choices=template_choices, required=False)

        def clean_slug(self):
            from django.template.defaultfilters import slugify
            slug = slugify(self.cleaned_data['slug'])
            if settings.PAGE_UNIQUE_SLUG_REQUIRED:
                if current_page and Page.objects.exclude(pk=current_page.id).filter(slug=slug):
                    raise forms.ValidationError('Another page with this slug already exists')
                if current_page is None and Page.objects.filter(slug=slug):
                    raise forms.ValidationError('Another page with this slug already exists')
            return slug

    from django.http import QueryDict

    if dict and type(dict) is not QueryDict:
        dict['language'] = l

    template = settings.DEFAULT_PAGE_TEMPLATE if current_page is None else current_page.get_template()
    for placeholder in get_placeholders(template):
        if placeholder.widget == 'TextInput':
            w = forms.TextInput()
        elif placeholder.widget == 'RichTextarea':
            w = forms.Textarea({'class':'rte'})
        else:
            w = forms.Textarea()
        if placeholder.name != "title":
            PageForm.base_fields[placeholder.name] = forms.CharField(widget=w, required=False)

    if dict:
        p = PageForm(dict)
    else:
        p = PageForm()

    return p

@staff_member_required
@auto_render
def add(request):
    """create a new page for a particular language"""
    if not has_page_add_permission(request):
        raise Http404
    opts = Page._meta
    app_label = _('Pages')
    add = True
    from settings import MEDIA_URL
    placeholders = get_placeholders(settings.DEFAULT_PAGE_TEMPLATE)
    if(request.POST):
        form = get_form(request, request.POST)
        if form.is_valid():
            status = form.cleaned_data['status']
            slug = form.cleaned_data['slug']
            template = form.cleaned_data.get('template', None)
            page = Page(author=request.user, status=status, slug=slug, template=template)
            page.save()
            if settings.PAGE_TAGGING:
                page.tags = form.cleaned_data['tags']

            language = form.cleaned_data['language']

            if "target" in request.GET:
                target = Page.objects.get(pk=int(request.GET["target"]))
                page.move_to(target, request.GET["position"])

            for placeholder in get_placeholders(page.get_template()):
                if placeholder.name in form.cleaned_data:
                    Content.set_or_create_content(page, language, placeholder.name, form.cleaned_data[placeholder.name])

            msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(page)}
            request.user.message_set.create(message=msg)

            return HttpResponseRedirect("../")
    else:
        form = get_form(request)

    return 'pages/change_form.html', locals()

@staff_member_required
@auto_render
def modify(request, page_id):
    """modifiy a page in a particular language"""
    opts = Page._meta
    app_label = _('Pages')
    change = True
    has_absolute_url = True
    from settings import MEDIA_URL
    page = Page.objects.get(pk=page_id)
    if not has_page_permission(request, page):
        raise Http404
    placeholders = get_placeholders(page.get_template())
    original = page

    if request.POST:

        form = get_form(request, request.POST, page)
        if form.is_valid():
            language = form.cleaned_data['language']
            page.status = form.cleaned_data['status']
            page.slug = form.cleaned_data['slug']
            page.template = form.cleaned_data.get('template', None)
            page.save()
            if settings.PAGE_TAGGING:
                page.tags = form.cleaned_data['tags']

            for placeholder in get_placeholders(page.get_template()):
                if placeholder.name in form.cleaned_data:
                    Content.set_or_create_content(page, language, placeholder.name, form.cleaned_data[placeholder.name])

            msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(page)}
            request.user.message_set.create(message=msg)
            return HttpResponseRedirect("../")
    else:
        l = Language.get_from_request(request)
        traduction_language = settings.PAGE_LANGUAGES
        if settings.PAGE_TAGGING:
            tag_list = ", ".join([str(t) for t in page.tags])
        else:
            tag_list = None
        dict = {'status':page.status, 'slug':page.slug, 'template':page.template, 'tags':tag_list}
        for placeholder in placeholders:
            dict[placeholder.name] = Content.get_content(page, l, placeholder.name)
        form = get_form(request, dict, page)

    return 'pages/change_form.html', locals()

@staff_member_required
@auto_render
def list_pages(request):
    """List root pages"""
    name = _("page")
    app_label = _('Pages')
    from settings import MEDIA_URL
    opts = Page._meta
    has_add_permission = has_page_add_permission(request)
    pages = Page.objects.filter(parent__isnull=True).order_by("tree_id")
    return 'pages/change_list.html', locals()

@staff_member_required
def valid_targets_list(request, page_id):
    """A list of valid targets to move a page"""
    page = Page.objects.get(pk=page_id)
    query = get_page_valid_targets_queryset(request, page)
    return HttpResponse(",".join([str(p.id) for p in query]))

@staff_member_required
def move_page(request, page_id):
    """Move the page to the requested target, at the given position"""
    page = Page.objects.get(pk=int(page_id))
    target = Page.objects.get(pk=int(request.POST['target']))
    page.move_to(target, request.POST['position'])
    return list_pages(request, template_name="pages/change_list_table.html")

@staff_member_required
def change_status(request, page_id):
    """Switch the status of a page"""
    if request.POST:
        page = Page.objects.get(pk=int(page_id))
        if page.status == 0:
            page.status = 1
            page.save()
        elif page.status == 1:
            page.status = 0
            page.save()
        return HttpResponse(page.status)
    else:
        raise Http404

@staff_member_required
@auto_render
def traduction(request, page_id, language_id):
    page = Page.objects.get(pk=page_id)
    context = {}
    lang = language_id
    placeholders = get_placeholders(page.get_template())
    print Content.get_content(page, language_id, "title")
    if Content.get_content(page, language_id, "title") is None:
        language_error = True
    return 'pages/traduction_helper.html', locals()
<|endoftext|>


<commit_before>import sublime
import sublime_plugin

# Class to make Find matching easier
class Finder:
    # TODO: Is this how constructors work in Python?
    def __init__(self, settings):
        # Save settings for later
        # TODO: We might just read directly from settings?
        self.settings = settings

    def find(self, view):
        pass

# DEV: On focus of a window, give me an error message
class FindPlusPlus(sublime_plugin.EventListener):
    def on_activated(self, view):
        # If this is a FindPlusPlus.py
        file_name = view.file_name()
        if file_name.endswith('FindPlusPlus.py'):
            print 'yep'

#         print "focus gained"
#         a = FindResults('hey')
#         pass

# TODO: Class for searching options

# Class to handle find results
class FindResults:
    def __init__(self, settings):
        # TODO: All actions inside of init should be methods themself?
        # Get the window
        window = self.get_window()

        # Get a panel
        results = window.get_output_panel('FindPPResults')

        # Open the panel
        window.run_command('show_panel', 'output.FindPPResults')
        pass

    def get_window(self):
        return sublime.active_window()
<commit_msg>Stopped previous recursion issue but output panel isn't appearing =(<commit_after>import sublime
import sublime_plugin

# Class to make Find matching easier
class Finder:
    # TODO: Is this how constructors work in Python?
    def __init__(self, settings):
        # Save settings for later
        # TODO: We might just read directly from settings?
        self.settings = settings

    def find(self, view):
        pass

# DEV: On focus of a window, give me an error message
class FindPlusPlus(sublime_plugin.EventListener):
    def on_activated(self, view):
        # If this is a FindPlusPlus.py
        file_name = view.file_name() or ''
        if file_name.endswith('FindPlusPlus.py'):
            print "focus gained"
            a = FindResults('hey')
            pass

# TODO: Class for searching options

# Class to handle find results
class FindResults:
    def __init__(self, settings):
        # TODO: All actions inside of init should be methods themself?
        # Get the window
        window = self.get_window()

        # Get a panel
        results = window.get_output_panel('FindPPResults')

        # Open the panel
        window.run_command('show_panel', 'output.FindPPResults')
        pass

    def get_window(self):
        return sublime.active_window()
<|endoftext|>


<commit_before>import numpy as np

def bow_vector(doc, word_to_id, unknown_id=0, dtype=np.int32):
    vec = np.zeros(len(word_to_id), dtype=dtype)  # Initialize BOW vector
    for word in doc:
        vec[word_to_id.get(word, unknown_id)] += 1
    return vec

<commit_msg>DOCS: NLP: Add docstring for `bow_vector()`<commit_after>import numpy as np

# ==============================================================================
#                                                            BAG OF WORDS VECTOR
# ==============================================================================
def bow_vector(doc, word_to_id, unknown_id=0, dtype=np.int32):
    """ Given a list of words `sentence` and the dictionary that maps words in
        the vocab to an array index, it returns an array which is
        a bag of words representation of that sentence.

        NOTE: Any words that are not in the vocabulary are assigned by
              default to the 0th index of the BOW. Change the `unknown_id`
              argument to set to a different index.

    Args:
        doc: (list of strings)
            List of words in the sentence, paragraph or document you wish to
            represent as a BoW vector.
        word_to_id: (dict)
            The dictionary that maps word strings to indices that will represent
            those words.
        unknown_id: (int, optional)(default=0)
            The index to use to represent words that do not appear in the
            vocabulary.
        dtype: (optional)(defualt=np.int32)
            The data type to use for the output array.

    Returns: (numpy array)
    """
    vec = np.zeros(len(word_to_id), dtype=dtype)  # Initialize BOW vector
    for word in doc:
        vec[word_to_id.get(word, unknown_id)] += 1
    return vec

<|endoftext|>


<commit_before>#!/usr/bin/env python
import sys
import _PyV8

class JSClass(object):
    def toString(self):
        "Returns a string representation of an object."
        return "[object %s]" % self.__class__.__name__

    def toLocaleString(self):
        "Returns a value as a string value appropriate to the host environment's current locale."
        return self.toString()

    def valueOf(self):
        "Returns the primitive value of the specified object."
        return self

    def hasOwnProperty(self, name):
        "Returns a Boolean value indicating whether an object has a property with the specified name."
        return hasattr(self, name)

    def isPrototypeOf(self, obj):
        "Returns a Boolean value indicating whether an object exists in the prototype chain of another object."
        raise NotImplementedError()

    def __defineGetter__(self, name, getter):
        "Binds an object's property to a function to be called when that property is looked up."
        if hasattr(self, name):
            setter = getattr(self, name).fset
        else:
            setter = None

        setattr(self, name, property(fget=getter, fset=setter))

    def __lookupGetter__(self, name):
        "Return the function bound as a getter to the specified property."
        return self.name.fget

    def __defineSetter__(self, name, setter):
        "Binds an object's property to a function to be called when an attempt is made to set that property."
        if hasattr(self, name):
            getter = getattr(self, name).fget
        else:
            getter = None

        setattr(self, name, property(fget=getter, fset=setter))

    def __lookupSetter__(self, name):
        "Return the function bound as a setter to the specified property."
        return self.name.fset

class JSDebug(object):
    class DebugEvent(object):
        def __init__(self, type, event):
            self.type = type
            self.event = event

    class BreakEvent(DebugEvent):
        def __init__(self, event):
            JSDebug.DebugEvent.__init__(self, _PyV8.JSDebugEvent.Break, event)

    class ExceptionEvent(DebugEvent):
        def __init__(self, event):
            JSDebug.DebugEvent.__init__(self, _PyV8.JSDebugEvent.Exception, event)

    class NewFunctionEvent(DebugEvent):
        def __init__(self, event):
            JSDebug.DebugEvent.__init__(self, _PyV8.JSDebugEvent.NewFunction, event)

    class CompileEvent(DebugEvent):
        def __init__(self, type, event):
            JSDebug.DebugEvent.__init__(self, type, event)

        @property
        def source(self):
            return str(self.event.script())

        def __str__(self):
            return self.source

    class BeforeCompileEvent(CompileEvent):
        def __init__(self, event):
            JSDebug.CompileEvent.__init__(self, _PyV8.JSDebugEvent.BeforeCompile, event)

        def __repr__(self):
            return "before compile script: " + self.source

    class AfterCompileEvent(CompileEvent):
        def __init__(self, event):
            JSDebug.CompileEvent.__init__(self, _PyV8.JSDebugEvent.AfterCompile, event)

        def __repr__(self):
            return "after compile script: " + self.source

    onMessage = None
    onBreak = None
    onException = None
    onNewFunction = None
    onBeforeCompile = None
    onAfterCompile = None

    def isEnabled(self):
        return _PyV8.debug().enabled

    def setEnabled(self, enable):
        dbg = _PyV8.debug()

        if enable:
            dbg.onDebugEvent = lambda type, evt: self.onDebugEvent(type, evt)
            dbg.onDebugMessage = lambda msg: self.onDebugMessage(msg)
        else:
            dbg.onDebugEvent = None
            dbg.onDebugMessage = None

        dbg.enabled = enable

    enabled = property(isEnabled, setEnabled)

    def onDebugMessage(self, msg):
        if self.onMessage:
            self.onMessage(msg)

    def onDebugEvent(self, type, evt):
        if type == _PyV8.JSDebugEvent.Break:
            if self.onBreak: self.onBreak(JSDebug.BreakEvent(evt))
        elif type == _PyV8.JSDebugEvent.Exception:
            if self.onException: self.onException(JSDebug.ExceptionEvent(evt))
        elif type == _PyV8.JSDebugEvent.NewFunction:
            if self.onNewFunction: self.onNewFunction(JSDebug.NewFunctionEvent(evt))
        elif type == _PyV8.JSDebugEvent.BeforeCompile:
            if self.onBeforeCompile: self.onBeforeCompile(JSDebug.BeforeCompileEvent(evt))
        elif type == _PyV8.JSDebugEvent.AfterCompile:
            if self.onAfterCompile: self.onAfterCompile(JSDebug.AfterCompileEvent(evt))

debugger = JSDebug()

JSEngine = _PyV8.JSEngine

import unittest

class TestWrapper(unittest.TestCase):
    def setUp(self):
        self.engine = JSEngine()

    def tearDown(self):
        del self.engine

    def testConverter(self):
        self.engine.eval("""
            var_i = 1;
            var_f = 1.0;
            var_s = "test";
            var_b = true;
        """)

        var_i = self.engine.context.var_i

        self.assert_(var_i)
        self.assertEquals(1, int(var_i))

        var_f = self.engine.context.var_f

        self.assert_(var_f)
        self.assertEquals(1.0, float(self.engine.context.var_f))

        var_s = self.engine.context.var_s
        self.assert_(var_s)
        self.assertEquals("test", str(self.engine.context.var_s))

        var_b = self.engine.context.var_b
        self.assert_(var_b)
        self.assert_(bool(var_b))

class TestEngine(unittest.TestCase):
    def testClassProperties(self):
        self.assertEquals("1.0.1", JSEngine.version)

    def testCompile(self):
        engine = JSEngine()

        try:
            s = engine.compile("1+2")

            self.assertEquals("1+2", s.source)
            self.assertEquals(3, int(s.run()))
        finally:
            del engine

    def testExec(self):
        engine = JSEngine()

        try:
            self.assertEquals(3, int(engine.eval("1+2")))
        finally:
            del engine

    def testGlobal(self):
        class Global(object):
            version = "1.0"

        engine = JSEngine(Global())

        try:
            # getter
            self.assertEquals(Global.version, str(engine.context.version))
            self.assertEquals(Global.version, str(engine.eval("version")))

            self.assertRaises(UserWarning, JSEngine.eval, engine, "nonexists")

            # setter
            self.assertEquals(2.0, float(engine.eval("version = 2.0")))

            self.assertEquals(2.0, float(engine.context.version))
        finally:
            del engine

    def testThis(self):
        class Global(object):
            version = 1.0

        engine = JSEngine(Global())

        try:
            self.assertEquals("[object global]", str(engine.eval("this")))

            self.assertEquals(1.0, float(engine.eval("this.version")))
        finally:
            del engine

    def testObjectBuildInMethods(self):
        class Global(JSClass):
            version = 1.0

        engine = JSEngine(Global())

        try:
            self.assertEquals("[object Global]", str(engine.eval("this.toString()")))
            self.assertEquals("[object Global]", str(engine.eval("this.toLocaleString()")))
            self.assertEquals(Global.version, float(engine.eval("this.valueOf()").version))
            self.assert_(bool(engine.eval("this.hasOwnProperty(\"version\")")))

            ret = engine.eval("this.hasOwnProperty(\"nonexistent\")")

            self.assertEquals("valueOf", ret.valueOf.func_name)
            self.assertEquals(ret, ret.valueOf.func_owner)
            self.assertEquals("false", str(ret.valueOf()))
        finally:
            del engine

class TestDebug(unittest.TestCase):
    def setUp(self):
        self.engine = JSEngine()

    def tearDown(self):
        del self.engine

    def testEventDispatch(self):
        global debugger

        self.assert_(not debugger.enabled)

        events = []

        debugger.onBreak = lambda evt: events.append(repr(evt))
        debugger.onException = lambda evt: events.append(repr(evt))
        debugger.onNewFunction = lambda evt: events.append(repr(evt))
        debugger.onBeforeCompile = lambda evt: events.append(repr(evt))
        debugger.onAfterCompile = lambda evt: events.append(repr(evt))

        engine = JSEngine()

        try:
            debugger.enabled = True

            self.assertEquals(3, int(engine.eval("eval(\"1+2\")")))

            debugger.enabled = False

            self.assertRaises(UserWarning, JSEngine.eval, engine, "throw 1")

            self.assert_(not debugger.enabled)
        finally:
            del engine

if __name__ == '__main__':
    unittest.main()<commit_msg>support to fetch script source information in the compile event<commit_after>#!/usr/bin/env python
import sys
import _PyV8

class JSClass(object):
    def toString(self):
        "Returns a string representation of an object."
        return "[object %s]" % self.__class__.__name__

    def toLocaleString(self):
        "Returns a value as a string value appropriate to the host environment's current locale."
        return self.toString()

    def valueOf(self):
        "Returns the primitive value of the specified object."
        return self

    def hasOwnProperty(self, name):
        "Returns a Boolean value indicating whether an object has a property with the specified name."
        return hasattr(self, name)

    def isPrototypeOf(self, obj):
        "Returns a Boolean value indicating whether an object exists in the prototype chain of another object."
        raise NotImplementedError()

    def __defineGetter__(self, name, getter):
        "Binds an object's property to a function to be called when that property is looked up."
        if hasattr(self, name):
            setter = getattr(self, name).fset
        else:
            setter = None

        setattr(self, name, property(fget=getter, fset=setter))

    def __lookupGetter__(self, name):
        "Return the function bound as a getter to the specified property."
        return self.name.fget

    def __defineSetter__(self, name, setter):
        "Binds an object's property to a function to be called when an attempt is made to set that property."
        if hasattr(self, name):
            getter = getattr(self, name).fget
        else:
            getter = None

        setattr(self, name, property(fget=getter, fset=setter))

    def __lookupSetter__(self, name):
        "Return the function bound as a setter to the specified property."
        return self.name.fset

class JSDebug(object):
    class DebugEvent(object):
        def __init__(self, type, event):
            self.type = type
            self.event = event

    class BreakEvent(DebugEvent):
        def __init__(self, event):
            JSDebug.DebugEvent.__init__(self, _PyV8.JSDebugEvent.Break, event)

    class ExceptionEvent(DebugEvent):
        def __init__(self, event):
            JSDebug.DebugEvent.__init__(self, _PyV8.JSDebugEvent.Exception, event)

    class NewFunctionEvent(DebugEvent):
        def __init__(self, event):
            JSDebug.DebugEvent.__init__(self, _PyV8.JSDebugEvent.NewFunction, event)

    class JSScript(object):
        Native = 0
        Extension = 1
        Normal = 2

        def __init__(self, script):
            self.script = script

        @property
        def source(self):
            return str(self.script.source())

        @property
        def name(self):
            return str(self.script.name()) if hasattr(self.script, "name") else None

        @property
        def line(self):
            return int(self.script.line_offset().value()) if hasattr(self.script, "line_offset") else -1;

        @property
        def column(self):
            return int(self.script.column_offset().value()) if hasattr(self.script, "column_offset") else -1;

        @property
        def type(self):
            return int(self.script.type())

        @property
        def typename(self):
            NAMES = {
                JSDebug.JSScript.Native : "native",
                JSDebug.JSScript.Extension : "extension",
                JSDebug.JSScript.Normal : "normal"
            }

            return NAMES[self.type]

        def __str__(self):
            return "<%s script %s @ %d:%d> : %s" % (self.typename, self.name,
                                                    self.line, self.column,
                                                    self.source)

    class CompileEvent(DebugEvent):
        def __init__(self, type, event):
            JSDebug.DebugEvent.__init__(self, type, event)

        __script = None

        @property
        def script(self):
            if not self.__script:
                self.__script = JSDebug.JSScript(self.event.script())

            return self.__script

        def __str__(self):
            return str(self.script)

    class BeforeCompileEvent(CompileEvent):
        def __init__(self, event):
            JSDebug.CompileEvent.__init__(self, _PyV8.JSDebugEvent.BeforeCompile, event)

        def __repr__(self):
            return "before compile script: " + str(self.script)

    class AfterCompileEvent(CompileEvent):
        def __init__(self, event):
            JSDebug.CompileEvent.__init__(self, _PyV8.JSDebugEvent.AfterCompile, event)

        def __repr__(self):
            return "after compile script: " + str(self.script)

    onMessage = None
    onBreak = None
    onException = None
    onNewFunction = None
    onBeforeCompile = None
    onAfterCompile = None

    def isEnabled(self):
        return _PyV8.debug().enabled

    def setEnabled(self, enable):
        dbg = _PyV8.debug()

        if enable:
            dbg.onDebugEvent = lambda type, evt: self.onDebugEvent(type, evt)
            dbg.onDebugMessage = lambda msg: self.onDebugMessage(msg)
        else:
            dbg.onDebugEvent = None
            dbg.onDebugMessage = None

        dbg.enabled = enable

    enabled = property(isEnabled, setEnabled)

    def onDebugMessage(self, msg):
        if self.onMessage:
            self.onMessage(msg)

    def onDebugEvent(self, type, evt):
        if type == _PyV8.JSDebugEvent.Break:
            if self.onBreak: self.onBreak(JSDebug.BreakEvent(evt))
        elif type == _PyV8.JSDebugEvent.Exception:
            if self.onException: self.onException(JSDebug.ExceptionEvent(evt))
        elif type == _PyV8.JSDebugEvent.NewFunction:
            if self.onNewFunction: self.onNewFunction(JSDebug.NewFunctionEvent(evt))
        elif type == _PyV8.JSDebugEvent.BeforeCompile:
            if self.onBeforeCompile: self.onBeforeCompile(JSDebug.BeforeCompileEvent(evt))
        elif type == _PyV8.JSDebugEvent.AfterCompile:
            if self.onAfterCompile: self.onAfterCompile(JSDebug.AfterCompileEvent(evt))

debugger = JSDebug()

JSEngine = _PyV8.JSEngine

import unittest
import logging

class TestWrapper(unittest.TestCase):
    def setUp(self):
        self.engine = JSEngine()

    def tearDown(self):
        del self.engine

    def testConverter(self):
        self.engine.eval("""
            var_i = 1;
            var_f = 1.0;
            var_s = "test";
            var_b = true;
        """)

        var_i = self.engine.context.var_i

        self.assert_(var_i)
        self.assertEquals(1, int(var_i))

        var_f = self.engine.context.var_f

        self.assert_(var_f)
        self.assertEquals(1.0, float(self.engine.context.var_f))

        var_s = self.engine.context.var_s
        self.assert_(var_s)
        self.assertEquals("test", str(self.engine.context.var_s))

        var_b = self.engine.context.var_b
        self.assert_(var_b)
        self.assert_(bool(var_b))

class TestEngine(unittest.TestCase):
    def testClassProperties(self):
        self.assertEquals("1.0.1", JSEngine.version)

    def testCompile(self):
        engine = JSEngine()

        try:
            s = engine.compile("1+2")

            self.assertEquals("1+2", s.source)
            self.assertEquals(3, int(s.run()))
        finally:
            del engine

    def testExec(self):
        engine = JSEngine()

        try:
            self.assertEquals(3, int(engine.eval("1+2")))
        finally:
            del engine

    def testGlobal(self):
        class Global(object):
            version = "1.0"

        engine = JSEngine(Global())

        try:
            # getter
            self.assertEquals(Global.version, str(engine.context.version))
            self.assertEquals(Global.version, str(engine.eval("version")))

            self.assertRaises(UserWarning, JSEngine.eval, engine, "nonexists")

            # setter
            self.assertEquals(2.0, float(engine.eval("version = 2.0")))

            self.assertEquals(2.0, float(engine.context.version))
        finally:
            del engine

    def testThis(self):
        class Global(object):
            version = 1.0

        engine = JSEngine(Global())

        try:
            self.assertEquals("[object global]", str(engine.eval("this")))

            self.assertEquals(1.0, float(engine.eval("this.version")))
        finally:
            del engine

    def testObjectBuildInMethods(self):
        class Global(JSClass):
            version = 1.0

        engine = JSEngine(Global())

        try:
            self.assertEquals("[object Global]", str(engine.eval("this.toString()")))
            self.assertEquals("[object Global]", str(engine.eval("this.toLocaleString()")))
            self.assertEquals(Global.version, float(engine.eval("this.valueOf()").version))
            self.assert_(bool(engine.eval("this.hasOwnProperty(\"version\")")))

            ret = engine.eval("this.hasOwnProperty(\"nonexistent\")")

            self.assertEquals("valueOf", ret.valueOf.func_name)
            self.assertEquals(ret, ret.valueOf.func_owner)
            self.assertEquals("false", str(ret.valueOf()))
        finally:
            del engine

class TestDebug(unittest.TestCase):
    def setUp(self):
        self.engine = JSEngine()

    def tearDown(self):
        del self.engine

    events = []

    def processDebugEvent(self, event):
        try:
            logging.debug("receive debug event: %s", repr(event))

            self.events.append(repr(event))
        except:
            logging.error(sys.exc_info())

    def testEventDispatch(self):
        global debugger

        self.assert_(not debugger.enabled)

        debugger.onBreak = lambda evt: self.processDebugEvent(evt)
        debugger.onException = lambda evt: self.processDebugEvent(evt)
        debugger.onNewFunction = lambda evt: self.processDebugEvent(evt)
        debugger.onBeforeCompile = lambda evt: self.processDebugEvent(evt)
        debugger.onAfterCompile = lambda evt: self.processDebugEvent(evt)

        engine = JSEngine()

        try:
            debugger.enabled = True

            self.assertEquals(3, int(engine.eval("eval(\"1+2\")")))

            debugger.enabled = False

            self.assertRaises(UserWarning, JSEngine.eval, engine, "throw 1")

            self.assert_(not debugger.enabled)
        finally:
            del engine

        self.assertEquals(4, len(self.events))

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG if "-v" in sys.argv else logging.WARN,
                        format='%(asctime)s %(levelname)s %(message)s')

    unittest.main()<|endoftext|>