<commit_before># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import (cstr, validate_email_add, cint, comma_and, has_gravatar,
	getdate, nowdate)
from frappe.model.mapper import get_mapped_doc

from erpnext.controllers.selling_controller import SellingController
from frappe.geo.address_and_contact import load_address_and_contact
from erpnext.accounts.party import set_taxes

sender_field = "email_id"

class Lead(SellingController):
	def get_feed(self):
		return '{0}: {1}'.format(_(self.status), self.lead_name)

	def onload(self):
		customer = frappe.db.get_value("Customer", {"lead_name": self.name})
		self.get("__onload").is_customer = customer
		load_address_and_contact(self, "lead")

	def validate(self):
		self._prev = frappe._dict({
			"contact_date": frappe.db.get_value("Lead", self.name, "contact_date") if \
				(not cint(self.get("__islocal"))) else None,
			"contact_by": frappe.db.get_value("Lead", self.name, "contact_by") if \
				(not cint(self.get("__islocal"))) else None,
		})

		self.set_status()
		self.check_email_id_is_unique()

		if self.email_id:
			if not self.flags.ignore_email_validation:
				validate_email_add(self.email_id, True)

			if self.email_id == self.lead_owner:
				frappe.throw(_("Lead Owner cannot be same as the Lead"))

			if self.email_id == self.contact_by:
				frappe.throw(_("Next Contact By cannot be same as the Lead Email Address"))

			self.image = has_gravatar(self.email_id)

		if self.contact_date and getdate(self.contact_date) < nowdate():
			frappe.throw(_("Next Contact Date cannot be in the past"))

	def on_update(self):
		self.add_calendar_event()

	def add_calendar_event(self, opts=None, force=False):
		super(Lead, self).add_calendar_event({
			"owner": self.lead_owner,
			"starts_on": self.contact_date,
			"subject": ('Contact ' + cstr(self.lead_name)),
			"description": ('Contact ' + cstr(self.lead_name)) + \
				(self.contact_by and ('. By : ' + cstr(self.contact_by)) or '')
		}, force)

	def check_email_id_is_unique(self):
		if self.email_id:
			# validate email is unique
			duplicate_leads = frappe.db.sql_list("""select name from tabLead
				where email_id=%s and name!=%s""", (self.email_id, self.name))

			if duplicate_leads:
				frappe.throw(_("Email Address must be unique, already exists for {0}")
					.format(comma_and(duplicate_leads)), frappe.DuplicateEntryError)

	def on_trash(self):
		frappe.db.sql("""update `tabIssue` set lead='' where lead=%s""",
			self.name)

		self.delete_events()

	def has_customer(self):
		return frappe.db.get_value("Customer", {"lead_name": self.name})

	def has_opportunity(self):
		return frappe.db.get_value("Opportunity", {"lead": self.name, "status": ["!=", "Lost"]})

	def has_quotation(self):
		return frappe.db.get_value("Quotation", {
			"lead": self.name,
			"docstatus": 1,
			"status": ["!=", "Lost"]

		})

	def has_lost_quotation(self):
		return frappe.db.get_value("Quotation", {
			"lead": self.name,
			"docstatus": 1,
			"status": "Lost"
		})

@frappe.whitelist()
def make_customer(source_name, target_doc=None):
	return _make_customer(source_name, target_doc)

def _make_customer(source_name, target_doc=None, ignore_permissions=False):
	def set_missing_values(source, target):
		if source.company_name:
			target.customer_type = "Company"
			target.customer_name = source.company_name
		else:
			target.customer_type = "Individual"
			target.customer_name = source.lead_name

		target.customer_group = frappe.db.get_default("Customer Group")

	doclist = get_mapped_doc("Lead", source_name,
		{"Lead": {
			"doctype": "Customer",
			"field_map": {
				"name": "lead_name",
				"company_name": "customer_name",
				"contact_no": "phone_1",
				"fax": "fax_1"
			}
		}}, target_doc, set_missing_values, ignore_permissions=ignore_permissions)

	return doclist

@frappe.whitelist()
def make_opportunity(source_name, target_doc=None):
	target_doc = get_mapped_doc("Lead", source_name,
		{"Lead": {
			"doctype": "Opportunity",
			"field_map": {
				"campaign_name": "campaign",
				"doctype": "enquiry_from",
				"name": "lead",
				"lead_name": "contact_display",
				"company_name": "customer_name",
				"email_id": "contact_email",
				"mobile_no": "contact_mobile"
			}
		}}, target_doc)

	return target_doc

@frappe.whitelist()
def make_quotation(source_name, target_doc=None):
	target_doc = get_mapped_doc("Lead", source_name,
		{"Lead": {
			"doctype": "Quotation",
			"field_map": {
				"name": "lead",
				"lead_name": "customer_name",
			}
		}}, target_doc)
	target_doc.quotation_to = "Lead"
	target_doc.run_method("set_missing_values")
	target_doc.run_method("set_other_charges")
	target_doc.run_method("calculate_taxes_and_totals")

	return target_doc

@frappe.whitelist()
def get_lead_details(lead, posting_date=None, company=None):
	if not lead: return {}

	from erpnext.accounts.party import set_address_details
	out = frappe._dict()

	lead_doc = frappe.get_doc("Lead", lead)
	lead = lead_doc

	out.update({
		"territory": lead.territory,
		"customer_name": lead.company_name or lead.lead_name,
		"contact_display": lead.lead_name,
		"contact_email": lead.email_id,
		"contact_mobile": lead.mobile_no,
		"contact_phone": lead.phone,
	})

	set_address_details(out, lead, "Lead")

	taxes_and_charges = set_taxes(None, 'Lead', posting_date, company,
		billing_address=out.get('customer_address'), shipping_address=out.get('shipping_address_name'))
	if taxes_and_charges:
		out['taxes_and_charges'] = taxes_and_charges

	return out
<commit_msg>fix date compare in contact_date<commit_after># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import (cstr, validate_email_add, cint, comma_and, has_gravatar, now)
from frappe.model.mapper import get_mapped_doc

from erpnext.controllers.selling_controller import SellingController
from frappe.geo.address_and_contact import load_address_and_contact
from erpnext.accounts.party import set_taxes

sender_field = "email_id"

class Lead(SellingController):
	def get_feed(self):
		return '{0}: {1}'.format(_(self.status), self.lead_name)

	def onload(self):
		customer = frappe.db.get_value("Customer", {"lead_name": self.name})
		self.get("__onload").is_customer = customer
		load_address_and_contact(self, "lead")

	def validate(self):
		self._prev = frappe._dict({
			"contact_date": frappe.db.get_value("Lead", self.name, "contact_date") if \
				(not cint(self.get("__islocal"))) else None,
			"contact_by": frappe.db.get_value("Lead", self.name, "contact_by") if \
				(not cint(self.get("__islocal"))) else None,
		})

		self.set_status()
		self.check_email_id_is_unique()

		if self.email_id:
			if not self.flags.ignore_email_validation:
				validate_email_add(self.email_id, True)

			if self.email_id == self.lead_owner:
				frappe.throw(_("Lead Owner cannot be same as the Lead"))

			if self.email_id == self.contact_by:
				frappe.throw(_("Next Contact By cannot be same as the Lead Email Address"))

			self.image = has_gravatar(self.email_id)

		if self.contact_date and self.contact_date < now():
			frappe.throw(_("Next Contact Date cannot be in the past"))

	def on_update(self):
		self.add_calendar_event()

	def add_calendar_event(self, opts=None, force=False):
		super(Lead, self).add_calendar_event({
			"owner": self.lead_owner,
			"starts_on": self.contact_date,
			"subject": ('Contact ' + cstr(self.lead_name)),
			"description": ('Contact ' + cstr(self.lead_name)) + \
				(self.contact_by and ('. By : ' + cstr(self.contact_by)) or '')
		}, force)

	def check_email_id_is_unique(self):
		if self.email_id:
			# validate email is unique
			duplicate_leads = frappe.db.sql_list("""select name from tabLead
				where email_id=%s and name!=%s""", (self.email_id, self.name))

			if duplicate_leads:
				frappe.throw(_("Email Address must be unique, already exists for {0}")
					.format(comma_and(duplicate_leads)), frappe.DuplicateEntryError)

	def on_trash(self):
		frappe.db.sql("""update `tabIssue` set lead='' where lead=%s""",
			self.name)

		self.delete_events()

	def has_customer(self):
		return frappe.db.get_value("Customer", {"lead_name": self.name})

	def has_opportunity(self):
		return frappe.db.get_value("Opportunity", {"lead": self.name, "status": ["!=", "Lost"]})

	def has_quotation(self):
		return frappe.db.get_value("Quotation", {
			"lead": self.name,
			"docstatus": 1,
			"status": ["!=", "Lost"]

		})

	def has_lost_quotation(self):
		return frappe.db.get_value("Quotation", {
			"lead": self.name,
			"docstatus": 1,
			"status": "Lost"
		})

@frappe.whitelist()
def make_customer(source_name, target_doc=None):
	return _make_customer(source_name, target_doc)

def _make_customer(source_name, target_doc=None, ignore_permissions=False):
	def set_missing_values(source, target):
		if source.company_name:
			target.customer_type = "Company"
			target.customer_name = source.company_name
		else:
			target.customer_type = "Individual"
			target.customer_name = source.lead_name

		target.customer_group = frappe.db.get_default("Customer Group")

	doclist = get_mapped_doc("Lead", source_name,
		{"Lead": {
			"doctype": "Customer",
			"field_map": {
				"name": "lead_name",
				"company_name": "customer_name",
				"contact_no": "phone_1",
				"fax": "fax_1"
			}
		}}, target_doc, set_missing_values, ignore_permissions=ignore_permissions)

	return doclist

@frappe.whitelist()
def make_opportunity(source_name, target_doc=None):
	target_doc = get_mapped_doc("Lead", source_name,
		{"Lead": {
			"doctype": "Opportunity",
			"field_map": {
				"campaign_name": "campaign",
				"doctype": "enquiry_from",
				"name": "lead",
				"lead_name": "contact_display",
				"company_name": "customer_name",
				"email_id": "contact_email",
				"mobile_no": "contact_mobile"
			}
		}}, target_doc)

	return target_doc

@frappe.whitelist()
def make_quotation(source_name, target_doc=None):
	target_doc = get_mapped_doc("Lead", source_name,
		{"Lead": {
			"doctype": "Quotation",
			"field_map": {
				"name": "lead",
				"lead_name": "customer_name",
			}
		}}, target_doc)
	target_doc.quotation_to = "Lead"
	target_doc.run_method("set_missing_values")
	target_doc.run_method("set_other_charges")
	target_doc.run_method("calculate_taxes_and_totals")

	return target_doc

@frappe.whitelist()
def get_lead_details(lead, posting_date=None, company=None):
	if not lead: return {}

	from erpnext.accounts.party import set_address_details
	out = frappe._dict()

	lead_doc = frappe.get_doc("Lead", lead)
	lead = lead_doc

	out.update({
		"territory": lead.territory,
		"customer_name": lead.company_name or lead.lead_name,
		"contact_display": lead.lead_name,
		"contact_email": lead.email_id,
		"contact_mobile": lead.mobile_no,
		"contact_phone": lead.phone,
	})

	set_address_details(out, lead, "Lead")

	taxes_and_charges = set_taxes(None, 'Lead', posting_date, company,
		billing_address=out.get('customer_address'), shipping_address=out.get('shipping_address_name'))
	if taxes_and_charges:
		out['taxes_and_charges'] = taxes_and_charges

	return out
<|endoftext|>


<commit_before>"""Generates the url of the latest video uploaded on Youtube"""

import requests
import json
from settings import *

# Gets response
r = requests.get(Youtube_base_url + Youtube_api_key)

# Generates the latest video url
try:
    if r.status_code == 200:
        json_data = json.loads(r.text)
        video_id = (json_data['items'][0]['snippet']['resourceId']['videoId'])
        video_url = Youtube_watch_url + video_id
    else:
        raise Exception(r)
except Exception as e:
    print(e)
<commit_msg>Minor change regarding url<commit_after>"""Generates the url of the latest video uploaded on Youtube"""

import requests
import json
from settings import *

# Gets response
r = requests.get(Youtube_base_url)

# Generates the latest video url
try:
    if r.status_code == 200:
        json_data = json.loads(r.text)
        video_id = (json_data['items'][0]['snippet']['resourceId']['videoId'])
        video_url = Youtube_watch_url + video_id
    else:
        raise Exception(r)
except Exception as e:
    print(e)
<|endoftext|>


<commit_before>#!/usr/bin/env python
#
# Copyright (C) 2011 Evite LLC

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA

import datetime
import re
import time
import types

try:
    from simplejson import JSONEncoder, JSONDecoder
except:
    try:
        # See if appengine has this module
        from django.utils.simplejson import JSONEncoder, JSONDecoder
    except:
        raise ImportError(
            "Cannot find an appropriate json module. Please easy_install "+\
            "simplejson and try again."
        )

__all__ = [
    'Encoder',
    'json_encode',
    'json_decode',
    'JsonSerializable',
    'json_ensure_string_keys',
    'dehump',
    'hump',
    'Dictomatic',
]

class Encoder(JSONEncoder):

    def default(self, o):
        if hasattr(o, "json"):
            return getattr(o, "json")()
        if isinstance(o, datetime.datetime):
            return o.ctime()
        return JSONEncoder.default(self, o)

_encoder = Encoder()
def json_encode(o):
    return _encoder.encode(o)

_decoder = JSONDecoder()
def json_decode(o):
    # remove tabs if they exists
    o = o.replace('\t','')
    data = _decoder.decode(o)
    return data

class JsonSerializable(object):

    def json(self):
        # TODO: ugly
        d = {}
        for k, v in self.__dict__.iteritems():
            if isinstance(v, JsonSerializable):
                d[k] = v.json()
            elif v is not None:
                d[k] = v
        return d

def json_ensure_string_keys(json):
    return dict([(str(k), v) for k,v in json.items()])

camel_case = re.compile('([a-z]+[A-Z])')
skyline_case = re.compile('([a-z]+_[a-z])')

def dehump(match):
    result = ''
    for group in match.groups():
        result = result + group[0:len(group)-1]+"_"+group[len(group)-1].lower()
    return result

def hump(match):
    result = ''
    for group in match.groups():
        result = result + group[0:len(group)-2]+group[len(group)-1].upper()
    return result

class Dictomatic(dict):

    @classmethod
    def wrap(cls, data, decode=True, start=True):
        if isinstance(data, Dictomatic):
            return data
        if decode and isinstance(data, (types.StringType, types.UnicodeType)):
            data = json_decode(data)
        if not start and isinstance(data, (types.ListType, types.TupleType)):
            for value, index in enumerate(data):
                if isinstance(value, (types.DictType,
                                      types.ListType,
                                      types.TupleType)):
                    data[index] = Dictomatic.wrap(
                        value, decode=False, start=False
                    )
            return data
        elif isinstance(data, types.DictType):
            data = json_ensure_string_keys(data)
            for key, value in data.iteritems():
                if isinstance(value, (types.DictType,
                                      types.ListType,
                                      types.TupleType)):
                    data[key] = Dictomatic.wrap(
                        value, decode=False, start=False
                    )
            return Dictomatic(data)
        elif isinstance(data, types.NoneType):
            return Dictomatic({})
        else:
            raise ValueError('Unexpected type: %s' % type(data))

    def __getattr__(self, name, default=None):
        '''
        Makes a dictionary behave like an object with magic dehumping action.
        '''

        # try it normally
        try:
            return self[name]
        except KeyError:
            if name.startswith('__'):
                raise AttributeError()
            # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
            try:
                return self[skyline_case.sub(hump, name)]
            # it's really not here, let them know
            except KeyError:
                try:
                    return self[camel_case.sub(dehump, name)]
                # it's really not here, let them know
                except KeyError:
                    return default

    def __setattr__(self, name, value):
        self[name] = value

<commit_msg>Using enumerate properly :)<commit_after>#!/usr/bin/env python
#
# Copyright (C) 2011 Evite LLC

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA

import datetime
import re
import time
import types

try:
    from simplejson import JSONEncoder, JSONDecoder
except:
    try:
        # See if appengine has this module
        from django.utils.simplejson import JSONEncoder, JSONDecoder
    except:
        raise ImportError(
            "Cannot find an appropriate json module. Please easy_install "+\
            "simplejson and try again."
        )

__all__ = [
    'Encoder',
    'json_encode',
    'json_decode',
    'JsonSerializable',
    'json_ensure_string_keys',
    'dehump',
    'hump',
    'Dictomatic',
]

class Encoder(JSONEncoder):

    def default(self, o):
        if hasattr(o, "json"):
            return getattr(o, "json")()
        if isinstance(o, datetime.datetime):
            return o.ctime()
        return JSONEncoder.default(self, o)

_encoder = Encoder()
def json_encode(o):
    return _encoder.encode(o)

_decoder = JSONDecoder()
def json_decode(o):
    # remove tabs if they exists
    o = o.replace('\t','')
    data = _decoder.decode(o)
    return data

class JsonSerializable(object):

    def json(self):
        # TODO: ugly
        d = {}
        for k, v in self.__dict__.iteritems():
            if isinstance(v, JsonSerializable):
                d[k] = v.json()
            elif v is not None:
                d[k] = v
        return d

def json_ensure_string_keys(json):
    return dict([(str(k), v) for k,v in json.items()])

camel_case = re.compile('([a-z]+[A-Z])')
skyline_case = re.compile('([a-z]+_[a-z])')

def dehump(match):
    result = ''
    for group in match.groups():
        result = result + group[0:len(group)-1]+"_"+group[len(group)-1].lower()
    return result

def hump(match):
    result = ''
    for group in match.groups():
        result = result + group[0:len(group)-2]+group[len(group)-1].upper()
    return result

class Dictomatic(dict):

    @classmethod
    def wrap(cls, data, decode=True, start=True):
        if isinstance(data, Dictomatic):
            return data
        if decode and isinstance(data, (types.StringType, types.UnicodeType)):
            data = json_decode(data)
        if not start and isinstance(data, (types.ListType, types.TupleType)):
            for index, value in enumerate(data):
                if isinstance(value, (types.DictType,
                                      types.ListType,
                                      types.TupleType)):
                    data[index] = Dictomatic.wrap(
                        value, decode=False, start=False
                    )
            return data
        elif isinstance(data, types.DictType):
            data = json_ensure_string_keys(data)
            for key, value in data.iteritems():
                if isinstance(value, (types.DictType,
                                      types.ListType,
                                      types.TupleType)):
                    data[key] = Dictomatic.wrap(
                        value, decode=False, start=False
                    )
            return Dictomatic(data)
        elif isinstance(data, types.NoneType):
            return Dictomatic({})
        else:
            raise ValueError('Unexpected type: %s' % type(data))

    def __getattr__(self, name, default=None):
        '''
        Makes a dictionary behave like an object with magic dehumping action.
        '''

        # try it normally
        try:
            return self[name]
        except KeyError:
            if name.startswith('__'):
                raise AttributeError()
            # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
            try:
                return self[skyline_case.sub(hump, name)]
            # it's really not here, let them know
            except KeyError:
                try:
                    return self[camel_case.sub(dehump, name)]
                # it's really not here, let them know
                except KeyError:
                    return default

    def __setattr__(self, name, value):
        self[name] = value

<|endoftext|>


<commit_before>from django.forms.forms import NON_FIELD_ERRORS
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils.http import is_safe_url
from django.utils.translation import ugettext as _
from requests.exceptions import HTTPError
from six.moves.urllib.parse import urlparse

from .forms import TicketForm

RETURN_URL_FIELD = 'next'

def get_safe_return_to(request, return_to):
    # Ensure the user-originating redirection url is safe.
    if not return_to or not is_safe_url(url=return_to, host=request.get_host()):
        return None
    return return_to

def ticket(request,
           template_name=None,
           success_redirect_url='/',
           ticket_template_name='zendesk_tickets/ticket.txt',
           form_class=TicketForm,
           subject='Website Ticket',
           tags=[],
           extra_context=None):
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            return_to = get_safe_return_to(request, form.cleaned_data.get('referer'))
            try:
                form.submit_ticket(request, subject, tags, ticket_template_name)
                if return_to:
                    return_to = urlparse(return_to).path
                    success_redirect_url = (
                        success_redirect_url +
                        ('?%s=%s' % (RETURN_URL_FIELD, return_to))
                    )
                return HttpResponseRedirect(success_redirect_url)
            except HTTPError:
                form.add_error(NON_FIELD_ERRORS, _('Unexpected error.'))
        else:
            return_to = get_safe_return_to(request, request.POST.get('referer'))
    else:
        return_to = get_safe_return_to(request, request.META.get('HTTP_REFERER'))
        form = form_class(
            initial={'referer': return_to}
        )

    context = {'form': form, 'return_to': return_to}
    if extra_context:
        context.update(extra_context)
    return render(request, template_name, context=context)

def success(request, template_name=None, extra_context=None):
    return_to = get_safe_return_to(request, request.GET.get(RETURN_URL_FIELD))
    context = {'return_to': return_to}
    if extra_context:
        context.update(extra_context)
    return render(request, template_name, context=context)
<commit_msg>Don’t allow self-referential return-to URL<commit_after>from django.forms.forms import NON_FIELD_ERRORS
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils.http import is_safe_url
from django.utils.translation import ugettext as _
from requests.exceptions import HTTPError
from six.moves.urllib.parse import urlparse

from .forms import TicketForm

RETURN_URL_FIELD = 'next'

def get_safe_return_to(request, return_to):
    # Ensure the user-originating redirection url is safe.
    if return_to and is_safe_url(url=return_to, host=request.get_host()) and return_to != request.build_absolute_uri():
        return return_to
    return None

def ticket(request,
           template_name=None,
           success_redirect_url='/',
           ticket_template_name='zendesk_tickets/ticket.txt',
           form_class=TicketForm,
           subject='Website Ticket',
           tags=[],
           extra_context=None):
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            return_to = get_safe_return_to(request, form.cleaned_data.get('referer'))
            try:
                form.submit_ticket(request, subject, tags, ticket_template_name)
                if return_to:
                    return_to = urlparse(return_to).path
                    success_redirect_url = (
                        success_redirect_url +
                        ('?%s=%s' % (RETURN_URL_FIELD, return_to))
                    )
                return HttpResponseRedirect(success_redirect_url)
            except HTTPError:
                form.add_error(NON_FIELD_ERRORS, _('Unexpected error.'))
        else:
            return_to = get_safe_return_to(request, request.POST.get('referer'))
    else:
        return_to = get_safe_return_to(request, request.META.get('HTTP_REFERER'))
        form = form_class(
            initial={'referer': return_to}
        )

    context = {'form': form, 'return_to': return_to}
    if extra_context:
        context.update(extra_context)
    return render(request, template_name, context=context)

def success(request, template_name=None, extra_context=None):
    return_to = get_safe_return_to(request, request.GET.get(RETURN_URL_FIELD))
    context = {'return_to': return_to}
    if extra_context:
        context.update(extra_context)
    return render(request, template_name, context=context)
<|endoftext|>


<commit_before>import colander
import logging
import copy
import webhelpers2.html.tags as tags

from ziggurat_form.exceptions import FormInvalid

log = logging.getLogger(__name__)

def while_parent(widget, path):
    if widget.position is not None:
        path.append(str(widget.position))
    else:
        path.append(widget.name)
    if widget.parent_widget and widget.parent_widget.name != '__root__':
        while_parent(widget.parent_widget, path)
    return path

class DummyNode(object):
    def __init__(self, name, widget=None):
        self.name = name
        self.widget = widget

class BaseWidget(object):
    _marker_type = None

    def __init__(self, custom_label=None, validators=None, *args, **kwargs):
        self.cloned = False
        self.custom_label = custom_label
        self.args = args
        self.kwargs = kwargs
        self.form = None
        self.validators = validators or []
        self.position = None
        self.node = None
        self.parent_widget = None
        self.required = False

    @property
    def name(self):
        return self.node.name

    def __str__(self):
        return '<{} {} of {}: p: {}>'.format(
            self.__class__.__name__,
            self.name,
            self.parent_widget.name if self.parent_widget else '',
            self.position
        )

    def clone(self):
        clone = copy.copy(self)
        # clone = self.__class__()
        clone.node = self.node
        clone.form = self.form
        clone.cloned = True
        return clone

    def coerce(self):
        print('coerce run', self.coerced_data)

    def validate(self):
        """
        Return all messages returned by validators, if validator returns True
        then it is considered to pass
        """
        errors = []
        for validator in self.validators:
            try:
                validator(self)
            except FormInvalid as exc:
                errors.append(exc.message)

        self.form.widget_errors[self.error_path] = errors
        return len(errors) == 0

    @property
    def children(self):
        return None

    # @property
    # def required(self):
    #     return self.field.required or len(self.validators) > 0

    @property
    def label(self):
        return self.custom_label or self.node.name.replace('_', ' ').capitalize()

    @property
    def error_path(self):
        return '.'.join(reversed(while_parent(self, [])))

    @property
    def schema_errors(self):
        errors = self.form.schema_errors.get(self.error_path)
        if errors:
            return [errors]
        return []

    @property
    def widget_errors(self):
        errors = self.form.widget_errors.get(self.error_path)
        return errors or []

    @property
    def errors(self):
        return self.widget_errors + self.schema_errors

    def __call__(self, *args, **kwargs):
        return '<{}>'.format(self.name)

    @property
    def marker_start(self):
        if self._marker_type is not None:
            return tags.hidden('__start__', '{}:{}'.format(self.name or '_ziggurat_form_field_',
                                                           self._marker_type), id=None)
        return ''

    @property
    def marker_end(self):
        if self._marker_type is not None:
            return tags.hidden('__end__', '{}:{}'.format(self.name or '_ziggurat_form_field_',
                                                         self._marker_type), id=None)
        return ''

    @property
    def data(self):
        p_widget = self.parent_widget
        parent_is_mapping = isinstance(p_widget, MappingWidget)

        if not p_widget:
            return

        data = p_widget.data

        if self.position is not None:
            if data and len(data) > self.position:
                return data[self.position]
        elif parent_is_mapping:
            if data:
                return data.get(self.name)
        else:
            log.error('something went wrong with field {}'.format(self.name))

    @property
    def coerced_data(self):
        p_widget = self.parent_widget
        parent_is_mapping = isinstance(p_widget, MappingWidget)

        if not p_widget:
            return

        data = p_widget.coerced_data

        if self.position is not None:
            if data and len(data) > self.position:
                return data[self.position]
        elif parent_is_mapping:
            if data and hasattr(data, 'get'):
                return data.get(self.name)
        else:
            log.error('something went wrong with field {}'.format(self.name))

class MappingWidget(BaseWidget):
    _marker_type = 'mapping'

    def __init__(self, *args, **kwargs):
        super(MappingWidget, self).__init__(*args, **kwargs)

    @property
    def children(self):
        snodes = []
        for item in self.node.children:
            cloned = item.clone()
            cloned.widget = cloned.widget.clone()
            cloned.widget.parent_widget = self
            snodes.append(cloned.widget)
        return snodes

    def __call__(self, *args, **kwargs):
        return ''

class FormWidget(MappingWidget):
    _marker_type = None

    name = "__root__"

    def __init__(self, *args, **kwargs):
        super(FormWidget, self).__init__(*args, **kwargs)
        self.non_coerced_data = {}

    def __call__(self, *args, **kwargs):
        return ''

    @property
    def data(self):
        return self.non_coerced_data

    @property
    def coerced_data(self):
        return self.coerced_data_holder

class TupleWidget(BaseWidget):
    _marker_type = 'sequence'

    def __init__(self, *args, **kwargs):
        super(TupleWidget, self).__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        return ''

    @property
    def children(self):
        results = []
        for i, item in enumerate(self.node.children):
            cloned = item.clone()
            cloned.widget = cloned.widget.clone()
            cloned.widget.position = i
            cloned.widget.parent_widget = self
            results.append(cloned.widget)

        return results

class PositionalWidget(BaseWidget):
    _marker_type = 'sequence'

    def __init__(self, *args, **kwargs):
        super(PositionalWidget, self).__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        return ''

    @property
    def children(self):
        results = []
        to_create = len(self.data or [1])
        for i in range(0, to_create):
            cloned = self.node.children[0].clone()
            cloned.widget = cloned.widget.clone()
            cloned.widget.position = i
            cloned.widget.parent_widget = self
            results.append(cloned.widget)
        return results

class TextWidget(BaseWidget):
    def __call__(self, *args, **kwargs):
        val = self.data
        print('text widget', self.data)
        if val is colander.null:
            val = ''
        return tags.text(self.name, val, *args, **kwargs)

class PasswordWidget(BaseWidget):
    def __call__(self, *args, **kwargs):
        val = self.data
        if val is colander.null:
            val = ''
        return tags.password(self.name, val, *args, **kwargs)

def confirm_validator(field):
    confirm_data = field.data
    original_data = field.parent_widget.data.get(field.name[:-8])
    if confirm_data != original_data:
        raise FormInvalid("Confirm field does not match")
    return True

class ConfirmWidget(MappingWidget):
    _marker_type = 'mapping'

    def __init__(self, widget_to_confirm, *args, **kwargs):
        super(ConfirmWidget, self).__init__(*args, **kwargs)
        self.widget_to_confirm = widget_to_confirm
        self.org_node = None

    def coerce(self):
        to_replace = self.coerced_data.get(self.name)
        self.parent_widget.coerced_data[self.name] = to_replace
        log.info('XXXX {} {}'.format(self.name, self.coerced_data))

    @property
    def children(self):
        self.widget_to_confirm.node = self.node
        self.widget_to_confirm.form = self.form
        self.widget_to_confirm.parent_widget = self

        confirm_node = self.widget_to_confirm.clone()
        confirm_node.node = DummyNode(self.node.name + '_confirm')
        confirm_node.validators = [confirm_validator]

        snodes = [
            self.widget_to_confirm,
            confirm_node
        ]
        return snodes
<commit_msg>++SelectWidget<commit_after>import colander
import logging
import copy
import webhelpers2.html.tags as tags

from ziggurat_form.exceptions import FormInvalid

log = logging.getLogger(__name__)

def while_parent(widget, path):
    if widget.position is not None:
        path.append(str(widget.position))
    else:
        path.append(widget.name)
    if widget.parent_widget and widget.parent_widget.name != '__root__':
        while_parent(widget.parent_widget, path)
    return path

class DummyNode(object):
    def __init__(self, name, widget=None):
        self.name = name
        self.widget = widget

class BaseWidget(object):
    _marker_type = None

    def __init__(self, custom_label=None, validators=None, *args, **kwargs):
        self.cloned = False
        self.custom_label = custom_label
        self.args = args
        self.kwargs = kwargs
        self.form = None
        self.validators = validators or []
        self.position = None
        self.node = None
        self.parent_widget = None
        self.required = False

    @property
    def name(self):
        return self.node.name

    def __str__(self):
        return '<{} {} of {}: p: {}>'.format(
            self.__class__.__name__,
            self.name,
            self.parent_widget.name if self.parent_widget else '',
            self.position
        )

    def clone(self):
        clone = copy.copy(self)
        # clone = self.__class__()
        clone.node = self.node
        clone.form = self.form
        clone.cloned = True
        return clone

    def coerce(self):
        print('coerce run', self.coerced_data)

    def validate(self):
        """
        Return all messages returned by validators, if validator returns True
        then it is considered to pass
        """
        errors = []
        for validator in self.validators:
            try:
                validator(self)
            except FormInvalid as exc:
                errors.append(exc.message)

        self.form.widget_errors[self.error_path] = errors
        return len(errors) == 0

    @property
    def children(self):
        return None

    # @property
    # def required(self):
    #     return self.field.required or len(self.validators) > 0

    @property
    def label(self):
        return self.custom_label or self.node.name.replace('_', ' ').capitalize()

    @property
    def error_path(self):
        return '.'.join(reversed(while_parent(self, [])))

    @property
    def schema_errors(self):
        errors = self.form.schema_errors.get(self.error_path)
        if errors:
            return [errors]
        return []

    @property
    def widget_errors(self):
        errors = self.form.widget_errors.get(self.error_path)
        return errors or []

    @property
    def errors(self):
        return self.widget_errors + self.schema_errors

    def __call__(self, *args, **kwargs):
        return '<{}>'.format(self.name)

    @property
    def marker_start(self):
        if self._marker_type is not None:
            return tags.hidden('__start__', '{}:{}'.format(self.name or '_ziggurat_form_field_',
                                                           self._marker_type), id=None)
        return ''

    @property
    def marker_end(self):
        if self._marker_type is not None:
            return tags.hidden('__end__', '{}:{}'.format(self.name or '_ziggurat_form_field_',
                                                         self._marker_type), id=None)
        return ''

    @property
    def data(self):
        p_widget = self.parent_widget
        parent_is_mapping = isinstance(p_widget, MappingWidget)

        if not p_widget:
            return

        data = p_widget.data

        if self.position is not None:
            if data and len(data) > self.position:
                return data[self.position]
        elif parent_is_mapping:
            if data:
                return data.get(self.name)
        else:
            log.error('something went wrong with field {}'.format(self.name))

    @property
    def coerced_data(self):
        p_widget = self.parent_widget
        parent_is_mapping = isinstance(p_widget, MappingWidget)

        if not p_widget:
            return

        data = p_widget.coerced_data

        if self.position is not None:
            if data and len(data) > self.position:
                return data[self.position]
        elif parent_is_mapping:
            if data and hasattr(data, 'get'):
                return data.get(self.name)
        else:
            log.error('something went wrong with field {}'.format(self.name))

class MappingWidget(BaseWidget):
    _marker_type = 'mapping'

    def __init__(self, *args, **kwargs):
        super(MappingWidget, self).__init__(*args, **kwargs)

    @property
    def children(self):
        snodes = []
        for item in self.node.children:
            cloned = item.clone()
            cloned.widget = cloned.widget.clone()
            cloned.widget.parent_widget = self
            snodes.append(cloned.widget)
        return snodes

    def __call__(self, *args, **kwargs):
        return ''

class FormWidget(MappingWidget):
    _marker_type = None

    name = "__root__"

    def __init__(self, *args, **kwargs):
        super(FormWidget, self).__init__(*args, **kwargs)
        self.non_coerced_data = {}

    def __call__(self, *args, **kwargs):
        return ''

    @property
    def data(self):
        return self.non_coerced_data

    @property
    def coerced_data(self):
        return self.coerced_data_holder

class TupleWidget(BaseWidget):
    _marker_type = 'sequence'

    def __init__(self, *args, **kwargs):
        super(TupleWidget, self).__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        return ''

    @property
    def children(self):
        results = []
        for i, item in enumerate(self.node.children):
            cloned = item.clone()
            cloned.widget = cloned.widget.clone()
            cloned.widget.position = i
            cloned.widget.parent_widget = self
            results.append(cloned.widget)

        return results

class PositionalWidget(BaseWidget):
    _marker_type = 'sequence'

    def __init__(self, *args, **kwargs):
        super(PositionalWidget, self).__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        return ''

    @property
    def children(self):
        results = []
        to_create = len(self.data or [1])
        for i in range(0, to_create):
            cloned = self.node.children[0].clone()
            cloned.widget = cloned.widget.clone()
            cloned.widget.position = i
            cloned.widget.parent_widget = self
            results.append(cloned.widget)
        return results

class TextWidget(BaseWidget):
    def __call__(self, *args, **kwargs):
        val = self.data
        print('text widget', self.data)
        if val is colander.null:
            val = ''
        return tags.text(self.name, val, *args, **kwargs)

class PasswordWidget(BaseWidget):
    def __call__(self, *args, **kwargs):
        val = self.data
        if val is colander.null:
            val = ''
        return tags.password(self.name, val, *args, **kwargs)

class SelectWidget(BaseWidget):
    def __call__(self, *args, **kwargs):
        val = self.data
        if val is colander.null:
            val = ''
        return tags.select(self.name, val, *args, **kwargs)

def confirm_validator(field):
    confirm_data = field.data
    original_data = field.parent_widget.data.get(field.name[:-8])
    if confirm_data != original_data:
        raise FormInvalid("Confirm field does not match")
    return True

class ConfirmWidget(MappingWidget):
    _marker_type = 'mapping'

    def __init__(self, widget_to_confirm, *args, **kwargs):
        super(ConfirmWidget, self).__init__(*args, **kwargs)
        self.widget_to_confirm = widget_to_confirm
        self.org_node = None

    def coerce(self):
        to_replace = self.coerced_data.get(self.name)
        self.parent_widget.coerced_data[self.name] = to_replace
        log.info('XXXX {} {}'.format(self.name, self.coerced_data))

    @property
    def children(self):
        self.widget_to_confirm.node = self.node
        self.widget_to_confirm.form = self.form
        self.widget_to_confirm.parent_widget = self

        confirm_node = self.widget_to_confirm.clone()
        confirm_node.node = DummyNode(self.node.name + '_confirm')
        confirm_node.validators = [confirm_validator]

        snodes = [
            self.widget_to_confirm,
            confirm_node
        ]
        return snodes
<|endoftext|>


<commit_before>
# PB - PlayBlaster
# Generates playblast from current maya scene. Includes camera focal length.

import maya.cmds as cmds
import os

#from dpaCreateFS import *
from dpa.ptask.area import PTaskArea

def playblast_dialog():
  # Creates a dialog prompt to determine if the user wishes to create a playblast
  #response = cmds.confirmDialog( title='Playblast', message='Are you SURE you want to create a new playblast?', button=['Yes','No'], defaultButton='No', cancelButton='No', dismissString='No' )
  #if response == 'Yes':
  floatUI()

def floatUI():
  # Check to see if window exists
  if cmds.window("PBQuality", exists=True):
    cmds.deleteUI("PBQuality")

  # Create window
  window = cmds.window("PBQuality", title="DPA Playblast", w=300, h=100, mnb=False, mxb=False, sizeable=False)

  # Create a main layout
  mainLayout = cmds.columnLayout(adj=True)
  blastLayout = cmds.columnLayout("blastLayout", p=mainLayout, w=260, adj=False, rs=5, cat=('left', 5))
  cmds.separator(p=blastLayout)

  cmds.text(label="Enter desired playbast quality:", p=blastLayout)
  qualityField = cmds.floatField("playblastValue", p=blastLayout, w=250, min=50, max=100, pre=0, step=1, v=90, ed=True)
  qualitySlider = cmds.floatSlider("playblastPercentage", p=blastLayout, w=250, min=50, max=100, step=1, v=90, dc=updatePercent)
  cmds.separator(p=blastLayout)

  sequenceOption = cmds.checkBox("sequenceOption", label="From Sequence", value=False)
  reviewOption = cmds.checkBox("reviewOption", label="Auto-bot review submission", value=False)
  cmds.separator(p=blastLayout)

  confirmLayout = cmds.rowColumnLayout("confirmLayout", p=mainLayout, w=250, nc=2, rs=(5, 5), co=[(1, 'left', 5), (2, 'right', 5)], cw=[(1, 125), (2, 125)])
  cancelButton = cmds.button("cancelButton", p=confirmLayout, label="Cancel", c="cmds.deleteUI('PBQuality')", w=80, h=30)
  pbButton = cmds.button("pbButton", p=confirmLayout, label="Playblast", c=handlePB, w=100, h=30)
  cmds.separator(p=confirmLayout)

  cmds.showWindow(window)

def updatePercent(*args):
  percent = cmds.floatSlider("playblastPercentage", q=True, v=True)
  cmds.floatField("playblastValue", e=True, v=percent)

def handlePB(*args):
  percent = cmds.floatField("playblastValue", q=True, v=True)
  #check to see if sequence option is selected
  seqTag = cmds.checkBox("sequenceOption", query=True, value =True)
  #check for auto review submission
  revTag = cmds.checkBox("reviewOption", query=True, value =True)
  runPB(percent, seqTag, revTag)

def runPB(quality, sequence, autoReview):
  #Get the file unix path of the maya file
  filePath = cmds.file(q=True, sceneName=True)
  #Parse the unix path and convert it into a dpa fspattern

  if quality < 50:
    print "Lower than 50 percent quality may result in very poor imaging..."
    cmds.deleteUI("PBQuality")
    return

  print "Percentage chosen: " + str(quality)
  print "From Sequence: " + str(sequence)
  print "AutoSubmit: " + str(autoReview)

  #Attempts to create a playblast of the current maya scene
  success = playblaster(quality, sequence, autoReview)

  if success:
    print "Successfully generated playblast :)"
  else:
    print "Failed to generate playblast :("

def playblaster(quality, sequence, autoReview):
  #Does some error checking to ensure the fspattern is correct
    area = PTaskArea.current()
    spec = None
    if area:
        spec = area.spec
    else:
        print "You need to dpaset into a ptask to use this tool."
        return False
    currentCam = cmds.modelPanel(cmds.getPanel(wf=True), q=True, cam=True)
    focalLength = cmds.camera(currentCam, q=True, fl=True)
    cameraName = currentCam.title() + "Fov" + str(focalLength)
    specName = spec.name(spec).title()

    if not autoReview:
        playblastdir = "/scratch" + area.dir()
        #listing = os.listdir(playblastdir)
        print "Making directory " + playblastdir
        os.system( "mkdir -p " + playblastdir )
        #get a listing of the version numbers in the directory
        nbversions = len(os.listdir(playblastdir))
        versionFrame = "%04d" % (nbversions + 1 )
        fileName = "%s/playblast%s%s-%s" % (playblastdir,specName,cameraName,versionFrame)
        print "writing playblast to file " + fileName + ".mov"
        xVal = cmds.getAttr('defaultResolution.width')
        yVal = cmds.getAttr('defaultResolution.height')
        if sequence:
            sqMgr = cmds.listConnections('sequenceManager1', s=True, d=False)[0]
            seqEnd = cmds.getAttr(str(sqMgr)+".maxFrame")
            seqStart = cmds.getAttr(str(sqMgr) +".minFrame")
            print "SqStart: " + str(seqStart)
            print "SqEnd: " + str(seqEnd)
            cmds.playblast(startTime=seqStart, endTime=seqEnd, sequenceTime=sequence, f=fileName, percent=quality, offScreen=True, format="qt", width=xVal, height=yVal)
        else:
            cmds.playblast(f=fileName, percent=quality, offScreen=True, format="qt", width=xVal, height=yVal)
        cmds.deleteUI("PBQuality")
        os.chmod(fileName+ ".mov", 0777)
        os.system( "vlc " + fileName + ".mov &" )
        return True
    if autoReview:
        #create a product to put this in
        xVal = cmds.getAttr('defaultResolution.width')
        yVal = cmds.getAttr('defaultResolution.height')
        product_spec = "playblast=movie"
        product_type = "mov"
        product_resolution = str(xVal) + "x" + str(yVal)
        product_description = "auto generated in dpa playblast tool"
        from dpa.action.registry import ActionRegistry
        create_action_cls = ActionRegistry().get_action('create', 'product')
        create_action = create_action_cls(product=product_spec, ptask=spec, description=product_description, file_type=product_type, resolution=product_resolution )
        try:
            create_action()
        except ActionError as e:
            raise EntityError("Unable to create a product: " + str(e) )

        #use product to get the directory path
        area = create_action.product_repr.area
        playblastdir = area.dir()
        versionFrame = create_action.product_version.number_padded
        baseFileName = "playblast%s%s-%s" % (specName,cameraName,versionFrame)
        fileName = playblastdir + "/" + baseFileName
        print "writing playblast to file " + fileName + ".mov"
        if sequence:
            sqMgr = cmds.listConnections('sequenceManager1', s=True, d=False)[0]
            seqEnd = cmds.getAttr(str(sqMgr)+".maxFrame")
            seqStart = cmds.getAttr(str(sqMgr) +".minFrame")
            print "SqStart: " + str(seqStart)
            print "SqEnd: " + str(seqEnd)
            cmds.playblast(startTime=seqStart, endTime=seqEnd, sequenceTime=sequence, f=fileName, percent=quality, offScreen=True, format="qt", width=xVal, height=yVal)
        else:
            cmds.playblast(f=fileName, percent=quality, offScreen=True, format="qt", width=xVal, height=yVal)
        cmds.deleteUI("PBQuality")
        os.chmod(fileName+ ".mov", 0777)
        reviewcmd = "cd " + playblastdir + "; dpacreatereview " + baseFileName + ".mov " +  str(create_action.product_repr.spec)
        print "creating review: " + reviewcmd
        os.system( reviewcmd )
        os.system( "vlc " + fileName + ".mov &" )
        return True

    cmds.error("Invalid selections.")
    return False

<commit_msg>fixed camera name to exclude pipe symbols<commit_after>
# PB - PlayBlaster
# Generates playblast from current maya scene. Includes camera focal length.

import maya.cmds as cmds
import os

#from dpaCreateFS import *
from dpa.ptask.area import PTaskArea

def playblast_dialog():
  # Creates a dialog prompt to determine if the user wishes to create a playblast
  #response = cmds.confirmDialog( title='Playblast', message='Are you SURE you want to create a new playblast?', button=['Yes','No'], defaultButton='No', cancelButton='No', dismissString='No' )
  #if response == 'Yes':
  floatUI()

def floatUI():
  # Check to see if window exists
  if cmds.window("PBQuality", exists=True):
    cmds.deleteUI("PBQuality")

  # Create window
  window = cmds.window("PBQuality", title="DPA Playblast", w=300, h=100, mnb=False, mxb=False, sizeable=False)

  # Create a main layout
  mainLayout = cmds.columnLayout(adj=True)
  blastLayout = cmds.columnLayout("blastLayout", p=mainLayout, w=260, adj=False, rs=5, cat=('left', 5))
  cmds.separator(p=blastLayout)

  cmds.text(label="Enter desired playbast quality:", p=blastLayout)
  qualityField = cmds.floatField("playblastValue", p=blastLayout, w=250, min=50, max=100, pre=0, step=1, v=90, ed=True)
  qualitySlider = cmds.floatSlider("playblastPercentage", p=blastLayout, w=250, min=50, max=100, step=1, v=90, dc=updatePercent)
  cmds.separator(p=blastLayout)

  sequenceOption = cmds.checkBox("sequenceOption", label="From Sequence", value=False)
  reviewOption = cmds.checkBox("reviewOption", label="Auto-bot review submission", value=False)
  cmds.separator(p=blastLayout)

  confirmLayout = cmds.rowColumnLayout("confirmLayout", p=mainLayout, w=250, nc=2, rs=(5, 5), co=[(1, 'left', 5), (2, 'right', 5)], cw=[(1, 125), (2, 125)])
  cancelButton = cmds.button("cancelButton", p=confirmLayout, label="Cancel", c="cmds.deleteUI('PBQuality')", w=80, h=30)
  pbButton = cmds.button("pbButton", p=confirmLayout, label="Playblast", c=handlePB, w=100, h=30)
  cmds.separator(p=confirmLayout)

  cmds.showWindow(window)

def updatePercent(*args):
  percent = cmds.floatSlider("playblastPercentage", q=True, v=True)
  cmds.floatField("playblastValue", e=True, v=percent)

def handlePB(*args):
  percent = cmds.floatField("playblastValue", q=True, v=True)
  #check to see if sequence option is selected
  seqTag = cmds.checkBox("sequenceOption", query=True, value =True)
  #check for auto review submission
  revTag = cmds.checkBox("reviewOption", query=True, value =True)
  runPB(percent, seqTag, revTag)

def runPB(quality, sequence, autoReview):
  #Get the file unix path of the maya file
  filePath = cmds.file(q=True, sceneName=True)
  #Parse the unix path and convert it into a dpa fspattern

  if quality < 50:
    print "Lower than 50 percent quality may result in very poor imaging..."
    cmds.deleteUI("PBQuality")
    return

  print "Percentage chosen: " + str(quality)
  print "From Sequence: " + str(sequence)
  print "AutoSubmit: " + str(autoReview)

  #Attempts to create a playblast of the current maya scene
  success = playblaster(quality, sequence, autoReview)

  if success:
    print "Successfully generated playblast :)"
  else:
    print "Failed to generate playblast :("

def playblaster(quality, sequence, autoReview):
  #Does some error checking to ensure the fspattern is correct
    area = PTaskArea.current()
    spec = None
    if area:
        spec = area.spec
    else:
        print "You need to dpaset into a ptask to use this tool."
        return False
    currentCam = cmds.modelPanel(cmds.getPanel(wf=True), q=True, cam=True)
    currentCamMunged = currentCam.replace( '|', '_' )
    focalLength = cmds.camera(currentCam, q=True, fl=True)
    cameraName = currentCamMunged.title() + "Fov" + str(focalLength)
    print "Camera Name: " + cameraName
    specName = spec.name(spec).title()

    if not autoReview:
        playblastdir = "/scratch" + area.dir()
        #listing = os.listdir(playblastdir)
        print "Making directory " + playblastdir
        os.system( "mkdir -p " + playblastdir )
        #get a listing of the version numbers in the directory
        nbversions = len(os.listdir(playblastdir))
        versionFrame = "%04d" % (nbversions + 1 )
        fileName = "%s/playblast%s%s-%s" % (playblastdir,specName,cameraName,versionFrame)
        print "writing playblast to file " + fileName + ".mov"
        xVal = cmds.getAttr('defaultResolution.width')
        yVal = cmds.getAttr('defaultResolution.height')
        if sequence:
            sqMgr = cmds.listConnections('sequenceManager1', s=True, d=False)[0]
            seqEnd = cmds.getAttr(str(sqMgr)+".maxFrame")
            seqStart = cmds.getAttr(str(sqMgr) +".minFrame")
            print "SqStart: " + str(seqStart)
            print "SqEnd: " + str(seqEnd)
            cmds.playblast(startTime=seqStart, endTime=seqEnd, sequenceTime=sequence, f=fileName, percent=quality, offScreen=True, format="qt", width=xVal, height=yVal)
        else:
            cmds.playblast(f=fileName, percent=quality, offScreen=True, format="qt", width=xVal, height=yVal)
        cmds.deleteUI("PBQuality")
        os.chmod(fileName+ ".mov", 0777)
        os.system( "vlc " + fileName + ".mov &" )
        return True
    if autoReview:
        #create a product to put this in
        xVal = cmds.getAttr('defaultResolution.width')
        yVal = cmds.getAttr('defaultResolution.height')
        product_spec = "playblast=movie"
        product_type = "mov"
        product_resolution = str(xVal) + "x" + str(yVal)
        product_description = "auto generated in dpa playblast tool"
        from dpa.action.registry import ActionRegistry
        create_action_cls = ActionRegistry().get_action('create', 'product')
        create_action = create_action_cls(product=product_spec, ptask=spec, description=product_description, file_type=product_type, resolution=product_resolution )
        try:
            create_action()
        except ActionError as e:
            raise EntityError("Unable to create a product: " + str(e) )

        #use product to get the directory path
        area = create_action.product_repr.area
        playblastdir = area.dir()
        versionFrame = create_action.product_version.number_padded
        baseFileName = "playblast%s%s-%s" % (specName,cameraName,versionFrame)
        fileName = playblastdir + "/" + baseFileName
        print "writing playblast to file " + fileName + ".mov"
        if sequence:
            sqMgr = cmds.listConnections('sequenceManager1', s=True, d=False)[0]
            seqEnd = cmds.getAttr(str(sqMgr)+".maxFrame")
            seqStart = cmds.getAttr(str(sqMgr) +".minFrame")
            print "SqStart: " + str(seqStart)
            print "SqEnd: " + str(seqEnd)
            cmds.playblast(startTime=seqStart, endTime=seqEnd, sequenceTime=sequence, f=fileName, percent=quality, offScreen=True, format="qt", width=xVal, height=yVal)
        else:
            cmds.playblast(f=fileName, percent=quality, offScreen=True, format="qt", width=xVal, height=yVal)
        cmds.deleteUI("PBQuality")
        os.chmod(fileName+ ".mov", 0777)
        reviewcmd = "cd " + playblastdir + "; dpacreatereview " + baseFileName + ".mov " +  str(create_action.product_repr.spec)
        print "creating review: " + reviewcmd
        os.system( reviewcmd )
        os.system( "vlc " + fileName + ".mov &" )
        return True

    cmds.error("Invalid selections.")
    return False

<|endoftext|>


<commit_before>from django.contrib.auth.tests.basic import BASIC_TESTS
from django.contrib.auth.tests.views \
        import PasswordResetTest, ChangePasswordTest, LoginTest, LogoutTest
from django.contrib.auth.tests.forms import FORM_TESTS
from django.contrib.auth.tests.remote_user \
        import RemoteUserTest, RemoteUserNoCreateTest, RemoteUserCustomTest
from django.contrib.auth.tests.tokens import TOKEN_GENERATOR_TESTS

# The password for the fixture data users is 'password'

__test__ = {
    'BASIC_TESTS': BASIC_TESTS,
    'PASSWORDRESET_TESTS': PasswordResetTest,
    'FORM_TESTS': FORM_TESTS,
    'TOKEN_GENERATOR_TESTS': TOKEN_GENERATOR_TESTS,
    'CHANGEPASSWORD_TESTS': ChangePasswordTest,
    'LOGIN_TESTS': LoginTest,
    'LOGOUT_TESTS': LogoutTest,
}
<commit_msg>Removed unnecessary keys in django.contrib.auth.test.__test__<commit_after>from django.contrib.auth.tests.basic import BASIC_TESTS
from django.contrib.auth.tests.views \
        import PasswordResetTest, ChangePasswordTest, LoginTest, LogoutTest
from django.contrib.auth.tests.forms import FORM_TESTS
from django.contrib.auth.tests.remote_user \
        import RemoteUserTest, RemoteUserNoCreateTest, RemoteUserCustomTest
from django.contrib.auth.tests.tokens import TOKEN_GENERATOR_TESTS

# The password for the fixture data users is 'password'

__test__ = {
    'BASIC_TESTS': BASIC_TESTS,
    'FORM_TESTS': FORM_TESTS,
    'TOKEN_GENERATOR_TESTS': TOKEN_GENERATOR_TESTS,
}
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# ***********************************
#  Author: Pedro Jorge De Los Santos
#  E-mail: delossantosmfq@gmail.com
#  Web: labdls.blogspot.mx
#  License: MIT License
# ***********************************
#~ """
#~ The graph module contains functions for
#~ plot displacements, stress, strains and
#~ other outputs from analysis.
#~ """
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import matplotlib.patches as patches
import matplotlib.collections as collections

class GSpring(lines.Line2D):
    def __init__(self,init,**kwargs):
        lines.Line2D.__init__(self,[],[],**kwargs)
        self.xdata = np.array([0,1/5.0,2/5.,3/5.,4/5.,1])+init
        self.ydata = np.array([0,0,0.05,-0.05,0,0])
        # Set data
        self.set_xdata(self.xdata)
        self.set_ydata(self.ydata)
        #self.set_linestyle("-") #Solid line

class GFixedNode(collections.PatchCollection):
    def __init__(self,xcoord,ycoord,**kwargs):
        collections.PatchCollection.__init__(self,[],**kwargs)
        tol = 0.02
        _xdata1 = np.array([xcoord-tol,xcoord,xcoord+tol])
        _ydata1 = np.array([ycoord-tol,ycoord,ycoord-tol])
        _xdata2 = np.array([xcoord-tol,xcoord,xcoord-tol])
        _ydata2 = np.array([ycoord-tol,ycoord,ycoord+tol])
        # Polygons
        p1 = patches.Polygon(zip(_xdata1,_ydata1))
        p1.set_color("r")
        p2 = patches.Polygon(zip(_xdata2,_ydata2))
        #print p1,p2
        #p2.set_color("g")
        # Set data
        self.set_paths((p1,p2))
        self.set_color("k")
        #self.set_marker("-")
        #self.set_mfc('r')
        #self.set_ms(10)

def plot_spring_model(model):
    GRAPH_TOL = 0.1
    fig = plt.figure()
    ax = fig.add_subplot(111)

    for k in model.elements.keys():
        ax.add_line(GSpring(k))

    #~ # BCs
    for k,v in model.U.items():
        if v==0:
            ax.add_collection(GFixedNode(k,0))

    max_x = len(model.elements)
    max_y = 0.2
    ax.set_xlim(-GRAPH_TOL, max_x+GRAPH_TOL)
    ax.set_ylim(-max_y,max_y)
    fig.savefig('this.png')
    plt.show()

if __name__ == '__main__':
    pass
<commit_msg>For plotting of truss elements<commit_after># -*- coding: utf-8 -*-
# ***********************************
#  Author: Pedro Jorge De Los Santos
#  E-mail: delossantosmfq@gmail.com
#  Web: labdls.blogspot.mx
#  License: MIT License
# ***********************************
#~ """
#~ The graph module contains functions for
#~ plot displacements, stress, strains and
#~ other outputs from analysis.
#~ """
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import matplotlib.patches as patches
import matplotlib.collections as collections

class GSpring(lines.Line2D):
    def __init__(self,init,**kwargs):
        lines.Line2D.__init__(self,[],[],**kwargs)
        self.xdata = np.array([0,1/5.0,2/5.,3/5.,4/5.,1])+init
        self.ydata = np.array([0,0,0.05,-0.05,0,0])
        # Set data
        self.set_xdata(self.xdata)
        self.set_ydata(self.ydata)
        #self.set_linestyle("-") #Solid line

class GFixedNode(collections.PatchCollection):
    def __init__(self,xcoord,ycoord,**kwargs):
        collections.PatchCollection.__init__(self,[],**kwargs)
        tol = 0.02
        _xdata1 = np.array([xcoord-tol,xcoord,xcoord+tol])
        _ydata1 = np.array([ycoord-tol,ycoord,ycoord-tol])
        _xdata2 = np.array([xcoord-tol,xcoord,xcoord-tol])
        _ydata2 = np.array([ycoord-tol,ycoord,ycoord+tol])
        # Polygons
        p1 = patches.Polygon(zip(_xdata1,_ydata1))
        p1.set_color("r")
        p2 = patches.Polygon(zip(_xdata2,_ydata2))
        #print p1,p2
        #p2.set_color("g")
        # Set data
        self.set_paths((p1,p2))
        self.set_color("k")
        #self.set_marker("-")
        #self.set_mfc('r')
        #self.set_ms(10)

def plot_spring_model(model):
    GRAPH_TOL = 0.1
    fig = plt.figure()
    ax = fig.add_subplot(111)

    for k in model.elements.keys():
        ax.add_line(GSpring(k))

    #~ # BCs
    for k,v in model.U.items():
        if v==0:
            ax.add_collection(GFixedNode(k,0))

    max_x = len(model.elements)
    max_y = 0.2
    ax.set_xlim(-GRAPH_TOL, max_x+GRAPH_TOL)
    ax.set_ylim(-max_y,max_y)
    #~ fig.savefig('this.png')
    plt.show()

def plot_truss_model(model):
    fig = plt.figure()
    ax = fig.add_subplot(111)

    for node in model.nodes.values():
        ax.plot(node.x, node.y, "ko")

    for element in model.elements.values():
        na, nb = element.getNodes()
        xx = [model.nodes[na.label].x, model.nodes[nb.label].x]
        yy = [model.nodes[na.label].y, model.nodes[nb.label].y]
        ax.plot(xx, yy, color="#5050dd")

    minx, maxx = xlim(model)
    miny, maxy = ylim(model)
    tolx = (maxx-minx)/10.0
    toly = (maxy-miny)/10.0
    ax.set_xlim(minx - tolx, maxx + tolx)
    ax.set_ylim(miny - toly, maxy + toly)
    plt.show()

def xlim(model):
    xcoords = [node.x for node in model.nodes.values()]
    return (min(xcoords),max(xcoords))

def ylim(model):
    ycoords = [node.y for node in model.nodes.values()]
    return (min(ycoords),max(ycoords))

if __name__ == '__main__':
    pass
<|endoftext|>


<commit_before>__version__ = '1.0rc2'
<commit_msg>bump version to 1.0<commit_after>__version__ = '1.0'
<|endoftext|>


<commit_before>from __future__ import absolute_import
from __future__ import print_function
from dpark.serialize import load_func, dump_func
import sys
import operator
from six.moves import range

if sys.version_info[0] < 3:
    def next_func(it):
        return it.next
else:
    def next_func(it):
        return it.__next__

class HeapOnKey(object):

    def __init__(self, key=None, min_heap=False):
        self.key = key
        self.min_heap = min_heap
        self._setup_cmp()

    def _setup_cmp(self):
        key = self.key
        min_heap = self.min_heap

        def _ge0(x, y):
            return not (x < y)

        def _lt(x, y):
            return key(x) < key(y)

        def _ge(x, y):
            return not (key(x) < key(y))

        if key is None:
            self.cmp_lt = operator.lt if min_heap else _ge0
        else:
            self.cmp_lt = _lt if min_heap else _ge

    def __getstate__(self):
        return dump_func(self.key), self.min_heap

    def __setstate__(self, state):
        key_f, self.min_heap = state
        self.key = load_func(key_f)
        self._setup_cmp()

    def push(self, heap, item):
        heap.append(item)
        self._sift_down(heap, 0, len(heap) - 1)

    def pop(self, heap):
        last_item = heap.pop()
        if heap:
            ret_item = heap[0]
            heap[0] = last_item
            self._sift_up(heap, 0)
        else:
            ret_item = last_item
        return ret_item

    def push_pop(self, heap, item):
        if heap and self.cmp_lt(heap[0], item):
            item, heap[0] = heap[0], item
            self._sift_up(heap, 0)
        return item

    def heapify(self, heap):
        n = len(heap)
        for i in range(n // 2 - 1, -1, -1):
            self._sift_up(heap, i)

    def _sift_down(self, heap, start_pos, pos):
        new_item = heap[pos]
        cmp_lt = self.cmp_lt
        while pos > start_pos:
            parent_pos = (pos - 1) >> 1
            parent = heap[parent_pos]
            if cmp_lt(new_item, parent):
                heap[pos] = parent
                pos = parent_pos
                continue
            break
        heap[pos] = new_item

    def _sift_up(self, heap, pos):
        end_pos = len(heap)
        child_pos = 2 * pos + 1
        cmp_lt = self.cmp_lt
        while child_pos < end_pos:
            right_pos = child_pos + 1
            if right_pos < end_pos and not cmp_lt(heap[child_pos], heap[right_pos]):
                child_pos = right_pos
            if cmp_lt(heap[pos], heap[child_pos]):
                break
            heap[pos], heap[child_pos] = heap[child_pos], heap[pos]
            pos = child_pos
            child_pos = 2 * pos + 1

    def replace(self, heap, item):
        returnitem = heap[0]  # raises appropriate IndexError if heap is empty
        heap[0] = item
        self._sift_up(heap, 0)
        return returnitem

    def merge(self, iterables, ordered_iters=0):
        """iterables: each is sorted
           ordered_iters: when come to equal value, the element in the first iter yields
                first(last) if ordered_iters >(<) 0
                not stable if ordered_iters == 0
        """
        if not ordered_iters:

            def key(x):
                return self.key(x[0])
        else:

            def key(x):
                return self.key(x[0]), x[1]

        heap = HeapOnKey(key, self.min_heap)
        _heappop, _heapreplace, _StopIteration = heap.pop, heap.replace, StopIteration
        _len = len

        h = []
        h_append = h.append
        order = -1 if ordered_iters and ((ordered_iters > 0) ^ self.min_heap) else 1

        for it_idx, it in enumerate(map(iter, iterables)):
            try:
                _next = next_func(it)
                h_append([_next(), order * it_idx, _next])
            except _StopIteration:
                pass
        heap.heapify(h)

        while _len(h) > 1:
            try:
                while 1:
                    v, _, _next = s = h[0]
                    yield v
                    s[0] = _next()  # raises StopIteration when exhausted
                    _heapreplace(h, s)  # restore heap condition
            except _StopIteration:
                _heappop(h)  # remove empty iterator
        if h:
            # fast case when only a single iterator remains
            v, _, _next = h[0]
            yield v
            for v in _next.__self__:
                yield v

def test():
    l = [10, 9, 20, 18, 3, 24, 29, 39]
    h = HeapOnKey()
    h.heapify(l)
    import sys
    print('the list after heapify:', l, file=sys.stderr)
    l.pop()
    l[0] = 12
    h._sift_up(l, 0)
    print('the list after sift up:', l, file=sys.stderr)
    h.push(l, 8)
    print('the list after push:', l, file=sys.stderr)
    ret = h.pop(l)
    print('the list after pop:', l, ' with value:', ret, file=sys.stderr)
    h = HeapOnKey(min_heap=True)
    h.heapify(l)
    h.push(l, 12)
    print('the list after reverse:', l, file=sys.stderr)

    class Foo:
        def __init__(self, name='', age=0, score=None):
            self.name = name
            self.age = age
            self.score = score

        def __getstate__(self):
            return self.name, self.age, self.score

        def __setstate__(self, state):
            self.name, self.age, self.score = state

        def __repr__(self):
            return '(name:' + self.name + ', age:' + str(self.age) + ', score(%d, %d, %d))' % self.score

    def key_func(foo):
        return foo.age

    l = [Foo('aaa', 10, (60, 89, 70)), Foo('bbb', 20, (78, 75, 60)),
         Foo('ccc', 15, (60, 73, 84)), Foo('ddd', 21, (87, 64, 65)),
         Foo('eee', 30, (54, 53, 79)), Foo('fff', 10, (87, 73, 98))]
    h = HeapOnKey(key=key_func, min_heap=True)
    h.heapify(l)
    print('the list after heapify:', l, file=sys.stderr)

    len_l = 100000
    top_n = 10
    l = []
    import random
    for i in range(len_l):
        l.append(random.randint(1, 2 * len_l + 1))

    top_l = []
    call_cnt = 0

    def cnt_key(x):
        global call_cnt
        call_cnt += 1
        return x

    h = HeapOnKey(key=cnt_key)
    import time
    start = time.time()
    for i in l:
        if len(top_l) >= top_n:
            h.push_pop(top_l, i)
        else:
            h.push(top_l, i)
    top_l.sort(key=cnt_key)
    print('after heap:', top_l, ' with elapsed:', time.time() - start, ' with cnt:', call_cnt / 2, file=sys.stderr)
    call_cnt = 0

    start = time.time()
    top_l = []
    for i in l:
        top_l.append(i)
        top_l.sort(key=cnt_key)
        if len(top_l) > top_n:
            top_l.pop()

    print('after sort:', top_l, ' with elapsed:', time.time() - start, ' with cnt:', call_cnt / 2, file=sys.stderr)

if __name__ == '__main__':
    test()
<commit_msg>Fix bad name: l -> lst<commit_after>from __future__ import absolute_import
from __future__ import print_function
from dpark.serialize import load_func, dump_func
import sys
import operator
from six.moves import range

if sys.version_info[0] < 3:
    def next_func(it):
        return it.next
else:
    def next_func(it):
        return it.__next__

class HeapOnKey(object):

    def __init__(self, key=None, min_heap=False):
        self.key = key
        self.min_heap = min_heap
        self._setup_cmp()

    def _setup_cmp(self):
        key = self.key
        min_heap = self.min_heap

        def _ge0(x, y):
            return not (x < y)

        def _lt(x, y):
            return key(x) < key(y)

        def _ge(x, y):
            return not (key(x) < key(y))

        if key is None:
            self.cmp_lt = operator.lt if min_heap else _ge0
        else:
            self.cmp_lt = _lt if min_heap else _ge

    def __getstate__(self):
        return dump_func(self.key), self.min_heap

    def __setstate__(self, state):
        key_f, self.min_heap = state
        self.key = load_func(key_f)
        self._setup_cmp()

    def push(self, heap, item):
        heap.append(item)
        self._sift_down(heap, 0, len(heap) - 1)

    def pop(self, heap):
        last_item = heap.pop()
        if heap:
            ret_item = heap[0]
            heap[0] = last_item
            self._sift_up(heap, 0)
        else:
            ret_item = last_item
        return ret_item

    def push_pop(self, heap, item):
        if heap and self.cmp_lt(heap[0], item):
            item, heap[0] = heap[0], item
            self._sift_up(heap, 0)
        return item

    def heapify(self, heap):
        n = len(heap)
        for i in range(n // 2 - 1, -1, -1):
            self._sift_up(heap, i)

    def _sift_down(self, heap, start_pos, pos):
        new_item = heap[pos]
        cmp_lt = self.cmp_lt
        while pos > start_pos:
            parent_pos = (pos - 1) >> 1
            parent = heap[parent_pos]
            if cmp_lt(new_item, parent):
                heap[pos] = parent
                pos = parent_pos
                continue
            break
        heap[pos] = new_item

    def _sift_up(self, heap, pos):
        end_pos = len(heap)
        child_pos = 2 * pos + 1
        cmp_lt = self.cmp_lt
        while child_pos < end_pos:
            right_pos = child_pos + 1
            if right_pos < end_pos and not cmp_lt(heap[child_pos], heap[right_pos]):
                child_pos = right_pos
            if cmp_lt(heap[pos], heap[child_pos]):
                break
            heap[pos], heap[child_pos] = heap[child_pos], heap[pos]
            pos = child_pos
            child_pos = 2 * pos + 1

    def replace(self, heap, item):
        returnitem = heap[0]  # raises appropriate IndexError if heap is empty
        heap[0] = item
        self._sift_up(heap, 0)
        return returnitem

    def merge(self, iterables, ordered_iters=0):
        """iterables: each is sorted
           ordered_iters: when come to equal value, the element in the first iter yields
                first(last) if ordered_iters >(<) 0
                not stable if ordered_iters == 0
        """
        if not ordered_iters:

            def key(x):
                return self.key(x[0])
        else:

            def key(x):
                return self.key(x[0]), x[1]

        heap = HeapOnKey(key, self.min_heap)
        _heappop, _heapreplace, _StopIteration = heap.pop, heap.replace, StopIteration
        _len = len

        h = []
        h_append = h.append
        order = -1 if ordered_iters and ((ordered_iters > 0) ^ self.min_heap) else 1

        for it_idx, it in enumerate(map(iter, iterables)):
            try:
                _next = next_func(it)
                h_append([_next(), order * it_idx, _next])
            except _StopIteration:
                pass
        heap.heapify(h)

        while _len(h) > 1:
            try:
                while 1:
                    v, _, _next = s = h[0]
                    yield v
                    s[0] = _next()  # raises StopIteration when exhausted
                    _heapreplace(h, s)  # restore heap condition
            except _StopIteration:
                _heappop(h)  # remove empty iterator
        if h:
            # fast case when only a single iterator remains
            v, _, _next = h[0]
            yield v
            for v in _next.__self__:
                yield v

def test():
    lst = [10, 9, 20, 18, 3, 24, 29, 39]
    h = HeapOnKey()
    h.heapify(lst)
    import sys
    print('the list after heapify:', lst, file=sys.stderr)
    lst.pop()
    lst[0] = 12
    h._sift_up(lst, 0)
    print('the list after sift up:', lst, file=sys.stderr)
    h.push(lst, 8)
    print('the list after push:', lst, file=sys.stderr)
    ret = h.pop(lst)
    print('the list after pop:', lst, ' with value:', ret, file=sys.stderr)
    h = HeapOnKey(min_heap=True)
    h.heapify(lst)
    h.push(lst, 12)
    print('the list after reverse:', lst, file=sys.stderr)

    class Foo:
        def __init__(self, name='', age=0, score=None):
            self.name = name
            self.age = age
            self.score = score

        def __getstate__(self):
            return self.name, self.age, self.score

        def __setstate__(self, state):
            self.name, self.age, self.score = state

        def __repr__(self):
            return '(name:' + self.name + ', age:' + str(self.age) + ', score(%d, %d, %d))' % self.score

    def key_func(foo):
        return foo.age

    lst = [Foo('aaa', 10, (60, 89, 70)), Foo('bbb', 20, (78, 75, 60)),
           Foo('ccc', 15, (60, 73, 84)), Foo('ddd', 21, (87, 64, 65)),
           Foo('eee', 30, (54, 53, 79)), Foo('fff', 10, (87, 73, 98))]
    h = HeapOnKey(key=key_func, min_heap=True)
    h.heapify(lst)
    print('the list after heapify:', lst, file=sys.stderr)

    len_l = 100000
    top_n = 10
    lst = []
    import random
    for i in range(len_l):
        lst.append(random.randint(1, 2 * len_l + 1))

    top_l = []
    call_cnt = 0

    def cnt_key(x):
        global call_cnt
        call_cnt += 1
        return x

    h = HeapOnKey(key=cnt_key)
    import time
    start = time.time()
    for i in lst:
        if len(top_l) >= top_n:
            h.push_pop(top_l, i)
        else:
            h.push(top_l, i)
    top_l.sort(key=cnt_key)
    print('after heap:', top_l, ' with elapsed:', time.time() - start, ' with cnt:', call_cnt / 2, file=sys.stderr)
    call_cnt = 0

    start = time.time()
    top_l = []
    for i in lst:
        top_l.append(i)
        top_l.sort(key=cnt_key)
        if len(top_l) > top_n:
            top_l.pop()

    print('after sort:', top_l, ' with elapsed:', time.time() - start, ' with cnt:', call_cnt / 2, file=sys.stderr)

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