<commit_before>from __future__ import unicode_literals

import re
import warnings
import json

from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib import messages
from django.contrib.auth import login as django_login
from django.contrib.auth import logout as django_logout

try:
    from django.utils.encoding import force_text
except ImportError:
    from django.utils.encoding import force_unicode as force_text

from ..utils import (import_attribute, get_user_model,
                     generate_unique_username,
                     resolve_url, get_current_site,
                     build_absolute_uri)

from . import app_settings

# Don't bother turning this into a setting, as changing this also
# requires changing the accompanying form error message. So if you
# need to change any of this, simply override clean_username().
USERNAME_REGEX = re.compile(r'^[\w.@+-]+$', re.UNICODE)

class DefaultAccountAdapter(object):

    def stash_verified_email(self, request, email):
        request.session['account_verified_email'] = email

    def unstash_verified_email(self, request):
        ret = request.session.get('account_verified_email')
        request.session['account_verified_email'] = None
        return ret

    def stash_user(self, request, user):
        request.session['account_user'] = user

    def unstash_user(self, request):
        return request.session.pop('account_user', None)

    def is_email_verified(self, request, email):
        """
        Checks whether or not the email address is already verified
        beyond allauth scope, for example, by having accepted an
        invitation before signing up.
        """
        ret = False
        verified_email = request.session.get('account_verified_email')
        if verified_email:
            ret = verified_email.lower() == email.lower()
        return ret

    def format_email_subject(self, subject):
        prefix = app_settings.EMAIL_SUBJECT_PREFIX
        if prefix is None:
            site = get_current_site()
            prefix = "[{name}] ".format(name=site.name)
        return prefix + force_text(subject)

    def render_mail(self, template_prefix, email, context):
        """
        Renders an e-mail to `email`.  `template_prefix` identifies the
        e-mail that is to be sent, e.g. "account/email/email_confirmation"
        """
        subject = render_to_string('{0}_subject.txt'.format(template_prefix),
                                   context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()
        subject = self.format_email_subject(subject)

        bodies = {}
        for ext in ['html', 'txt']:
            try:
                template_name = '{0}_message.{1}'.format(template_prefix, ext)
                bodies[ext] = render_to_string(template_name,
                                               context).strip()
            except TemplateDoesNotExist:
                if ext == 'txt' and not bodies:
                    # We need at least one body
                    raise
        if 'txt' in bodies:
            msg = EmailMultiAlternatives(subject,
                                         bodies['txt'],
                                         settings.DEFAULT_FROM_EMAIL,
                                         [email])
            if 'html' in bodies:
                msg.attach_alternative(bodies['html'], 'text/html')
        else:
            msg = EmailMessage(subject,
                               bodies['html'],
                               settings.DEFAULT_FROM_EMAIL,
                               [email])
            msg.content_subtype = 'html'  # Main content is now text/html
        return msg

    def send_mail(self, template_prefix, email, context):
        msg = self.render_mail(template_prefix, email, context)
        msg.send()

    def get_login_redirect_url(self, request):
        """
        Returns the default URL to redirect to after logging in.  Note
        that URLs passed explicitly (e.g. by passing along a `next`
        GET parameter) take precedence over the value returned here.
        """
        assert request.user.is_authenticated()
        url = getattr(settings, "LOGIN_REDIRECT_URLNAME", None)
        if url:
            warnings.warn("LOGIN_REDIRECT_URLNAME is deprecated, simply"
                          " use LOGIN_REDIRECT_URL with a URL name",
                          DeprecationWarning)
        else:
            url = settings.LOGIN_REDIRECT_URL
        return resolve_url(url)

    def get_logout_redirect_url(self, request):
        """
        Returns the URL to redirect to after the user logs out. Note that
        this method is also invoked if you attempt to log out while no users
        is logged in. Therefore, request.user is not guaranteed to be an
        authenticated user.
        """
        return resolve_url(app_settings.LOGOUT_REDIRECT_URL)

    def get_email_confirmation_redirect_url(self, request):
        """
        The URL to return to after successful e-mail confirmation.
        """
        if request.user.is_authenticated():
            if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL:
                return  \
                    app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
            else:
                return self.get_login_redirect_url(request)
        else:
            return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL

    def is_open_for_signup(self, request):
        """
        Checks whether or not the site is open for signups.

        Next to simply returning True/False you can also intervene the
        regular flow by raising an ImmediateHttpResponse
        """
        return True

    def new_user(self, request):
        """
        Instantiates a new User instance.
        """
        user = get_user_model()()
        return user

    def populate_username(self, request, user):
        """
        Fills in a valid username, if required and missing.  If the
        username is already present it is assumed to be valid
        (unique).
        """
        from .utils import user_username, user_email, user_field
        first_name = user_field(user, 'first_name')
        last_name = user_field(user, 'last_name')
        email = user_email(user)
        username = user_username(user)
        if app_settings.USER_MODEL_USERNAME_FIELD:
            user_username(user,
                          username
                          or self.generate_unique_username([first_name,
                                                            last_name,
                                                            email,
                                                            'user']))

    def generate_unique_username(self, txts, regex=None):
        return generate_unique_username(txts, regex)

    def save_user(self, request, user, form, commit=True):
        """
        Saves a new `User` instance using information provided in the
        signup form.
        """
        from .utils import user_username, user_email, user_field

        data = form.cleaned_data
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        username = data.get('username')
        user_email(user, email)
        user_username(user, username)
        if first_name:
            user_field(user, 'first_name', first_name)
        if last_name:
            user_field(user, 'last_name', last_name)
        if 'password1' in data:
            user.set_password(data["password1"])
        else:
            user.set_unusable_password()
        self.populate_username(request, user)
        if commit:
            # Ability not to commit makes it easier to derive from
            # this adapter by adding
            user.save()
        return user

    def clean_username(self, username, shallow=False):
        """
        Validates the username. You can hook into this if you want to
        (dynamically) restrict what usernames can be chosen.
        """
        if not USERNAME_REGEX.match(username):
            raise forms.ValidationError(_("Usernames can only contain "
                                          "letters, digits and @/./+/-/_."))

        # TODO: Add regexp support to USERNAME_BLACKLIST
        username_blacklist_lower = [ub.lower()
                                    for ub in app_settings.USERNAME_BLACKLIST]
        if username.lower() in username_blacklist_lower:
            raise forms.ValidationError(_("Username can not be used. "
                                          "Please use other username."))
        # Skipping database lookups when shallow is True, needed for unique
        # username generation.
        if not shallow:
            username_field = app_settings.USER_MODEL_USERNAME_FIELD
            assert username_field
            user_model = get_user_model()
            try:
                query = {username_field + '__iexact': username}
                user_model.objects.get(**query)
            except user_model.DoesNotExist:
                return username
            raise forms.ValidationError(
                _("This username is already taken. Please choose another."))
        return username

    def clean_email(self, email):
        """
        Validates an email value. You can hook into this if you want to
        (dynamically) restrict what email addresses can be chosen.
        """
        return email

    def clean_password(self, password):
        """
        Validates a password. You can hook into this if you want to
        restric the allowed password choices.
        """
        min_length = app_settings.PASSWORD_MIN_LENGTH
        if len(password) < min_length:
            raise forms.ValidationError(_("Password must be a minimum of {0} "
                                          "characters.").format(min_length))
        return password

    def add_message(self, request, level, message_template,
                    message_context=None, extra_tags=''):
        """
        Wrapper of `django.contrib.messages.add_message`, that reads
        the message text from a template.
        """
        if 'django.contrib.messages' in settings.INSTALLED_APPS:
            try:
                if message_context is None:
                    message_context = {}
                message = render_to_string(message_template,
                                           message_context).strip()
                if message:
                    messages.add_message(request, level, message,
                                         extra_tags=extra_tags)
            except TemplateDoesNotExist:
                pass

    def ajax_response(self, request, response, redirect_to=None, form=None):
        data = {}
        status = response.status_code

        if redirect_to:
            status = 200
            data['location'] = redirect_to
        if form:
            if form.is_valid():
                status = 200
            else:
                status = 400
                data['form_errors'] = form._errors
            if hasattr(response, 'render'):
                response.render()
            data['html'] = response.content.decode('utf8')
        return HttpResponse(json.dumps(data),
                            status=status,
                            content_type='application/json')

    def login(self, request, user):
        # HACK: This is not nice. The proper Django way is to use an
        # authentication backend
        if not hasattr(user, 'backend'):
            user.backend \
                = "allauth.account.auth_backends.AuthenticationBackend"
        django_login(request, user)

    def logout(self, request):
        django_logout(request)

    def confirm_email(self, request, email_address):
        """
        Marks the email address as confirmed on the db
        """
        email_address.verified = True
        email_address.set_as_primary(conditional=True)
        email_address.save()

    def set_password(self, user, password):
        user.set_password(password)
        user.save()

    def get_user_search_fields(self):
        user = get_user_model()()
        return filter(lambda a: a and hasattr(user, a),
                      [app_settings.USER_MODEL_USERNAME_FIELD,
                       'first_name', 'last_name', 'email'])

    def is_safe_url(self, url):
        from django.utils.http import is_safe_url
        return is_safe_url(url)

    def get_email_confirmation_url(self, request, emailconfirmation):
        """Constructs the email confirmation (activation) url.

        Note that if you have architected your system such that email
        confirmations are sent outside of the request context `request`
        can be `None` here.
        """
        url = reverse(
            "account_confirm_email",
            args=[emailconfirmation.key])
        ret = build_absolute_uri(
            request,
            url,
            protocol=app_settings.DEFAULT_HTTP_PROTOCOL)
        return ret

    def send_confirmation_mail(self, request, emailconfirmation, signup):
        current_site = get_current_site(request)
        activate_url = self.get_email_confirmation_url(
            request,
            emailconfirmation)
        ctx = {
            "user": emailconfirmation.email_address.user,
            "activate_url": activate_url,
            "current_site": current_site,
            "key": emailconfirmation.key,
        }
        if signup:
            email_template = 'account/email/email_confirmation_signup'
        else:
            email_template = 'account/email/email_confirmation'
        self.send_mail(email_template,
                       emailconfirmation.email_address.email,
                       ctx)

def get_adapter():
    return import_attribute(app_settings.ADAPTER)()
<commit_msg>Fixed formatting email subject in multisite environment.<commit_after>from __future__ import unicode_literals

import re
import warnings
import json

from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib import messages
from django.contrib.auth import login as django_login
from django.contrib.auth import logout as django_logout

try:
    from django.utils.encoding import force_text
except ImportError:
    from django.utils.encoding import force_unicode as force_text

from ..utils import (import_attribute, get_user_model,
                     generate_unique_username,
                     resolve_url, get_current_site,
                     build_absolute_uri)

from . import app_settings

# Don't bother turning this into a setting, as changing this also
# requires changing the accompanying form error message. So if you
# need to change any of this, simply override clean_username().
USERNAME_REGEX = re.compile(r'^[\w.@+-]+$', re.UNICODE)

class DefaultAccountAdapter(object):

    def stash_verified_email(self, request, email):
        request.session['account_verified_email'] = email

    def unstash_verified_email(self, request):
        ret = request.session.get('account_verified_email')
        request.session['account_verified_email'] = None
        return ret

    def stash_user(self, request, user):
        request.session['account_user'] = user

    def unstash_user(self, request):
        return request.session.pop('account_user', None)

    def is_email_verified(self, request, email):
        """
        Checks whether or not the email address is already verified
        beyond allauth scope, for example, by having accepted an
        invitation before signing up.
        """
        ret = False
        verified_email = request.session.get('account_verified_email')
        if verified_email:
            ret = verified_email.lower() == email.lower()
        return ret

    def format_email_subject(self, subject, context=None):
        prefix = app_settings.EMAIL_SUBJECT_PREFIX
        if prefix is None:
            if context and 'current_site' in context:
                site = context.get('current_site')
            else:
                site = get_current_site()
            prefix = "[{name}] ".format(name=site.name)
        return prefix + force_text(subject)

    def render_mail(self, template_prefix, email, context):
        """
        Renders an e-mail to `email`.  `template_prefix` identifies the
        e-mail that is to be sent, e.g. "account/email/email_confirmation"
        """
        subject = render_to_string('{0}_subject.txt'.format(template_prefix),
                                   context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()
        subject = self.format_email_subject(subject, context)

        bodies = {}
        for ext in ['html', 'txt']:
            try:
                template_name = '{0}_message.{1}'.format(template_prefix, ext)
                bodies[ext] = render_to_string(template_name,
                                               context).strip()
            except TemplateDoesNotExist:
                if ext == 'txt' and not bodies:
                    # We need at least one body
                    raise
        if 'txt' in bodies:
            msg = EmailMultiAlternatives(subject,
                                         bodies['txt'],
                                         settings.DEFAULT_FROM_EMAIL,
                                         [email])
            if 'html' in bodies:
                msg.attach_alternative(bodies['html'], 'text/html')
        else:
            msg = EmailMessage(subject,
                               bodies['html'],
                               settings.DEFAULT_FROM_EMAIL,
                               [email])
            msg.content_subtype = 'html'  # Main content is now text/html
        return msg

    def send_mail(self, template_prefix, email, context):
        msg = self.render_mail(template_prefix, email, context)
        msg.send()

    def get_login_redirect_url(self, request):
        """
        Returns the default URL to redirect to after logging in.  Note
        that URLs passed explicitly (e.g. by passing along a `next`
        GET parameter) take precedence over the value returned here.
        """
        assert request.user.is_authenticated()
        url = getattr(settings, "LOGIN_REDIRECT_URLNAME", None)
        if url:
            warnings.warn("LOGIN_REDIRECT_URLNAME is deprecated, simply"
                          " use LOGIN_REDIRECT_URL with a URL name",
                          DeprecationWarning)
        else:
            url = settings.LOGIN_REDIRECT_URL
        return resolve_url(url)

    def get_logout_redirect_url(self, request):
        """
        Returns the URL to redirect to after the user logs out. Note that
        this method is also invoked if you attempt to log out while no users
        is logged in. Therefore, request.user is not guaranteed to be an
        authenticated user.
        """
        return resolve_url(app_settings.LOGOUT_REDIRECT_URL)

    def get_email_confirmation_redirect_url(self, request):
        """
        The URL to return to after successful e-mail confirmation.
        """
        if request.user.is_authenticated():
            if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL:
                return  \
                    app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
            else:
                return self.get_login_redirect_url(request)
        else:
            return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL

    def is_open_for_signup(self, request):
        """
        Checks whether or not the site is open for signups.

        Next to simply returning True/False you can also intervene the
        regular flow by raising an ImmediateHttpResponse
        """
        return True

    def new_user(self, request):
        """
        Instantiates a new User instance.
        """
        user = get_user_model()()
        return user

    def populate_username(self, request, user):
        """
        Fills in a valid username, if required and missing.  If the
        username is already present it is assumed to be valid
        (unique).
        """
        from .utils import user_username, user_email, user_field
        first_name = user_field(user, 'first_name')
        last_name = user_field(user, 'last_name')
        email = user_email(user)
        username = user_username(user)
        if app_settings.USER_MODEL_USERNAME_FIELD:
            user_username(user,
                          username
                          or self.generate_unique_username([first_name,
                                                            last_name,
                                                            email,
                                                            'user']))

    def generate_unique_username(self, txts, regex=None):
        return generate_unique_username(txts, regex)

    def save_user(self, request, user, form, commit=True):
        """
        Saves a new `User` instance using information provided in the
        signup form.
        """
        from .utils import user_username, user_email, user_field

        data = form.cleaned_data
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        username = data.get('username')
        user_email(user, email)
        user_username(user, username)
        if first_name:
            user_field(user, 'first_name', first_name)
        if last_name:
            user_field(user, 'last_name', last_name)
        if 'password1' in data:
            user.set_password(data["password1"])
        else:
            user.set_unusable_password()
        self.populate_username(request, user)
        if commit:
            # Ability not to commit makes it easier to derive from
            # this adapter by adding
            user.save()
        return user

    def clean_username(self, username, shallow=False):
        """
        Validates the username. You can hook into this if you want to
        (dynamically) restrict what usernames can be chosen.
        """
        if not USERNAME_REGEX.match(username):
            raise forms.ValidationError(_("Usernames can only contain "
                                          "letters, digits and @/./+/-/_."))

        # TODO: Add regexp support to USERNAME_BLACKLIST
        username_blacklist_lower = [ub.lower()
                                    for ub in app_settings.USERNAME_BLACKLIST]
        if username.lower() in username_blacklist_lower:
            raise forms.ValidationError(_("Username can not be used. "
                                          "Please use other username."))
        # Skipping database lookups when shallow is True, needed for unique
        # username generation.
        if not shallow:
            username_field = app_settings.USER_MODEL_USERNAME_FIELD
            assert username_field
            user_model = get_user_model()
            try:
                query = {username_field + '__iexact': username}
                user_model.objects.get(**query)
            except user_model.DoesNotExist:
                return username
            raise forms.ValidationError(
                _("This username is already taken. Please choose another."))
        return username

    def clean_email(self, email):
        """
        Validates an email value. You can hook into this if you want to
        (dynamically) restrict what email addresses can be chosen.
        """
        return email

    def clean_password(self, password):
        """
        Validates a password. You can hook into this if you want to
        restric the allowed password choices.
        """
        min_length = app_settings.PASSWORD_MIN_LENGTH
        if len(password) < min_length:
            raise forms.ValidationError(_("Password must be a minimum of {0} "
                                          "characters.").format(min_length))
        return password

    def add_message(self, request, level, message_template,
                    message_context=None, extra_tags=''):
        """
        Wrapper of `django.contrib.messages.add_message`, that reads
        the message text from a template.
        """
        if 'django.contrib.messages' in settings.INSTALLED_APPS:
            try:
                if message_context is None:
                    message_context = {}
                message = render_to_string(message_template,
                                           message_context).strip()
                if message:
                    messages.add_message(request, level, message,
                                         extra_tags=extra_tags)
            except TemplateDoesNotExist:
                pass

    def ajax_response(self, request, response, redirect_to=None, form=None):
        data = {}
        status = response.status_code

        if redirect_to:
            status = 200
            data['location'] = redirect_to
        if form:
            if form.is_valid():
                status = 200
            else:
                status = 400
                data['form_errors'] = form._errors
            if hasattr(response, 'render'):
                response.render()
            data['html'] = response.content.decode('utf8')
        return HttpResponse(json.dumps(data),
                            status=status,
                            content_type='application/json')

    def login(self, request, user):
        # HACK: This is not nice. The proper Django way is to use an
        # authentication backend
        if not hasattr(user, 'backend'):
            user.backend \
                = "allauth.account.auth_backends.AuthenticationBackend"
        django_login(request, user)

    def logout(self, request):
        django_logout(request)

    def confirm_email(self, request, email_address):
        """
        Marks the email address as confirmed on the db
        """
        email_address.verified = True
        email_address.set_as_primary(conditional=True)
        email_address.save()

    def set_password(self, user, password):
        user.set_password(password)
        user.save()

    def get_user_search_fields(self):
        user = get_user_model()()
        return filter(lambda a: a and hasattr(user, a),
                      [app_settings.USER_MODEL_USERNAME_FIELD,
                       'first_name', 'last_name', 'email'])

    def is_safe_url(self, url):
        from django.utils.http import is_safe_url
        return is_safe_url(url)

    def get_email_confirmation_url(self, request, emailconfirmation):
        """Constructs the email confirmation (activation) url.

        Note that if you have architected your system such that email
        confirmations are sent outside of the request context `request`
        can be `None` here.
        """
        url = reverse(
            "account_confirm_email",
            args=[emailconfirmation.key])
        ret = build_absolute_uri(
            request,
            url,
            protocol=app_settings.DEFAULT_HTTP_PROTOCOL)
        return ret

    def send_confirmation_mail(self, request, emailconfirmation, signup):
        current_site = get_current_site(request)
        activate_url = self.get_email_confirmation_url(
            request,
            emailconfirmation)
        ctx = {
            "user": emailconfirmation.email_address.user,
            "activate_url": activate_url,
            "current_site": current_site,
            "key": emailconfirmation.key,
        }
        if signup:
            email_template = 'account/email/email_confirmation_signup'
        else:
            email_template = 'account/email/email_confirmation'
        self.send_mail(email_template,
                       emailconfirmation.email_address.email,
                       ctx)

def get_adapter():
    return import_attribute(app_settings.ADAPTER)()
<|endoftext|>


<commit_before># Django settings for cualbondi project.
import os
from settings_local import loadDbParameters

DEBUG = True
TEMPLATE_DEBUG = DEBUG

LOGIN_REDIRECT_URL = '/'

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)
DEFAULT_FROM_EMAIL = "info@cualbondi.com.ar"

MANAGERS = ADMINS

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

DATABASES = loadDbParameters()

USE_CACHE = False
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}
CACHE_TIMEOUT = 60*60

OLWIDGET_STATIC_URL = "/media/olwidget"
GOOGLE_API = "//maps.google.com/maps/api/js?v=3.6&sensor=false"

# Variables personalizadas
RADIO_ORIGEN_DEFAULT = 200
RADIO_DESTINO_DEFAULT = 200
LONGITUD_PAGINA = 5

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_PATH, 'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = 'media'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '=tr&%05vw6&s4eoq)wdj(d&(56#cq@5k0b-c$^v6vr)#%e(c+&'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

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

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
"apps.core.context_processors.lista_ciudades",
"apps.core.context_processors.get_ciudad_actual")

ROOT_URLCONF = 'urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(os.path.dirname(__file__),'templates')
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    'django.contrib.comments',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'django.contrib.gis',
    'apps.catastro',
    'apps.core',
    'apps.usuarios',
    'floppyforms',
    'olwidget',
#    'moderacion',
#    'editor',
#    'django_extensions',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
<commit_msg>compatibilidad con django 1.4<commit_after># Django settings for cualbondi project.
import os
from settings_local import loadDbParameters

DEBUG = True
TEMPLATE_DEBUG = DEBUG

LOGIN_REDIRECT_URL = '/'

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)
DEFAULT_FROM_EMAIL = "info@cualbondi.com.ar"

MANAGERS = ADMINS

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

DATABASES = loadDbParameters()

USE_CACHE = False
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}
CACHE_TIMEOUT = 60*60

OLWIDGET_STATIC_URL = "/media/olwidget"
GOOGLE_API = "//maps.google.com/maps/api/js?v=3.6&sensor=false"

# Variables personalizadas
RADIO_ORIGEN_DEFAULT = 200
RADIO_DESTINO_DEFAULT = 200
LONGITUD_PAGINA = 5

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_PATH, 'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = 'media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '=tr&%05vw6&s4eoq)wdj(d&(56#cq@5k0b-c$^v6vr)#%e(c+&'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

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

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
"apps.core.context_processors.lista_ciudades",
"apps.core.context_processors.get_ciudad_actual")

ROOT_URLCONF = 'urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(os.path.dirname(__file__),'templates')
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    'django.contrib.comments',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'django.contrib.gis',
    'apps.catastro',
    'apps.core',
    'apps.usuarios',
    'floppyforms',
    'olwidget',
#    'moderacion',
#    'editor',
#    'django_extensions',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
<|endoftext|>


<commit_before>#!/usr/bin/env python
"""
Very simple single-process/single-threaded/non-async web server to provide packages
"""
import sys
import os
import socket
import argparse
import shutil
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer
from SocketServer import ThreadingMixIn

__version__ = "0.1"

def show_example_condarc(port):
    template = """
  channels:
        - %(url)s

"""
    host = socket.gethostname()
    url = "http://%s" % host
    if port != 80:
        url = "%s:%s" % (url, port)
    print "Please create a conda configuration file called $HOME/.condarc with the following contents (yaml format)"
    print template % vars()

def copy_index_html(target):
    this_path = os.path.dirname(os.path.abspath(__file__))
    shutil.copy(os.path.join(this_path, "index.html"), target)

class ThreadedHttpServer(ThreadingMixIn, HTTPServer):
    pass

def serve(port):
    server_address = ('', port)
    httpd = ThreadedHttpServer(server_address, SimpleHTTPRequestHandler)
    sa = httpd.socket.getsockname()
    show_example_condarc(port)
    print "Serving HTTP on", sa[0], "port", sa[1], "from", os.getcwd(), "..."
    httpd.serve_forever()

def main():
    parser = argparse.ArgumentParser(description=__doc__, version=__version__)
    default_doc_root = os.path.join(sys.prefix, "conda-bld")
    parser.add_argument("--port", "-p", type=int, default=8000,
                        help="default port for listening is %(default)s")
    parser.add_argument("--root", "-r", default=default_doc_root,
                        help="default document root is %(default)r")
    parser.add_argument("--noindex", default=False, action="store_true",
                        help="Do not copy index.html to document root")
    args = parser.parse_args()
    if not args.noindex:
        copy_index_html(args.root)
    os.chdir(args.root)
    serve(args.port)

if __name__ == "__main__":
    sys.exit(main() or 0)
<commit_msg>update repo cache<commit_after>#!/usr/bin/env python
"""
Very simple single-process/non-async web server to provide packages
"""
import sys
import os
import socket
import argparse
import shutil
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer
from SocketServer import ThreadingMixIn

__version__ = "0.1"

def show_example_condarc(port):
    template = """
  channels:
        - %(url)s

"""
    host = socket.gethostname()
    url = "http://%s" % host
    if port != 80:
        url = "%s:%s" % (url, port)
    print "Please create a conda configuration file called $HOME/.condarc with the following contents (yaml format)"
    print template % vars()

def copy_index_html(target):
    this_path = os.path.dirname(os.path.abspath(__file__))
    shutil.copy(os.path.join(this_path, "index.html"), target)

class ThreadedHttpServer(ThreadingMixIn, HTTPServer):
    pass

def update_repodata():
    cmd = "{prefix}/bin/conda index {prefix}/conda-bld/linux-64/"
    os.system(cmd.format(prefix=sys.prefix))

def serve(port):
    server_address = ('', port)
    httpd = ThreadedHttpServer(server_address, SimpleHTTPRequestHandler)
    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "from", os.getcwd(), "..."
    httpd.serve_forever()

def main():
    parser = argparse.ArgumentParser(description=__doc__, version=__version__)
    default_doc_root = os.path.join(sys.prefix, "conda-bld")
    parser.add_argument("--port", "-p", type=int, default=8000,
                        help="default port for listening is %(default)s")
    parser.add_argument("--root", "-r", default=default_doc_root,
                        help="default document root is %(default)r")
    parser.add_argument("--noindex", default=False, action="store_true",
                        help="Do not copy index.html to document root")
    parser.add_argument("--noupdate", default=False, action="store_true",
                        help="Do not update repodata.json")

    args = parser.parse_args()
    if not args.noindex:
        copy_index_html(args.root)
    if not args.noupdate:
        update_repodata()
    show_example_condarc(args.port)

    os.chdir(args.root)
    serve(args.port)

if __name__ == "__main__":
    sys.exit(main() or 0)
<|endoftext|>


<commit_before>__version__ = '0.6.0dev'
<commit_msg>Bumped to 0.5.1<commit_after>__version__ = '0.5.1'
<|endoftext|>


<commit_before>import os
from cudatext import *

class Command:
    dlg=0
    fnd=0
    edh=0
    edtext=None

    def apply_opt(self, back, from_caret):

        op=''
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='reex')
        if v['val']=='1': op+='r'
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='case')
        if v['val']=='1': op+='c'
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='word')
        if v['val']=='1': op+='w'
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='inse')
        if v['val']=='1': op+='s'
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='wrap')
        if v['val']=='1': op+='a'

        if back: op+='b'
        if from_caret: op+='f'

        finder_proc(self.fnd, FINDER_SET_OPT, op)

        finder_proc(self.fnd, FINDER_SET_ED, self.edh)

        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='what')['val']
        finder_proc(self.fnd, FINDER_SET_FINDTEXT, v)

        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='repl')['val']
        finder_proc(self.fnd, FINDER_SET_REPTEXT, v)

        print('finder: opt: "'+op+'", find what: "'+finder_proc(self.fnd, FINDER_GET_FINDTEXT)+'", replace: "'+finder_proc(self.fnd, FINDER_GET_REPTEXT)+'"')

    def do_count(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, False)
        res=finder_proc(self.fnd, FINDER_COUNT)
        print('count:', res)

    def do_find(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, False)
        res=finder_proc(self.fnd, FINDER_FIND, next=False, setcaret=True)
        if res is not None:
            self.edtext.action(EDACTION_SHOW_POS, (res[0], res[1]))
        print('find-first:', res)

    def do_find_next(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, True)
        res=finder_proc(self.fnd, FINDER_FIND, next=False, setcaret=True)
        if res is not None:
            self.edtext.action(EDACTION_SHOW_POS, (res[0], res[1]))
        print('find-next:', res)

    def do_find_prev(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(True, True)
        res=finder_proc(self.fnd, FINDER_FIND, next=False, setcaret=True)
        if res is not None:
            self.edtext.action(EDACTION_SHOW_POS, (res[0], res[1]))
        print('find-prev:', res)

    def do_find_all(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, False)
        res=finder_proc(self.fnd, FINDER_FIND_ALL)
        print('find-all:', res)

    def do_rep(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, True)
        res=finder_proc(self.fnd, FINDER_FIND_REP, next=False, setcaret=True)
        if res is not None:
            self.edtext.action(EDACTION_SHOW_POS, (res[0], res[1]))
        print('replace-next:', res)

    def do_rep_all(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, False)
        res=finder_proc(self.fnd, FINDER_REP_ALL)
        print('replace-all:', res)

    def run(self):

        idd=dlg_proc(0, DLG_CREATE)

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'reex', 'x':5, 'y':5, 'w':50, 'h':28, 'cap':'&.*'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'case', 'x':55, 'y':5, 'w':50, 'h':28, 'cap':'&cC'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'word', 'x':105, 'y':5, 'w':50, 'h':28, 'cap':'"&w"'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'inse', 'x':155, 'y':5, 'w':50, 'h':28, 'cap':'[&...]'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'wrap', 'x':205, 'y':5, 'w':50, 'h':28, 'cap':'wrap'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"label");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'wha_', 'x':5, 'y':30, 'w':200, 'h':17, 'cap':'&Find what'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"memo");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'what', 'x':5, 'y':50, 'w':200, 'h':70, 'val': 'aa'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"label");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'rep_', 'x':230, 'y':30, 'w':200, 'h':17, 'cap':'&Replace with'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"memo");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'repl', 'x':230, 'y':50, 'w':200, 'h':70, 'val': 'dd'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"label");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'crt_', 'x':5, 'y':120, 'w':200, 'h':17, 'cap':'&Carets'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"edit");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'crts', 'x':5, 'y':140, 'w':200, 'h':25})

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'frst', 'x':5, 'y':170, 'w':100, 'h':25, 'cap':'Find first', 'on_change': self.do_find })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'next', 'x':5, 'y':200, 'w':100, 'h':25, 'cap':'Find next', 'on_change': self.do_find_next })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'prev', 'x':105, 'y':170, 'w':100, 'h':25, 'cap':'Find prev', 'on_change': self.do_find_prev })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'fall', 'x':105, 'y':200, 'w':100, 'h':25, 'cap':'Find all', 'on_change': self.do_find_all })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'rone', 'x':230, 'y':170, 'w':100, 'h':25, 'cap':'Replace next', 'on_change': self.do_rep })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'rall', 'x':230, 'y':200, 'w':100, 'h':25, 'cap':'Replace all', 'on_change': self.do_rep_all })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'coun', 'x':335, 'y':200, 'w':100, 'h':25, 'cap':'Count', 'on_change': self.do_count })

        idc=dlg_proc(idd, DLG_CTL_ADD,"label");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'tex_', 'x':5, 'y':240, 'w':200, 'h':17, 'cap':'User text'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"editor");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'text', 'x':5, 'y':255, 'w':450, 'h':200})
        self.edh=dlg_proc(idd, DLG_CTL_HANDLE, name='text')
        self.edtext=Editor(self.edh)

        self.edtext.set_text_all('''a aa
aaaaa aaaaaa aaaaaaaaaaaaaaa aa
aa aaaa aaa bb a a b b
bb
b
a
aaaaa

bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
''')

        dlg_proc(idd, DLG_PROP_SET, prop={
            'w':500, 'h':500, 'cap':'Testing finder_proc', 'tag':''})

        self.dlg=idd
        self.fnd=finder_proc(0, FINDER_CREATE)

        dlg_proc(idd, DLG_SHOW_MODAL)
        dlg_proc(idd, DLG_FREE)
        <commit_msg>work on testing-plg<commit_after>import os
from cudatext import *

class Command:
    dlg=0
    fnd=0
    edh=0
    edtext=None

    def apply_opt(self, back, from_caret):

        op=''
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='reex')
        if v['val']=='1': op+='r'
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='case')
        if v['val']=='1': op+='c'
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='word')
        if v['val']=='1': op+='w'
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='inse')
        if v['val']=='1': op+='s'
        v=dlg_proc(self.dlg, DLG_CTL_PROP_GET, name='wrap')
        if v['val']=='1': op+='a'

        if back: op+='b'
        if from_caret: op+='f'

        finder_proc(self.fnd, FINDER_SET_OPT, op)

        finder_proc(self.fnd, FINDER_SET_ED, self.edh)

        s_find=self.edfind.get_text_all()
        finder_proc(self.fnd, FINDER_SET_FINDTEXT, s_find)

        s_rep=self.edrep.get_text_all()
        finder_proc(self.fnd, FINDER_SET_REPTEXT, s_rep)

        print('finder: opt: "'+op+'", find what: "'+s_find+'", replace: "'+s_rep+'"')

    def do_count(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, False)
        res=finder_proc(self.fnd, FINDER_COUNT)
        print('count:', res)

    def do_find(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, False)
        res=finder_proc(self.fnd, FINDER_FIND, next=False, setcaret=True)
        if res is not None:
            self.edtext.action(EDACTION_SHOW_POS, (res[0], res[1]))
        print('find-first:', res)

    def do_find_next(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, True)
        res=finder_proc(self.fnd, FINDER_FIND, next=False, setcaret=True)
        if res is not None:
            self.edtext.action(EDACTION_SHOW_POS, (res[0], res[1]))
        print('find-next:', res)

    def do_find_prev(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(True, True)
        res=finder_proc(self.fnd, FINDER_FIND, next=False, setcaret=True)
        if res is not None:
            self.edtext.action(EDACTION_SHOW_POS, (res[0], res[1]))
        print('find-prev:', res)

    def do_find_all(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, False)
        res=finder_proc(self.fnd, FINDER_FIND_ALL)
        print('find-all:', res)

    def do_rep(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, True)
        res=finder_proc(self.fnd, FINDER_FIND_REP, next=False, setcaret=True)
        if res is not None:
            self.edtext.action(EDACTION_SHOW_POS, (res[0], res[1]))
        print('replace-next:', res)

    def do_rep_all(self, id_dlg, id_ctl, data='', info=''):

        self.apply_opt(False, False)
        res=finder_proc(self.fnd, FINDER_REP_ALL)
        print('replace-all:', res)

    def run(self):

        idd=dlg_proc(0, DLG_CREATE)

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'reex', 'x':5, 'y':5, 'w':50, 'h':28, 'cap':'&.*'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'case', 'x':55, 'y':5, 'w':50, 'h':28, 'cap':'&cC'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'word', 'x':105, 'y':5, 'w':50, 'h':28, 'cap':'"&w"'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'inse', 'x':155, 'y':5, 'w':50, 'h':28, 'cap':'[&...]'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"checkbutton");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'wrap', 'x':205, 'y':5, 'w':50, 'h':28, 'cap':'wrap'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"label");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'wha_', 'x':5, 'y':30, 'w':200, 'h':17, 'cap':'&Find what'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"editor");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'what', 'x':5, 'y':50, 'w':200, 'h':70})
        h=dlg_proc(idd, DLG_CTL_HANDLE, name='what')
        self.edfind=Editor(h)
        self.edfind.set_text_all('aa')
        self.edfind.set_prop(PROP_GUTTER_ALL, False)

        idc=dlg_proc(idd, DLG_CTL_ADD,"label");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'rep_', 'x':230, 'y':30, 'w':200, 'h':17, 'cap':'&Replace with'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"editor");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'repl', 'x':230, 'y':50, 'w':200, 'h':70 })
        h=dlg_proc(idd, DLG_CTL_HANDLE, name='repl')
        self.edrep=Editor(h)
        self.edrep.set_text_all('[..]')
        self.edrep.set_prop(PROP_GUTTER_ALL, False)

        idc=dlg_proc(idd, DLG_CTL_ADD,"label");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'crt_', 'x':5, 'y':120, 'w':200, 'h':17, 'cap':'&Carets'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"edit");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'crts', 'x':5, 'y':140, 'w':200, 'h':25})

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'frst', 'x':5, 'y':170, 'w':100, 'h':25, 'cap':'Find first', 'on_change': self.do_find })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'next', 'x':5, 'y':200, 'w':100, 'h':25, 'cap':'Find next', 'on_change': self.do_find_next })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'prev', 'x':105, 'y':170, 'w':100, 'h':25, 'cap':'Find prev', 'on_change': self.do_find_prev })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'fall', 'x':105, 'y':200, 'w':100, 'h':25, 'cap':'Find all', 'on_change': self.do_find_all })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'rone', 'x':230, 'y':170, 'w':100, 'h':25, 'cap':'Replace next', 'on_change': self.do_rep })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'rall', 'x':230, 'y':200, 'w':100, 'h':25, 'cap':'Replace all', 'on_change': self.do_rep_all })

        idc=dlg_proc(idd, DLG_CTL_ADD,"button");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'coun', 'x':335, 'y':200, 'w':100, 'h':25, 'cap':'Count', 'on_change': self.do_count })

        idc=dlg_proc(idd, DLG_CTL_ADD,"label");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'tex_', 'x':5, 'y':240, 'w':200, 'h':17, 'cap':'User text'})

        idc=dlg_proc(idd, DLG_CTL_ADD,"editor");dlg_proc(idd, DLG_CTL_PROP_SET, index=idc, prop={
        'name':'text', 'x':5, 'y':255, 'w':450, 'h':200})
        self.edh=dlg_proc(idd, DLG_CTL_HANDLE, name='text')
        self.edtext=Editor(self.edh)

        self.edtext.set_text_all('''a aa
aaaaa aaaaaa aaaaaaaaaaaaaaa aa
aa aaaa aaa bb a a b b
bb
b
a
aaaaa

bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
bb
a
bbb b bbbbb b b bbb
''')

        dlg_proc(idd, DLG_PROP_SET, prop={
            'w':500, 'h':500, 'cap':'Testing finder_proc', 'tag':''})

        self.dlg=idd
        self.fnd=finder_proc(0, FINDER_CREATE)

        dlg_proc(idd, DLG_SHOW_MODAL)
        dlg_proc(idd, DLG_FREE)
        <|endoftext|>


<commit_before># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Provides capabilities for establishing connectivity with a GCE instance.

Connectivity can be provided even if it requires tunneling through ssh
because instances are not necessarily exposed through the GCE firewall
for external access.
"""

import atexit
import json
import logging
import os
import socket
import time
import urllib2

def _unused_port():
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.bind(('localhost', 0))
  addr, port = s.getsockname()
  s.close()
  return port

class _ProcessKiller(object):
  """Helper class for killing firewall tunnels."""

  def  __init__(self, process):
    self.__process = process
  def safe_kill(self):
    try:
      print '*** terminating tunnel'
      os.kill(self.__process, -9)
    except:
      pass

def _find_internal_ip_interface(iface_list):
  """Find an IP address that is internal from GCE.

  Args:
    iface_list: a list of GCE networkInterface.

  Returns:
    IP address string or None.
  """
  logger = logging.getLogger(__name__)
  for iface in iface_list:
    try:
      ip = iface['networkIP']
      if ip != '127.0.0.1':
        return ip
    except:
      logger.warning('Network Interface has no "networkIP": %s', iface)

  logger.warning('Could not find internal IP interface in %s:', iface_list)
  return None

def _find_external_ip_interface(iface_list, gcloud_response):
  """Find an IP address that is external from GCE.

  Args:
    iface_list: a list of GCE networkInterface.

  Returns:
    IP address string or None.
  """
  logger = logging.getLogger(__name__)
  for iface in iface_list:
    try:
      access_configs = iface['accessConfigs']
    except:
      logger.error(
          'Description lacks networkInterfaces/accessConfigs field:%s',
          gcloud_response)
      continue
    # Find an external IP address in this list
    for config in access_configs:
      try:
        if config['name'] == 'external-nat':
          return config['natIP']
      except:
        logger.warning('Config lacks name or natIP:%s', config)

  logger.warning('Could not find external IP interface in %s:', iface_list)
  return None

def determine_where_i_am():
  """Determine the project/zone/instance this process is running on.

  Returns:
    project, zone, instance  string-triple.
    Each will be None if we are not running on GCE.
  """
  logger = logging.getLogger(__name__)
  headers = {'Metadata-Flavor': 'Google'}

  url = 'http://metadata/computeMetadata/v1/project/project-id'
  try:
    my_project = urllib2.urlopen(urllib2.Request(url, headers=headers)).read()
  except Exception as e:
    # Likely we are not running on GCE at all.
    logger.debug('We are not running on GCE.' + str(e))
    return None, None, None

  # Since the above succeeded, we expect this to succeed
  url = 'http://metadata/computeMetadata/v1/instance/zone'
  formal_zone = urllib2.urlopen(urllib2.Request(url, headers=headers)).read()
  my_zone = formal_zone.split('/')[-1]
  url = 'http://metadata/computeMetadata/v1/instance/hostname'
  hostname = urllib2.urlopen(urllib2.Request(url, headers=headers)).read()
  my_instance = hostname.split('.')[0]
  logger.debug('We are are running in project=%s zone=%s instance=%s',
               my_project, my_zone, my_instance)
  return my_project, my_zone, my_instance

def am_i(project, zone, instance):
  """Determine if this process is running in the specified instance.

  Args:
    project: A GCP project.
    zone: A GCP zone.
    instance: A GCE instance name.

  Returns:
    True if this process is being run in the specified instance, false otherwise
        including not on GCP at all.
  """
  my_project, my_zone, my_instance = determine_where_i_am()
  if instance != my_instance or my_zone != zone:
    return False
  return not project or project == my_project

def _network_interfaces_for_instance(gcloud, instance):
  """Determine VM network interfaces for a given GCP instance.

  Args:
    gcloud:  [GCloudHelper] bound to the instance's project and zone.
    instance: [string] The name of the instance to lookup.

  Returns:
    list of network interfaces (IP addresses) or None

  Raises:
    Exception if instance information could not be determined.
  """
  logger = logging.getLogger(__name__)
  logger.debug('Testing locating test project instance=%s', instance)
  gcloud_response = gcloud.describe_resource('instances', instance)
  if gcloud_response.retcode != 0:
    logger.error(
        'Could not find instance=%s in project=%s, zone=%s: %s',
        instance, gcloud.project, gcloud.zone, gcloud_response.error)
    return None, gcloud_response

  try:
    doc = json.JSONDecoder().decode(gcloud_response.output)
  except:
    logger.error('Invalid JSON in response: %s', gcloud_response)
    return None, gcloud_response

  try:
    if doc['status'] != 'RUNNING':
      logger.error(
          'instance=%s project=%s zone=%s is not RUNNING: %s',
          instance, gcloud.project, gcloud.zone, doc['status'])
      return None, gcloud_response
  except:
    logger.warning('Could not check VM status:%s', gcloud_response)

  try:
    iface_list = doc['networkInterfaces']
  except KeyError:
    logger.error('JSON has no networkInterfaces: %s', doc)
    return None, gcloud_response

  return iface_list, gcloud_response

def establish_network_connectivity(gcloud, instance, target_port):
  """Determine conventional host:port url for a target_port on an GCE instance.

  GCE instances are firewalled within GCE by default so reaching them may
  require tunneling if this function is called from outside the GCE project.
  If we need to tunnel, the tunnel will be established and remain active
  until exit. To avoid port conflicts, we'll pick an unused local port for
  the tunnel.

  Args:
    gcloud: A GCloudHelper bound to the instance's project and zone.
    instance: The GCE instance name we want to reach.
    target_port: The port number on the instance we are interested in.

  Returns:
    IP host:port address string to the specified GCE instance.
    The port may be different from the target_port if we needed to tunnel
    because it will be on the client-side port of the tunnel (on localhost).
  """
  logger = logging.getLogger(__name__)
  # We're going to use the generic gcloud interface, which will
  # work whether or not we are running in a GCE instance ourselves.

  logger.debug('Testing locating test project instance=%s', instance)
  iface_list, gcloud_response = _network_interfaces_for_instance(
      gcloud, instance)
  if iface_list is None:
    return None

  tried_urls = []
  for which in ['external', 'internal']:
    if which == 'external':
      ip = _find_external_ip_interface(iface_list, gcloud_response)
    else:
      ip = _find_internal_ip_interface(iface_list)
    if not ip:
      continue

    logger.debug('%s is on ip=%s', instance, ip)
    url = 'http://{host}:{port}'.format(host=ip, port=target_port)
    tried_urls.append(url)
    try:
      response = urllib2.urlopen(url, None, 5)
      logger.debug('%s is directly reachable already.', url)
      return '{0}:{1}'.format(ip, target_port)
    except urllib2.URLError:
      pass

  my_project, my_zone, my_instance = determine_where_i_am()
  if my_project and (my_project == gcloud.project or not gcloud.project):
    logger.error(
        'We are in the same project %s but cannot reach the server %s.'
        ' It must not be running on port %d, or is bound to localhost',
        my_project, instance, target_port)

  local_port = _unused_port()
  # The use of 'localhost' here will be relative to the instance we ssh into
  # (i.e. it is 'localhost' on the GCE instance, not the client process).
  # GCloud wont need the actual IP address.
  # Since we have the tunnel, we'll be returning 'localhost' with our new port.
  tunnel_spec = '{local_port}:localhost:{target_port}'.format(
      local_port=local_port, target_port=target_port)

  logger.debug(
      'None of %s were directly reachable;\nEstablishing tunnel as %s',
      tried_urls, tunnel_spec)
  logger.info(
      'Could not connect directly. Try tunneling as %s...', tunnel_spec)
  pid, fd = gcloud.pty_fork_ssh(
      instance, ['--ssh-flag="-L %s"' % tunnel_spec], async=True)

  running = False
  try:
    running = not os.kill(pid, 0)
  except OSError:
    pass

  if running:
    print '*** opened tunnel as pid={pid}. This should close at exit.'.format(
        pid=pid)
    atexit.register(_ProcessKiller(pid).safe_kill)

  logger.debug('Confirming tunnel is working')
  url = 'http://localhost:%d' % local_port
  for i in range(15):
    try:
      response = urllib2.urlopen(url, None, 10)
      logger.debug('Confirmed availability (%d)', response.getcode())
      return 'localhost:%d' % local_port
    except:
      time.sleep(1)  # wait a bit longer

  logger.error('Could not connect to our own tunnel at %s', url)
  logger.error('Could not establish connection to %s.', instance)

  return None
<commit_msg>Faster GCE server tunneling.<commit_after># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Provides capabilities for establishing connectivity with a GCE instance.

Connectivity can be provided even if it requires tunneling through ssh
because instances are not necessarily exposed through the GCE firewall
for external access.
"""

import atexit
import json
import logging
import os
import socket
import time
import urllib2

def _unused_port():
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.bind(('localhost', 0))
  addr, port = sock.getsockname()
  sock.close()
  return port

class _ProcessKiller(object):
  """Helper class for killing firewall tunnels."""
  # pylint: disable=too-few-public-methods

  def  __init__(self, process):
    self.__process = process

  def safe_kill(self):
    """Terminates the gcloud ssh tunnel when our process terminates."""
    try:
      print '*** terminating tunnel'
      os.kill(self.__process, -9)
    except OSError:
      pass

def _find_internal_ip_interface(iface_list):
  """Find an IP address that is internal from GCE.

  Args:
    iface_list: a list of GCE networkInterface.

  Returns:
    IP address string or None.
  """
  logger = logging.getLogger(__name__)
  for iface in iface_list:
    try:
      ip_addr = iface['networkIP']
      if ip_addr != '127.0.0.1':
        return ip_addr
    except KeyError:
      logger.warning('Network Interface has no "networkIP": %s', iface)

  logger.warning('Could not find internal IP interface in %s:', iface_list)
  return None

def _find_external_ip_interface(iface_list, gcloud_response):
  """Find an IP address that is external from GCE.

  Args:
    iface_list: a list of GCE networkInterface.

  Returns:
    IP address string or None.
  """
  logger = logging.getLogger(__name__)
  for iface in iface_list:
    try:
      access_configs = iface['accessConfigs']
    except KeyError:
      logger.error(
          'Description lacks networkInterfaces/accessConfigs field:%s',
          gcloud_response)
      continue
    # Find an external IP address in this list
    for config in access_configs:
      try:
        if config['name'] == 'external-nat':
          return config['natIP']
      except KeyError:
        logger.warning('Config lacks name or natIP:%s', config)

  logger.warning('Could not find external IP interface in %s:', iface_list)
  return None

def determine_where_i_am():
  """Determine the project/zone/instance this process is running on.

  Returns:
    project, zone, instance  string-triple.
    Each will be None if we are not running on GCE.
  """
  logger = logging.getLogger(__name__)
  headers = {'Metadata-Flavor': 'Google'}

  url = 'http://metadata/computeMetadata/v1/project/project-id'
  try:
    my_project = urllib2.urlopen(urllib2.Request(url, headers=headers)).read()
  except urllib2.URLError as e:
    # Likely we are not running on GCE at all.
    logger.debug('We are not running on GCE.\n  %s', str(e))
    return None, None, None

  # Since the above succeeded, we expect this to succeed
  url = 'http://metadata/computeMetadata/v1/instance/zone'
  formal_zone = urllib2.urlopen(urllib2.Request(url, headers=headers)).read()
  my_zone = formal_zone.split('/')[-1]
  url = 'http://metadata/computeMetadata/v1/instance/hostname'
  hostname = urllib2.urlopen(urllib2.Request(url, headers=headers)).read()
  my_instance = hostname.split('.')[0]
  logger.debug('We are are running in project=%s zone=%s instance=%s',
               my_project, my_zone, my_instance)
  return my_project, my_zone, my_instance

def am_i(project, zone, instance):
  """Determine if this process is running in the specified instance.

  Args:
    project: A GCP project.
    zone: A GCP zone.
    instance: A GCE instance name.

  Returns:
    True if this process is being run in the specified instance,
    false otherwise including not on GCP at all.
  """
  my_project, my_zone, my_instance = determine_where_i_am()
  if instance != my_instance or my_zone != zone:
    return False
  return not project or project == my_project

def _network_interfaces_for_instance(gcloud, instance):
  """Determine VM network interfaces for a given GCP instance.

  Args:
    gcloud:  [GCloudHelper] bound to the instance's project and zone.
    instance: [string] The name of the instance to lookup.

  Returns:
    list of network interfaces (IP addresses) or None

  Raises:
    Exception if instance information could not be determined.
  """
  logger = logging.getLogger(__name__)
  logger.debug('Testing locating test project instance=%s', instance)
  gcloud_response = gcloud.describe_resource('instances', instance)
  if gcloud_response.retcode != 0:
    logger.error(
        'Could not find instance=%s in project=%s, zone=%s: %s',
        instance, gcloud.project, gcloud.zone, gcloud_response.error)
    return None, gcloud_response

  try:
    doc = json.JSONDecoder().decode(gcloud_response.output)
  except ValueError:
    logger.error('Invalid JSON in response: %s', gcloud_response)
    return None, gcloud_response

  try:
    if doc['status'] != 'RUNNING':
      logger.error(
          'instance=%s project=%s zone=%s is not RUNNING: %s',
          instance, gcloud.project, gcloud.zone, doc['status'])
      return None, gcloud_response
  except KeyError:
    logger.warning('Could not check VM status:%s', gcloud_response)

  try:
    iface_list = doc['networkInterfaces']
  except KeyError:
    logger.error('JSON has no networkInterfaces: %s', doc)
    return None, gcloud_response

  return iface_list, gcloud_response

def establish_network_connectivity(gcloud, instance, target_port):
  """Determine conventional host:port url for a target_port on an GCE instance.

  GCE instances are firewalled within GCE by default so reaching them may
  require tunneling if this function is called from outside the GCE project.
  If we need to tunnel, the tunnel will be established and remain active
  until exit. To avoid port conflicts, we'll pick an unused local port for
  the tunnel.

  Args:
    gcloud: A GCloudHelper bound to the instance's project and zone.
    instance: The GCE instance name we want to reach.
    target_port: The port number on the instance we are interested in.

  Returns:
    IP host:port address string to the specified GCE instance.
    The port may be different from the target_port if we needed to tunnel
    because it will be on the client-side port of the tunnel (on localhost).
  """
  logger = logging.getLogger(__name__)
  # We're going to use the generic gcloud interface, which will
  # work whether or not we are running in a GCE instance ourselves.

  logger.debug('Testing locating test project instance=%s', instance)
  iface_list, gcloud_response = _network_interfaces_for_instance(
      gcloud, instance)
  if iface_list is None:
    return None

  my_project, my_zone, my_instance = determine_where_i_am()
  in_same_project = my_project and my_project == gcloud.project
  tried_urls = []
  for which in ['external', 'internal']:
    if which == 'external':
      ip_addr = _find_external_ip_interface(iface_list, gcloud_response)
    elif in_same_project:
      ip_addr = _find_internal_ip_interface(iface_list)
    else:
      logger.debug("Dont try internal IP since we're not in the same project")
      ip_addr = None
    if not ip_addr:
      continue

    logger.debug('%s is on ip=%s', instance, ip_addr)
    url = 'http://{host}:{port}'.format(host=ip_addr, port=target_port)
    tried_urls.append(url)
    try:
      response = urllib2.urlopen(url, None, 5)
      logger.debug('%s is directly reachable already.', url)
      return '{0}:{1}'.format(ip_addr, target_port)
    except urllib2.URLError:
      pass

  if in_same_project:
    logger.error(
        'We are in the same project %s but cannot reach the server %s.'
        ' It must not be running on port %d, or is bound to localhost',
        my_project, instance, target_port)

  local_port = _unused_port()
  # The use of 'localhost' here will be relative to the instance we ssh into
  # (i.e. it is 'localhost' on the GCE instance, not the client process).
  # GCloud wont need the actual IP address.
  # Since we have the tunnel, we'll be returning 'localhost' with our new port.
  tunnel_spec = '{local_port}:localhost:{target_port}'.format(
      local_port=local_port, target_port=target_port)

  logger.debug(
      'None of %s were directly reachable;\nEstablishing tunnel as %s',
      tried_urls, tunnel_spec)
  logger.info(
      'Could not connect directly. Try tunneling as %s...', tunnel_spec)
  pid, fd = gcloud.pty_fork_ssh(
      instance, ['--ssh-flag="-L %s"' % tunnel_spec], async=True)

  running = False
  try:
    running = not os.kill(pid, 0)
  except OSError:
    pass

  if running:
    print '*** opened tunnel as pid={pid}. This should close at exit.'.format(
        pid=pid)
    atexit.register(_ProcessKiller(pid).safe_kill)

  logger.debug('Confirming tunnel is working')
  url = 'http://localhost:%d' % local_port

  # It takes some time for the subprocess to establish the tunnel.
  # Since the tunnel is not set up, the local port will not be available
  # and the open attempt will fail right away. Retry until it is set up.
  for i in range(20):
    try:
      # 5 second timeout
      response = urllib2.urlopen(url, None, 5)
      logger.debug('Confirmed availability (%d)', response.getcode())
      return 'localhost:%d' % local_port
    except urllib2.URLError:
      time.sleep(1)

  logger.error('Could not connect to our own tunnel at %s', url)
  logger.error('Could not establish connection to %s.', instance)

  return None
<|endoftext|>


<commit_before>from roglick.components import PositionComponent,SpriteComponent
from roglick.engine import event
from roglick.engine.ecs import EntityManager,SystemManager
from roglick.engine.panels import PanelManager,PanelContext
from roglick.events import QuitEvent
from roglick.systems import InputSystem,MovementSystem
from roglick.world import WorldManager
from roglick import panels

class GameMaster(object):
    def __init__(self):
        # We need an EntityManager of course
        self._entities = EntityManager()

        # We need a world for the game to take place in
        self._init_world()

        # Systems make everything "go"
        self._init_systems()

        # And of course we need a way to display it all
        self._init_display()

        # Last -- but certainly not least -- we'll need event handlers
        self._register_event_handlers()

        # Okay, REALLY last: We need a PC!
        self._init_pc()

        # This flag, when True, keeps our game loop running
        self._run = True

    @event.event_handler(QuitEvent)
    def quit_handler(self, quitevent):
        self._run = False
        return event.PASS

    def run(self):
        while self._run:
            self._display.draw_panels()
            self._systems.execute()

    def _init_world(self):
        self._world = WorldManager(self._entities)

    def _init_systems(self):
        self._systems = SystemManager(self._entities)

        # Populate our Systems
        self._systems.add_system(InputSystem())
        self._systems.add_system(MovementSystem())

    def _init_display(self):
        self._display = PanelManager('Ro\'glick')
        self._display.set_context(PanelContext.MapScreen)

        self._display.add_panel(
                panels.MapPanel(
                    self._entities, self._world, PanelContext.MapScreen))

    def _register_event_handlers(self):
        # Start with ourself
        event.register(self)

        # WorldManager runs before our systems
        event.register(self._world)

        # Register system event handlers
        for system in self._systems.systems:
            event.register(system)

    def _init_pc(self):
        # Get a random place to put the PC
        x,y = self._world.current_map.get_random_cell()
        pc_pos = PositionComponent(x, y)
        pc_sprite = SpriteComponent('@')

        self._entities.set_component(self._entities.pc, pc_pos)
        self._entities.set_component(self._entities.pc, pc_sprite)

<commit_msg>Event-driven screen drawing<commit_after>from roglick.components import PositionComponent,SpriteComponent
from roglick.engine import event
from roglick.engine.ecs import EntityManager,SystemManager
from roglick.engine.panels import PanelManager,PanelContext
from roglick.events import PreInputEvent,QuitEvent
from roglick.systems import InputSystem,MovementSystem
from roglick.world import WorldManager
from roglick import panels

class GameMaster(object):
    def __init__(self):
        # We need an EntityManager of course
        self._entities = EntityManager()

        # We need a world for the game to take place in
        self._init_world()

        # Systems make everything "go"
        self._init_systems()

        # And of course we need a way to display it all
        self._init_display()

        # Last -- but certainly not least -- we'll need event handlers
        self._register_event_handlers()

        # Okay, REALLY last: We need a PC!
        self._init_pc()

        # This flag, when True, keeps our game loop running
        self._run = True

    @event.event_handler(PreInputEvent)
    def draw_handler(self, myevent):
        self._display.draw_panels()
        return event.PASS

    @event.event_handler(QuitEvent)
    def quit_handler(self, quitevent):
        self._run = False
        return event.PASS

    def run(self):
        while self._run:
            self._systems.execute()

    def _init_world(self):
        self._world = WorldManager(self._entities)

    def _init_systems(self):
        self._systems = SystemManager(self._entities)

        # Populate our Systems
        self._systems.add_system(InputSystem())
        self._systems.add_system(MovementSystem())

    def _init_display(self):
        self._display = PanelManager('Ro\'glick')
        self._display.set_context(PanelContext.MapScreen)

        self._display.add_panel(
                panels.MapPanel(
                    self._entities, self._world, PanelContext.MapScreen))

    def _register_event_handlers(self):
        # Start with ourself
        event.register(self)

        # WorldManager runs before our systems
        event.register(self._world)

        # Register system event handlers
        for system in self._systems.systems:
            event.register(system)

    def _init_pc(self):
        # Get a random place to put the PC
        x,y = self._world.current_map.get_random_cell()
        pc_pos = PositionComponent(x, y)
        pc_sprite = SpriteComponent('@')

        self._entities.set_component(self._entities.pc, pc_pos)
        self._entities.set_component(self._entities.pc, pc_sprite)

<|endoftext|>


<commit_before>from __future__ import absolute_import, division, print_function

import datetime
import time

import requests

from panoptes_client.panoptes import (
    PanoptesAPIException,
    Talk,
)

TALK_EXPORT_TYPES = (
    'talk_comments',
    'talk_tags',
)

talk = Talk()

class Exportable(object):
    """
    Abstract class containing methods for generating and downloading data
    exports.
    """

    def get_export(
        self,
        export_type,
        generate=False,
        wait=False,
        wait_timeout=None,
    ):
        """
        Downloads a data export over HTTP. Returns a file-like object
        containing the content of the export.

        - **export_type** is a string specifying which type of export should be
          downloaded.
        - **generate** is a boolean specifying whether to generate a new export
          and wait for it to be ready, or to just download the latest export.
        - **wait** is a boolean specifying whether to wait for an in-progress
          export to finish, if there is one. Has no effect if ``generate`` is
          ``True``.
        - **wait_timeout** is the number of seconds to wait if ``wait`` is
          ``True``. Has no effect if ``wait`` is ``False`` or if ``generate``
          is ``True``.

        Example::

            classification_export = Project(1234).get_export('classifications')
            for row in csv.DictReader(classification_export):
                print(row)
        """

        if generate:
            self.generate_export(export_type)

        if generate or wait:
            export = self.wait_export(export_type, wait_timeout)
        else:
            export = self.describe_export(export_type)

        if export_type in TALK_EXPORT_TYPES:
            media_url = export['data_requests'][0]['url']
        else:
            media_url = export['media'][0]['src']

        return requests.get(media_url, stream=True)

    def wait_export(
        self,
        export_type,
        timeout=None,
    ):
        """
        Blocks until an in-progress export is ready.

        - **export_type** is a string specifying which type of export to wait
          for.
        - **timeout** is the maximum number of seconds to wait.

        If ``timeout`` is given and the export is not ready by the time limit,
        :py:class:`.PanoptesAPIException` is raised.
        """

        success = False
        if timeout:
            end_time = datetime.datetime.now() + datetime.timedelta(
                seconds=timeout
            )

        while (not timeout) or (datetime.datetime.now() < end_time):
            export_description = self.describe_export(
                export_type,
            )

            if export_type in TALK_EXPORT_TYPES:
                export_metadata = export_description['data_requests'][0]
            else:
                export_metadata = export_description['media'][0]['metadata']

            if export_metadata.get('state', '') in ('ready', 'finished'):
                success = True
                break

            time.sleep(2)

        if not success:
            raise PanoptesAPIException(
                '{}_export not ready within {} seconds'.format(
                    export_type,
                    timeout
                )
            )

        return export_description

    def generate_export(self, export_type):
        """
        Start a new export.

        - **export_type** is a string specifying which type of export to start.

        Returns a :py:class:`dict` containing metadata for the new export.
        """

        if export_type in TALK_EXPORT_TYPES:
            return talk.post_data_request(
                'project-{}'.format(self.id),
                export_type.replace('talk_', '')
            )

        return self.http_post(
            self._export_path(export_type),
            json={"media": {"content_type": "text/csv"}},
        )[0]

    def describe_export(self, export_type):
        """
        Fetch metadata for an export.

        - **export_type** is a string specifying which type of export to look
          up.

        Returns a :py:class:`dict` containing metadata for the export.
        """
        if export_type in TALK_EXPORT_TYPES:
            return talk.get_data_request(
                'project-{}'.format(self.id),
                export_type.replace('talk_', '')
            )[0]

        return self.http_get(
            self._export_path(export_type),
        )[0]

    def _export_path(self, export_type):
        return '{}/{}_export'.format(self.id, export_type)
<commit_msg>Add CSV reader wrappers to exports<commit_after>from __future__ import absolute_import, division, print_function

import csv
import datetime
import functools
import time

import requests

from panoptes_client.panoptes import (
    PanoptesAPIException,
    Talk,
)

TALK_EXPORT_TYPES = (
    'talk_comments',
    'talk_tags',
)

talk = Talk()

class Exportable(object):
    """
    Abstract class containing methods for generating and downloading data
    exports.
    """

    def get_export(
        self,
        export_type,
        generate=False,
        wait=False,
        wait_timeout=None,
    ):
        """
        Downloads a data export over HTTP. Returns a `Requests Response
        <http://docs.python-requests.org/en/master/api/#requests.Response>`_
        object containing the content of the export.

        - **export_type** is a string specifying which type of export should be
          downloaded.
        - **generate** is a boolean specifying whether to generate a new export
          and wait for it to be ready, or to just download the latest export.
        - **wait** is a boolean specifying whether to wait for an in-progress
          export to finish, if there is one. Has no effect if ``generate`` is
          ``True``.
        - **wait_timeout** is the number of seconds to wait if ``wait`` is
          ``True``. Has no effect if ``wait`` is ``False`` or if ``generate``
          is ``True``.

        The returned :py:class:`.Response` object has two additional attributes
        as a convenience for working with the CSV content; **csv_reader** and
        **csv_dictreader**, which are wrappers for :py:meth:`.csv.reader`
        and :py:class:`csv.DictReader` respectively. These wrappers take care
        of correctly decoding the export content for the CSV parser.

        Example::

            classification_export = Project(1234).get_export('classifications')
            for row in classification_export.csv_reader():
                print(row)

            classification_export = Project(1234).get_export('classifications')
            for row in classification_export.csv_dictreader():
                print(row)
        """

        if generate:
            self.generate_export(export_type)

        if generate or wait:
            export = self.wait_export(export_type, wait_timeout)
        else:
            export = self.describe_export(export_type)

        if export_type in TALK_EXPORT_TYPES:
            media_url = export['data_requests'][0]['url']
        else:
            media_url = export['media'][0]['src']

        response = requests.get(media_url, stream=True)
        response.csv_reader = functools.partial(
            csv.reader,
            response.iter_lines(decode_unicode=True),
        )
        response.csv_dictreader = functools.partial(
            csv.DictReader,
            response.iter_lines(decode_unicode=True),
        )
        return response

    def wait_export(
        self,
        export_type,
        timeout=None,
    ):
        """
        Blocks until an in-progress export is ready.

        - **export_type** is a string specifying which type of export to wait
          for.
        - **timeout** is the maximum number of seconds to wait.

        If ``timeout`` is given and the export is not ready by the time limit,
        :py:class:`.PanoptesAPIException` is raised.
        """

        success = False
        if timeout:
            end_time = datetime.datetime.now() + datetime.timedelta(
                seconds=timeout
            )

        while (not timeout) or (datetime.datetime.now() < end_time):
            export_description = self.describe_export(
                export_type,
            )

            if export_type in TALK_EXPORT_TYPES:
                export_metadata = export_description['data_requests'][0]
            else:
                export_metadata = export_description['media'][0]['metadata']

            if export_metadata.get('state', '') in ('ready', 'finished'):
                success = True
                break

            time.sleep(2)

        if not success:
            raise PanoptesAPIException(
                '{}_export not ready within {} seconds'.format(
                    export_type,
                    timeout
                )
            )

        return export_description

    def generate_export(self, export_type):
        """
        Start a new export.

        - **export_type** is a string specifying which type of export to start.

        Returns a :py:class:`dict` containing metadata for the new export.
        """

        if export_type in TALK_EXPORT_TYPES:
            return talk.post_data_request(
                'project-{}'.format(self.id),
                export_type.replace('talk_', '')
            )

        return self.http_post(
            self._export_path(export_type),
            json={"media": {"content_type": "text/csv"}},
        )[0]

    def describe_export(self, export_type):
        """
        Fetch metadata for an export.

        - **export_type** is a string specifying which type of export to look
          up.

        Returns a :py:class:`dict` containing metadata for the export.
        """
        if export_type in TALK_EXPORT_TYPES:
            return talk.get_data_request(
                'project-{}'.format(self.id),
                export_type.replace('talk_', '')
            )[0]

        return self.http_get(
            self._export_path(export_type),
        )[0]

    def _export_path(self, export_type):
        return '{}/{}_export'.format(self.id, export_type)
<|endoftext|>